Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2002 Prentice Hall. All rights reserved. Chapter 16: Messaging with JMS Outline 16.1 Introduction 16.2 Installation and Configuration of J2EE 1.3 16.3.

Similar presentations


Presentation on theme: " 2002 Prentice Hall. All rights reserved. Chapter 16: Messaging with JMS Outline 16.1 Introduction 16.2 Installation and Configuration of J2EE 1.3 16.3."— Presentation transcript:

1  2002 Prentice Hall. All rights reserved. Chapter 16: Messaging with JMS Outline 16.1 Introduction 16.2 Installation and Configuration of J2EE 1.3 16.3 Point-To-Point Messaging 16.3.1 Voter Application: Overview 16.3.2 Voter Application: Sender Side 16.3.3 Voter Application: Receiver Side| 16.3.4 Voter Application: Configuring and Running 16.4 Publish/Subscribe Messaging 16.4.1 Weather Application: Overview 16.4.2 Weather Application: Publisher Side 16.4.3 Weather Application: Subscriber Side 16.4.4 Weather Application: Configuring and Running 16.5 Message-Driven Enterprise JavaBeans 16.5.1 Voter Application: Overview 16.5.2 Voter Application: Receiver Side\ 16.5.3 Voter Application: Configuring and Running

2  2002 Prentice Hall. All rights reserved. 16.1 Introduction Message-oriented middleware –enables components to post messages for other components –two types point-to-point messaging model –components send messages to message queue messages sent to one consumer publish/subscribe messaging model –components publish message to topic on server multiple subscribers receive message for given topic

3  2002 Prentice Hall. All rights reserved. 16.1 Introduction (cont.) Message –composed of header –message destination –sending time properties (optional) –server determines type of message being sent –clients helps determine what messages to receive body –content of message

4  2002 Prentice Hall. All rights reserved. 16.1 Introduction (cont.) –composed of 5 types 1.BytesMessages 2.MapMessages 3.ObjectMessages 4.StreamMessages 5.TextMessages Message-driven beans –Enterprise JavaBeans that support messaging –EJB container uses any message-driven bean for given topic message-driven beans cannot maintain clients state –enable components to receive messages asynchronously

5  2002 Prentice Hall. All rights reserved. 16.2 Installation and Configuration of J2EE 1.3 Steps for installing J2EE 1.3 –download and unpack appropriate software bundle http://java.sun.com/j2ee/j2sdkee-beta/index.html –set environment variables according to Fig. 16.1

6  2002 Prentice Hall. All rights reserved. 16.2 Installation and Configuration of J2EE 1.3 (cont.)

7  2002 Prentice Hall. All rights reserved. 16.3 Point-To-Point Messaging Allows clients send messages to message queue. –receiver connects to queue to consume non-consumed messages Messages intended for one receiver. Messages stored in queue until client consumes messages.

8  2002 Prentice Hall. All rights reserved. 16.3 Point-To-Point Messaging (cont.) Fig. 16.2Point-to-point messaging model.

9  2002 Prentice Hall. All rights reserved. 16.3.1 Voter Application: Overview Tallies votes to favorite computer languages. Class Voter –sends votes as messages to Votes queue messages are simple TextMessage objects –body contains candidate name Class VoteCollector –consumes messages and tallies votes –updates display

10  2002 Prentice Hall. All rights reserved. 16.3.1 Voter Application: Overview (cont.) Fig. 16.3Voter application overview.

11  2002 Prentice Hall. All rights reserved. 16.3.2 Voter Application: Sender Side Consists of single class, Voter. –allows user to select programming language –sends vote to Votes queue

12  2002 Prentice Hall. All rights reserved. Outline Fig. 16.4 Voter class submits votes as messages to queue. Line 13 1 // Voter.java 2 // Voter is the GUI that allows the client to vote 3 // for a programming language. Voter sends the vote 4 // to the "Votes" queue as a TextMessage. 5 package com.deitel.advjhtp1.jms.voter; 6 7 // Java core packages 8 import java.awt.*; 9 import java.awt.event.*; 10 11 // Java extension packages 12 import javax.swing.*; 13 import javax.jms.*; 14 import javax.naming.*; 15 16 public class Voter extends JFrame { 17 18 private String selectedLanguage; 19 20 // JMS variables 21 private QueueConnection queueConnection; 22 private QueueSession queueSession; 23 private QueueSender queueSender; 24 25 // Voter constructor 26 public Voter() 27 { 28 // lay out user interface 29 super( "Voter" ); 30 31 Container container = getContentPane(); 32 container.setLayout( new BorderLayout() ); 33 contains JMS API classes and interfaces

13  2002 Prentice Hall. All rights reserved. Outline Fig. 16.4 Voter class submits votes as messages to queue. 34 JTextArea voteArea = 35 new JTextArea( "Please vote for your\n" + 36 "favorite programming language" ); 37 voteArea.setEditable( false ); 38 container.add( voteArea, BorderLayout.NORTH ); 39 40 JPanel languagesPanel = new JPanel(); 41 languagesPanel.setLayout( new GridLayout( 0, 1 ) ); 42 43 // add each language as its own JCheckBox 44 // ButtonGroup ensures exactly one language selected 45 ButtonGroup languagesGroup = new ButtonGroup(); 46 CheckBoxHandler checkBoxHandler = new CheckBoxHandler(); 47 String languages[] = 48 { "C", "C++", "Java", "Lisp", "Python" }; 49 selectedLanguage = ""; 50 51 // create JCheckBox for each language 52 // and add to ButtonGroup and JPanel 53 for ( int i = 0; i < languages.length; i++ ) { 54 JCheckBox checkBox = new JCheckBox( languages[ i ] ); 55 checkBox.addItemListener( checkBoxHandler ); 56 languagesPanel.add( checkBox ); 57 languagesGroup.add( checkBox ); 58 } 59 60 container.add( languagesPanel, BorderLayout.CENTER ); 61 62 // create button to submit vote 63 JButton submitButton = new JButton( "Submit vote!" ); 64 container.add( submitButton, BorderLayout.SOUTH ); 65

14  2002 Prentice Hall. All rights reserved. Outline Fig. 16.4 Voter class submits votes as messages to queue. Line 92 Lines 96-100 66 // invoke method submitVote when submitButton clicked 67 submitButton.addActionListener ( 68 69 new ActionListener() { 70 71 public void actionPerformed ( ActionEvent event ) { 72 submitVote(); 73 } 74 } 75 ); 76 77 // invoke method quit when window closed 78 addWindowListener( 79 80 new WindowAdapter() { 81 82 public void windowClosing( WindowEvent event ) { 83 quit(); 84 } 85 } 86 ); 87 88 // connect to message queue 89 try { 90 91 // create JNDI context 92 Context jndiContext = new InitialContext(); 93 94 // retrieve queue connection factory and 95 // queue from JNDI context 96 QueueConnectionFactory queueConnectionFactory = 97 ( QueueConnectionFactory ) 98 jndiContext.lookup( "VOTE_FACTORY" ); 99 Queue queue = ( Queue ) jndiContext.lookup( "Votes" ); 100 create JNDI contextserver administrator responsible for creating queue connection factory and queue

15  2002 Prentice Hall. All rights reserved. Outline Fig. 16.4 Voter class submits votes as messages to queue. Lines 102-103 Lines 104-106 Lines 107 Lines 131-132 Line 133 101 // create connection, session and sender 102 queueConnection = 103 queueConnectionFactory.createQueueConnection(); 104 queueSession = 105 queueConnection.createQueueSession( false, 106 Session.AUTO_ACKNOWLEDGE ); 107 queueSender = queueSession.createSender( queue ); 108 } 109 110 // process Naming exception from JNDI context 111 catch ( NamingException namingException ) { 112 namingException.printStackTrace(); 113 System.exit( 1 ); 114 } 115 116 // process JMS exception from queue connection or session 117 catch ( JMSException jmsException ) { 118 jmsException.printStackTrace(); 119 System.exit( 1 ); 120 } 121 122 } // end Voter constructor 123 124 // submit selected vote to "Votes" queue as TextMessage 125 public void submitVote() 126 { 127 if ( selectedLanguage != "" ) { 128 129 // create text message containing selected language 130 try { 131 TextMessage voteMessage = 132 queueSession.createTextMessage(); 133 voteMessage.setText( selectedLanguage ); 134 create QueueConnection create QueueSession post messages through QueueSender instance message instanceset body of message

16  2002 Prentice Hall. All rights reserved. Outline Fig. 16.4 Voter class submits votes as messages to queue. Line 136 Line 154 135 // send the message to the queue 136 queueSender.send( voteMessage ); 137 } 138 139 // process JMS exception 140 catch ( JMSException jmsException ) { 141 jmsException.printStackTrace(); 142 } 143 } 144 145 } // end method submitVote 146 147 // close client application 148 public void quit() 149 { 150 if ( queueConnection != null ) { 151 152 // close queue connection if it exists 153 try { 154 queueConnection.close(); 155 } 156 157 // process JMS exception 158 catch ( JMSException jmsException ) { 159 jmsException.printStackTrace(); 160 } 161 } 162 163 System.exit( 0 ); 164 165 } // end method quit 166 send message close connection to queue

17  2002 Prentice Hall. All rights reserved. Outline Fig. 16.4 Voter class submits votes as messages to queue. 167 // launch Voter application 168 public static void main( String args[] ) 169 { 170 Voter voter = new Voter(); 171 voter.pack(); 172 voter.setVisible( true ); 173 } 174 175 // CheckBoxHandler handles event when checkbox checked 176 private class CheckBoxHandler implements ItemListener { 177 178 // checkbox event 179 public void itemStateChanged( ItemEvent event ) 180 { 181 // update selectedLanguage 182 JCheckBox source = ( JCheckBox ) event.getSource(); 183 selectedLanguage = source.getText(); 184 } 185 } 186 }

18  2002 Prentice Hall. All rights reserved. 16.3.2 Voter Application: Sender Side (cont.) Fig. 16.5Voter application votes for favorite programming language

19  2002 Prentice Hall. All rights reserved. 16.3.3 Voter Application: Receiver Side Class VoteCollector intended receiver –tallies and displays votes Votes queue can be populated before VoteCollector connects.

20  2002 Prentice Hall. All rights reserved. Outline Fig. 16.6 VoteCollector class retrieves and tallies votes. 1 // VoteCollector.java 2 // VoteCollector tallies and displays the votes 3 // posted as TextMessages to the "Votes" queue. 4 package com.deitel.advjhtp1.jms.voter; 5 6 // Java core packages 7 import java.awt.*; 8 import java.awt.event.*; 9 import java.util.*; 10 11 // Java extension packages 12 import javax.swing.*; 13 import javax.jms.*; 14 import javax.naming.*; 15 16 public class VoteCollector extends JFrame { 17 18 private JPanel displayPanel; 19 private Map tallies = new HashMap(); 20 21 // JMS variables 22 private QueueConnection queueConnection; 23 24 // VoteCollector constructor 25 public VoteCollector() 26 { 27 super( "Vote Tallies" ); 28 29 Container container = getContentPane(); 30 31 // displayPanel will display tally results 32 displayPanel = new JPanel(); 33 displayPanel.setLayout( new GridLayout( 0, 1 ) ); 34 container.add( new JScrollPane( displayPanel ) ); 35

21  2002 Prentice Hall. All rights reserved. Outline Fig. 16.6 VoteCollector class retrieves and tallies votes. Line 51 Lines 55-57 Lines 61-65 Lines 66-67 36 // invoke method quit when window closed 37 addWindowListener( 38 39 new WindowAdapter() { 40 41 public void windowClosing( WindowEvent event ) { 42 quit(); 43 } 44 } 45 ); 46 47 // connect to "Votes" queue 48 try { 49 50 // create JNDI context 51 Context jndiContext = new InitialContext(); 52 53 // retrieve queue connection factory 54 // and queue from JNDI context 55 QueueConnectionFactory queueConnectionFactory = 56 ( QueueConnectionFactory ) 57 jndiContext.lookup( "VOTE_FACTORY" ); 58 Queue queue = ( Queue ) jndiContext.lookup( "Votes" ); 59 60 // create connection, session and receiver 61 queueConnection = 62 queueConnectionFactory.createQueueConnection(); 63 QueueSession queueSession = 64 queueConnection.createQueueSession( false, 65 Session.AUTO_ACKNOWLEDGE ); 66 QueueReceiver queueReceiver = 67 queueSession.createReceiver( queue ); 68 create JNDI contextget queue connection factory create QueueSession create votes receiver

22  2002 Prentice Hall. All rights reserved. Outline Fig. 16.6 VoteCollector class retrieves and tallies votes. Lines 70-71 Lines 74 Lines 92-109 69 // initialize and set message listener 70 queueReceiver.setMessageListener( 71 new VoteListener( this ) ); 72 73 // start connection 74 queueConnection.start(); 75 } 76 77 // process Naming exception from JNDI context 78 catch ( NamingException namingException ) { 79 namingException.printStackTrace(); 80 System.exit( 1 ); 81 } 82 83 // process JMS exception from queue connection or session 84 catch ( JMSException jmsException ) { 85 jmsException.printStackTrace(); 86 System.exit( 1 ); 87 } 88 89 } // end VoteCollector constructor 90 91 // add vote to corresponding tally 92 public void addVote( String vote ) 93 { 94 if ( tallies.containsKey( vote ) ) { 95 96 // if vote already has corresponding tally 97 TallyPanel tallyPanel = 98 ( TallyPanel ) tallies.get( vote ); 99 tallyPanel.updateTally(); 100 } 101 register listener activate connectionupdates tallies and display. Callback method for VoteListener instance

23  2002 Prentice Hall. All rights reserved. Outline Fig. 16.6 VoteCollector class retrieves and tallies votes. Line 118 102 // add to GUI and tallies 103 else { 104 TallyPanel tallyPanel = new TallyPanel( vote, 1 ); 105 displayPanel.add( tallyPanel ); 106 tallies.put( vote, tallyPanel ); 107 validate(); 108 } 109 } 110 111 // quit application 112 public void quit() 113 { 114 if ( queueConnection != null ) { 115 116 // close the queue connection if it exists 117 try { 118 queueConnection.close(); 119 } 120 121 // process JMS exception 122 catch ( JMSException jmsException ) { 123 jmsException.printStackTrace(); 124 System.exit( 1 ); 125 } 126 127 } 128 129 System.exit( 0 ); 130 131 } // end method quit 132 close queue connection

24  2002 Prentice Hall. All rights reserved. Outline Fig. 16.6 VoteCollector class retrieves and tallies votes. 133 // launch VoteCollector 134 public static void main( String args[] ) 135 { 136 VoteCollector voteCollector = new VoteCollector(); 137 voteCollector.setSize( 200, 200 ); 138 voteCollector.setVisible( true ); 139 } 140 }

25  2002 Prentice Hall. All rights reserved. 16.3.3 Voter Application: Receiver Side (cont.) Fig. 16.7 VoteCollector tallies and displays votes.

26  2002 Prentice Hall. All rights reserved. Outline Fig. 16.8 VoteListener class receives messages from the queue. Line 11 Line 29 Line 32 1 // VoteListener.java 2 // VoteListener is the message listener for the 3 // receiver of the "Votes" queue. It implements 4 // the specified onMessage method to update the 5 // GUI with the received vote. 6 package com.deitel.advjhtp1.jms.voter; 7 8 // Java extension packages 9 import javax.jms.*; 10 11 public class VoteListener implements MessageListener { 12 13 private VoteCollector voteCollector; 14 15 // VoteListener constructor 16 public VoteListener( VoteCollector collector ) 17 { 18 voteCollector = collector; 19 } 20 21 // receive new message 22 public void onMessage( Message message ) 23 { 24 TextMessage voteMessage; 25 26 // retrieve and process message 27 try { 28 29 if ( message instanceof TextMessage ) { 30 voteMessage = ( TextMessage ) message; 31 String vote = voteMessage.getText(); 32 voteCollector.addVote( vote ); 33 34 System.out.println( "Received vote: " + vote ); 35 } implements MessageListener interface ensure message of type TextMessage call back

27  2002 Prentice Hall. All rights reserved. Outline Fig. 16.8 VoteListener class receives messages from the queue. 36 37 else { 38 System.out.println( "Expecting " + 39 "TextMessage object, received " + 40 message.getClass().getName() ); 41 } 42 } 43 44 // process JMS exception from message 45 catch ( JMSException jmsException ) { 46 jmsException.printStackTrace(); 47 } 48 49 } // end method onMessage 50 }

28  2002 Prentice Hall. All rights reserved. Outline Fig. 16.9 TallyPanel class displays candidate name and tally. 1 // TallyPanel.java 2 // TallPanel is the GUI component which displays 3 // the name and tally for a vote candidate. 4 package com.deitel.advjhtp1.jms.voter; 5 6 // Java core packages 7 import java.awt.*; 8 9 // Java extension packages 10 import javax.swing.*; 11 12 public class TallyPanel extends JPanel { 13 14 private JLabel nameLabel; 15 private JTextField tallyField; 16 private String name; 17 private int tally; 18 19 // TallyPanel constructor 20 public TallyPanel( String voteName, int voteTally ) 21 { 22 name = voteName; 23 tally = voteTally; 24 25 nameLabel = new JLabel( name ); 26 tallyField = 27 new JTextField( Integer.toString( tally ), 10 ); 28 tallyField.setEditable( false ); 29 tallyField.setBackground( Color.white ); 30 31 add( nameLabel ); 32 add( tallyField ); 33 34 } // end TallyPanel constructor 35

29  2002 Prentice Hall. All rights reserved. Outline Fig. 16.9 TallyPanel class displays candidate name and tally. 36 // update tally by one vote 37 public void updateTally() 38 { 39 tally++; 40 tallyField.setText( Integer.toString( tally ) ); 41 } 42 } increments tally by one

30  2002 Prentice Hall. All rights reserved. 16.3.4 Voter Application: Configuring and Running 1.Start J2EE server j2ee –verbose 2.Create Votes queue (in new window) j2eeadmin –addJmsDestination Votes queue 3.Verify queue was created j2eeadmin –listJmsDestination 4.Create connection factory j2eeadmin –addJmsFactory VOTE_FACTORY queue 5.Start VoteCollector java –classpath %J2EE_HOME%\lib\j2ee.jar;. -Djms.properties=%J2EE_HOME%\config\jms_client.properties com.deitel.advjhtp1.jms.voter.VoteCollector 6.Start Voter (in new window) java –classpath %J2EE_HOME%\lib\j2ee.jar;. -Djms.properties=%J2EE_HOME%\config\jms_client.properties com.deitel.advjhtp1.jms.voter.Voter

31  2002 Prentice Hall. All rights reserved. 16.3.4 Voter Application: Configuring and Running (cont.) Once application finished –remove connection factory j2eeadmin –removeJmsFactory VOTE_FACTORY –remote topic j2eeadmin –removeJmsDestination Votes –stop J2EE server j2ee -stop

32  2002 Prentice Hall. All rights reserved. 16.4 Publish/Subscribe Messaging Allows multiple clients to –connect to topic on server –send messages –receive messages When client publishes message, message sent to all clients subscribed to topic. Two subscription types: 1.nondurable messages received while subscriptions active 2.durable server maintains messages while subscription inactive –server sends messages when client reactivates

33  2002 Prentice Hall. All rights reserved. 16.4 Publish/Subscribe Messaging (cont.) Fig. 16.10Publish/subscribe messaging model.

34  2002 Prentice Hall. All rights reserved. 16.4.1 Weather Application: Overview Class WeatherPublisher –retrieves weather updates from URL –publishes information as messages to topic Class WeatherSubscriber –provides GUI enables user to select desired cities –subscribes to Weather topic receives corresponding messages uses message selector

35  2002 Prentice Hall. All rights reserved. 16.4.1 Weather Application: Overview (cont.) Fig. 16.11Weather application overview.

36  2002 Prentice Hall. All rights reserved. 16.4.2 Weather Application: Publisher Side Class WeatherPublisher –retrieves weather updates from National Weather Service –publishes weather updates to Weather topic –messages of type ObjectMessage String property City specifies corresponding city

37  2002 Prentice Hall. All rights reserved. Outline Fig. 16.12 WeatherPublisher class publishes messages to Weather topic. 1 // WeatherPublisher.java 2 // WeatherPublisher retrieves weather conditions from the National 3 // Weather Service and publishes them to the Weather topic 4 // as ObjectMessages containing WeatherBeans. The city name is 5 // used in a String property "City" in the message header. 6 package com.deitel.advjhtp1.jms.weather; 7 \ 8 // Java core packages 9 import java.io.*; 10 import java.net.*; 11 import java.util.*; 12 13 // Java extension packages 14 import javax.jms.*; 15 import javax.naming.*; 16 17 // Deitel packages 18 import com.deitel.advjhtp1.rmi.weather.WeatherBean; 19 20 public class WeatherPublisher extends TimerTask { 21 22 private BufferedReader in; 23 private TopicConnection topicConnection; 24 25 // WeatherPublisher constructor 26 public WeatherPublisher() 27 { 28 // update weather conditions every minute 29 Timer timer = new Timer(); 30 timer.scheduleAtFixedRate( this, 0, 60000 ); 31 32 // allow user to quit 33 InputStreamReader inputStreamReader = 34 new InputStreamReader( System.in ); 35 char answer = '\0';

38  2002 Prentice Hall. All rights reserved. Outline Fig. 16.12 WeatherPublisher class publishes messages to Weather topic. 36 37 // loop until user enters q or Q 38 while ( !( ( answer == 'q' ) || ( answer == 'Q' ) ) ) { 39 40 // read in character 41 try { 42 answer = ( char ) inputStreamReader.read(); 43 } 44 45 // process IO exception 46 catch ( IOException ioException ) { 47 ioException.printStackTrace(); 48 System.exit( 1 ); 49 } 50 51 } // end while 52 53 // close connections 54 try { 55 56 // close topicConnection if it exists 57 if ( topicConnection != null ) { 58 topicConnection.close(); 59 } 60 61 in.close(); // close connection to NWS Web server 62 timer.cancel(); // stop timer 63 } 64 65 // process JMS exception from closing topic connection 66 catch ( JMSException jmsException ) { 67 jmsException.printStackTrace(); 68 System.exit( 1 ); 69 } 70

39  2002 Prentice Hall. All rights reserved. Outline Fig. 16.12 WeatherPublisher class publishes messages to Weather topic. Line 90 Line 95-97 Line 103-104 71 // process IO exception from closing connection 72 // to NWS Web server 73 catch ( IOException ioException ) { 74 ioException.printStackTrace(); 75 System.exit( 1 ); 76 } 77 78 System.exit( 0 ); 79 80 } // end WeatherPublisher constructor 81 82 // get weather information from NWS 83 public void run() 84 { 85 // connect to topic "Weather" 86 try { 87 System.out.println( "Update weather information..." ); 88 89 // create JNDI context 90 Context jndiContext = new InitialContext(); 91 String topicName = "Weather"; 92 93 // retrieve topic connection factory and topic 94 // from JNDI context 95 TopicConnectionFactory topicConnectionFactory = 96 ( TopicConnectionFactory ) 97 jndiContext.lookup( "WEATHER_FACTORY" ); 98 99 Topic topic = 100 ( Topic ) jndiContext.lookup( topicName ); 101 102 // create connection, session, publisher and message 103 topicConnection = 104 topicConnectionFactory.createTopicConnection(); 105 create JNDI context look up TopicConnectionFactory and Topic create TopicConnection

40  2002 Prentice Hall. All rights reserved. Outline Fig. 16.12 WeatherPublisher class publishes messages to Weather topic. Lines 106-108 Lines 110-111 Lines 113-114 106 TopicSession topicSession = 107 topicConnection.createTopicSession( false, 108 Session.AUTO_ACKNOWLEDGE ); 109 110 TopicPublisher topicPublisher = 111 topicSession.createPublisher( topic ); 112 113 ObjectMessage message = 114 topicSession.createObjectMessage(); 115 116 // connect to National Weather Service 117 // and publish conditions to topic 118 119 // National Weather Service Travelers Forecast page 120 URL url = new URL( 121 "http://iwin.nws.noaa.gov/iwin/us/traveler.html" ); 122 123 // set up text input stream to read Web page contents 124 in = new BufferedReader( 125 new InputStreamReader( url.openStream() ) ); 126 127 // helps determine starting point of data on Web page 128 String separator = "TAV12"; 129 130 // locate separator string in Web page 131 while ( !in.readLine().startsWith( separator ) ) 132 ; // do nothing 133 134 // strings representing headers on Travelers Forecast 135 // Web page for daytime and nighttime weather 136 String dayHeader = 137 "CITY WEA HI/LO WEA HI/LO"; 138 139 String nightHeader = 140 "CITY WEA LO/HI WEA LO/HI"; create TopicSession obtain TopicPublisher will contain WeatherBean objects

41  2002 Prentice Hall. All rights reserved. Outline Fig. 16.12 WeatherPublisher class publishes messages to Weather topic. Lines 165-168 Line 173 Lines 174-175 141 142 String inputLine = ""; 143 144 // locate header that begins weather information 145 do { 146 inputLine = in.readLine(); 147 } 148 149 while ( !inputLine.equals( dayHeader ) && 150 !inputLine.equals( nightHeader ) ); 151 152 // create WeatherBean objects for each city's data 153 // publish to Weather topic using city as message's type 154 inputLine = in.readLine(); // get first city's info 155 156 // the portion of inputLine containing relevant data is 157 // 28 characters long. If the line length is not at 158 // least 28 characters long, done processing data. 159 while ( inputLine.length() > 28 ) { 160 161 // create WeatherBean object for city 162 // first 16 characters are city name 163 // next six characters are weather description 164 // next six characters are HI/LO temperature 165 WeatherBean weather = new WeatherBean( 166 inputLine.substring( 0, 16 ).trim(), 167 inputLine.substring( 16, 22 ).trim(), 168 inputLine.substring( 23, 29 ).trim() ); 169 170 // publish WeatherBean object with city name 171 // as a message property, 172 // used for selection by clients 173 message.setObject( weather ); 174 message.setStringProperty( "City", 175 weather.getCityName() ); create WeatherBean object store WeatherBean in MessageObject set City property

42  2002 Prentice Hall. All rights reserved. Outline Fig. 16.12 WeatherPublisher class publishes messages to Weather topic. Line 176 176 topicPublisher.publish( message ); 177 178 System.out.println( "published message for city: " 179 + weather.getCityName() ); 180 181 inputLine = in.readLine(); // get next city's info 182 } 183 184 System.out.println( "Weather information updated." ); 185 186 } // end try 187 188 // process Naming exception from JNDI context 189 catch ( NamingException namingException ) { 190 namingException.printStackTrace(); 191 System.exit( 1 ); 192 } 193 194 // process JMS exception from connection, 195 // session, publisher or message 196 catch ( JMSException jmsException ) { 197 jmsException.printStackTrace(); 198 System.exit( 1 ); 199 } 200 201 // process failure to connect to National Weather Service 202 catch ( java.net.ConnectException connectException ) { 203 connectException.printStackTrace(); 204 System.exit( 1 ); 205 } 206 207 // process other exceptions 208 catch ( Exception exception ) { 209 exception.printStackTrace(); 210 System.exit( 1 ); publish message to topic

43  2002 Prentice Hall. All rights reserved. Outline Fig. 16.12 WeatherPublisher class publishes messages to Weather topic. 211 } 212 213 } // end method run 214 215 // launch WeatherPublisher 216 public static void main( String args[] ) 217 { 218 System.err.println( "Initializing server...\n" + 219 "Enter 'q' or 'Q' to quit" ); 220 221 WeatherPublisher publisher = new WeatherPublisher(); 222 } 223 }

44  2002 Prentice Hall. All rights reserved. 16.4.2 Weather Application: Publisher Side (cont.) Fig. 16.13 WeatherPublisher publishing weather update messages.

45  2002 Prentice Hall. All rights reserved. 16.4.3 Weather Application: Subscriber Side Subscribes to Weather topic. –receives weather updates for selected cities Presents GUI for user.

46  2002 Prentice Hall. All rights reserved. Outline Fig. 16.14 WeatherSubscribe r class allows user to receive weather updates. 1 // WeatherSubscriber.java 2 // WeatherSubscriber presents a GUI for the client to request 3 // weather conditions for various cities. The WeatherSubscriber 4 // retrieves the weather conditions from the Weather topic; 5 // each message body contains a WeatherBean object. The message 6 // header contains a String property "City," which allows 7 // the client to select the desired cities. 8 package com.deitel.advjhtp1.jms.weather; 9 10 // Java core packages 11 import java.awt.*; 12 import java.awt.event.*; 13 14 // Java extension packages 15 import javax.swing.*; 16 import javax.naming.*; 17 import javax.jms.*; 18 19 public class WeatherSubscriber extends JFrame { 20 21 // GUI variables 22 private WeatherDisplay weatherDisplay; 23 private JList citiesList; 24

47  2002 Prentice Hall. All rights reserved. Outline Fig. 16.14 WeatherSubscribe r class allows user to receive weather updates. Line 55 25 // cities contains cities for which weather 26 // updates are available on "Weather" topic 27 private String cities[] = { "ALBANY NY", "ANCHORAGE", 28 "ATLANTA", "ATLANTIC CITY", "BOSTON", "BUFFALO", 29 "BURLINGTON VT", "CHARLESTON WV", "CHARLOTTE", "CHICAGO", 30 "CLEVELAND", "DALLAS FT WORTH", "DENVER", "DETROIT", 31 "GREAT FALLS", "HARTFORD SPGFLD", "HONOLULU", 32 "HOUSTON INTCNTL", "KANSAS CITY", "LAS VEGAS", 33 "LOS ANGELES", "MIAMI BEACH", "MPLS ST PAUL", "NEW ORLEANS", 34 "NEW YORK CITY", "NORFOLK VA", "OKLAHOMA CITY", "ORLANDO", 35 "PHILADELPHIA", "PHOENIX", "PITTSBURGH", "PORTLAND ME", 36 "PORTLAND OR", "RENO" }; 37 38 // JMS variables 39 private TopicConnection topicConnection; 40 private TopicSession topicSession; 41 private Topic topic; 42 private TopicSubscriber topicSubscriber; 43 private WeatherListener topicListener; 44 45 // WeatherSubscriber constructor 46 public WeatherSubscriber() 47 { 48 super( "JMS WeatherSubscriber..." ); 49 weatherDisplay = new WeatherDisplay(); 50 51 // set up JNDI context and JMS connections 52 try { 53 54 // create JNDI context 55 Context jndiContext = new InitialContext(); 56 get JNDI context

48  2002 Prentice Hall. All rights reserved. Outline Fig. 16.14 WeatherSubscribe r class allows user to receive weather updates. Lines 59-61 Line 65 Lines 68-69 Lines 72-73 Line 76 57 // retrieve topic connection factory 58 // from JNDI context 59 TopicConnectionFactory topicConnectionFactory = 60 ( TopicConnectionFactory ) jndiContext.lookup( 61 "WEATHER_FACTORY" ); 62 63 // retrieve topic from JNDI context 64 String topicName = "Weather"; 65 topic = ( Topic ) jndiContext.lookup( topicName ); 66 67 // create topic connection 68 topicConnection = 69 topicConnectionFactory.createTopicConnection(); 70 71 // create topic session 72 topicSession = topicConnection.createTopicSession( false, 73 Session.AUTO_ACKNOWLEDGE ); 74 75 // initialize listener 76 topicListener = new WeatherListener( weatherDisplay ); 77 } 78 79 // process Naming exception from JNDI context 80 catch ( NamingException namingException ) { 81 namingException.printStackTrace(); 82 } 83 84 // process JMS exceptions from topic connection or session 85 catch ( JMSException jmsException ) { 86 jmsException.printStackTrace(); 87 } 88 89 // lay out user interface 90 Container container = getContentPane(); 91 container.setLayout( new BorderLayout() ); obtain TopicConnectionFactory create Topic create TopicConnection create TopicSession initialize WeatherListener

49  2002 Prentice Hall. All rights reserved. Outline Fig. 16.14 WeatherSubscribe r class allows user to receive weather updates. 92 93 JPanel selectionPanel = new JPanel(); 94 selectionPanel.setLayout( new BorderLayout() ); 95 96 JLabel selectionLabel = new JLabel( "Select Cities" ); 97 selectionPanel.add( selectionLabel, BorderLayout.NORTH ); 98 99 // create list of cities for which users 100 // can request weather updates 101 citiesList = new JList( cities ); 102 selectionPanel.add( new JScrollPane( citiesList ), 103 BorderLayout.CENTER ); 104 105 JButton getWeatherButton = new JButton( "Get Weather..." ); 106 selectionPanel.add( getWeatherButton, BorderLayout.SOUTH ); 107 108 // invoke method getWeather when getWeatherButton clicked 109 getWeatherButton.addActionListener ( 110 111 new ActionListener() { 112 113 public void actionPerformed ( ActionEvent event ) 114 { 115 getWeather(); 116 } 117 } 118 119 ); // end call to addActionListener 120 121 container.add( selectionPanel, BorderLayout.WEST ); 122 container.add( weatherDisplay, BorderLayout.CENTER ); 123 124 // invoke method quit when window closed 125 addWindowListener( 126

50  2002 Prentice Hall. All rights reserved. Outline Fig. 16.14 WeatherSubscribe r class allows user to receive weather updates. Line 153 127 new WindowAdapter() { 128 129 public void windowClosing( WindowEvent event ) 130 { 131 quit(); 132 } 133 } 134 135 ); // end call to addWindowListener 136 137 } // end WeatherSubscriber constructor 138 139 // get weather information for selected cities 140 public void getWeather() 141 { 142 // retrieve selected indices 143 int selectedIndices[] = citiesList.getSelectedIndices(); 144 145 if ( selectedIndices.length > 0 ) { 146 147 // if topic subscriber exists, method has 148 // been called before 149 if ( topicSubscriber != null ) { 150 151 // close previous topic subscriber 152 try { 153 topicSubscriber.close(); 154 } 155 156 // process JMS exception 157 catch ( JMSException jmsException ) { 158 jmsException.printStackTrace(); 159 } 160 remove previous subscriber so that new subscriber can filter newly selected cities

51  2002 Prentice Hall. All rights reserved. Outline Fig. 16.14 WeatherSubscribe r class allows user to receive weather updates. Lines 166-173 Lines 177-178 Line 180 161 // clear previous cities from display 162 weatherDisplay.clearCities(); 163 } 164 165 // create message selector to retrieve specified cities 166 StringBuffer messageSelector = new StringBuffer(); 167 messageSelector.append( 168 "City = '" + cities[ selectedIndices[ 0 ] ] + "'" ); 169 170 for ( int i = 1; i < selectedIndices.length; i++ ) { 171 messageSelector.append( " OR City = '" + 172 cities[ selectedIndices[ i ] ] + "'" ); 173 } 174 175 // create topic subscriber and subscription 176 try { 177 topicSubscriber = topicSession.createSubscriber( 178 topic, messageSelector.toString(), false ); 179 topicSubscriber.setMessageListener( topicListener ); 180 topicConnection.start(); 181 182 JOptionPane.showMessageDialog( this, 183 "A weather update should be arriving soon..." ); 184 } 185 186 // process JMS exception 187 catch ( JMSException jmsException ) { 188 jmsException.printStackTrace(); 189 } 190 191 } // end if 192 193 } // end method getWeather 194 create MessageSelector create TopicSubscriber begin receiving messages

52  2002 Prentice Hall. All rights reserved. Outline Fig. 16.14 WeatherSubscribe r class allows user to receive weather updates. Line 203 Line 207 195 // quit WeatherSubscriber application 196 public void quit() 197 { 198 // close connection and subscription to topic 199 try { 200 201 // close topic subscriber 202 if ( topicSubscriber != null ) { 203 topicSubscriber.close(); 204 } 205 206 // close topic connection 207 topicConnection.close(); 208 } 209 210 // process JMS exception 211 catch ( JMSException jmsException ) { 212 jmsException.printStackTrace(); 213 System.exit( 1 ); 214 } 215 216 System.exit( 0 ); 217 218 } // end method quit 219 220 // launch WeatherSubscriber application 221 public static void main( String args [] ) 222 { 223 WeatherSubscriber subscriber = new WeatherSubscriber(); 224 subscriber.pack(); 225 subscriber.setVisible( true ); 226 } 227 } close subscriberclose connection

53  2002 Prentice Hall. All rights reserved. 16.4.3 Weather Application: Subscriber Side (cont.) Fig. 16.15 WeatherSubscriber selecting cities for weather updates.

54  2002 Prentice Hall. All rights reserved. 16.4.3 Weather Application: Subscriber Side (cont.) Fig. 16.16 WeatherSubscriber having received updated weather conditions.

55  2002 Prentice Hall. All rights reserved. Outline Fig. 16.17 WeatherListener class subscribes to Weather topic to receive weather forecasts. Line 15 Line 32 1 // WeatherListener.java 2 // WeatherListener is the MessageListener for a subscription 3 // to the Weather topic. It implements the specified onMessage 4 // method to update the GUI with the corresponding city's 5 // weather. 6 package com.deitel.advjhtp1.jms.weather; 7 8 // Java extension packages 9 import javax.jms.*; 10 import javax.swing.*; 11 12 // Deitel packages 13 import com.deitel.advjhtp1.rmi.weather.WeatherBean; 14 15 public class WeatherListener implements MessageListener { 16 17 private WeatherDisplay weatherDisplay; 18 19 // WeatherListener constructor 20 public WeatherListener( WeatherDisplay display ) 21 { 22 weatherDisplay = display; 23 } 24 25 // receive new message 26 public void onMessage( Message message ) 27 { 28 // retrieve and process message 29 try { 30 31 // ensure Message is an ObjectMessage 32 if ( message instanceof ObjectMessage ) { 33 implements MessageListener ensures message of type ObjectMessage

56  2002 Prentice Hall. All rights reserved. Outline Fig. 16.17 WeatherListener class subscribes to Weather topic to receive weather forecasts. Lines 35-38 Line 41 34 // get WeatherBean from ObjectMessage 35 ObjectMessage objectMessage = 36 ( ObjectMessage ) message; 37 WeatherBean weatherBean = 38 ( WeatherBean ) objectMessage.getObject(); 39 40 // add WeatherBean to display 41 weatherDisplay.addItem( weatherBean ); 42 43 } // end if 44 45 else { 46 System.out.println( "Expected ObjectMessage," + 47 " but received " + message.getClass().getName() ); 48 } 49 50 } // end try 51 52 // process JMS exception from message 53 catch ( JMSException jmsException ) { 54 jmsException.printStackTrace(); 55 } 56 57 } // end method onMessage 58 } obtain WeatherBean display contents

57  2002 Prentice Hall. All rights reserved. Outline Fig. 16.18 WeatherDisplay displays WeatherBeans in a Jlist using a WeatherCellRende rer. 1 // WeatherDisplay.java 2 // WeatherDisplay extends JPanel to display results 3 // of client's request for weather conditions. 4 package com.deitel.advjhtp1.jms.weather; 5 6 // Java core packages 7 import java.awt.*; 8 import java.awt.event.*; 9 import java.util.*; 10 11 // Java extension packages 12 import javax.swing.*; 13 14 // Deitel packages 15 import com.deitel.advjhtp1.rmi.weather.*; 16 17 public class WeatherDisplay extends JPanel { 18 19 // WeatherListModel and Map for storing WeatherBeans 20 private WeatherListModel weatherListModel; 21 private Map weatherItems; 22 23 // WeatherDisplay constructor 24 public WeatherDisplay() 25 { 26 setLayout( new BorderLayout() ); 27 28 ImageIcon headerImage = new ImageIcon( 29 WeatherDisplay.class.getResource( 30 "images/header.jpg" ) ); 31 add( new JLabel( headerImage ), BorderLayout.NORTH ); 32

58  2002 Prentice Hall. All rights reserved. Outline Fig. 16.18 WeatherDisplay displays WeatherBeans in a Jlist using a WeatherCellRende rer. Lines 56-58 Lines 62-63 33 // use JList to display updated weather conditions 34 // for requested cities 35 weatherListModel = new WeatherListModel(); 36 JList weatherJList = new JList( weatherListModel ); 37 weatherJList.setCellRenderer( new WeatherCellRenderer() ); 38 39 add( new JScrollPane( weatherJList ), BorderLayout.CENTER ); 40 41 // maintain WeatherBean items in HashMap 42 weatherItems = new HashMap(); 43 44 } // end WeatherDisplay constructor 45 46 // add WeatherBean item to display 47 public void addItem( WeatherBean weather ) 48 { 49 String city = weather.getCityName(); 50 51 // check whether city is already in display 52 if ( weatherItems.containsKey( city ) ) { 53 54 // if city is in Map, and therefore in display 55 // remove previous WeatherBean object 56 WeatherBean previousWeather = 57 ( WeatherBean ) weatherItems.remove( city ); 58 weatherListModel.remove( previousWeather ); 59 } 60 61 // add WeatherBean to Map and WeatherListModel 62 weatherListModel.add( weather ); 63 weatherItems.put( city, weather ); 64 65 } // end method addItem remove if bean previously existing add new bean to list

59  2002 Prentice Hall. All rights reserved. Outline Fig. 16.18 WeatherDisplay displays WeatherBeans in a Jlist using a WeatherCellRende rer. 66 67 // clear all cities from display 68 public void clearCities() 69 { 70 weatherItems.clear(); 71 weatherListModel.clear(); 72 } 73 }

60  2002 Prentice Hall. All rights reserved. 16.4.4 Weather Application: Configuring and Running 1.Start J2EE server j2ee –verbose 2.Create Weather topic (new window) j2eeadmin –addJmsDestination Weather topic 3.Verify topic selected j2eeadmin –listJmsDestination 4.Create connection factory j2eeadmin –addJmsFactory WEATHER_FACTORY topic 5.Start WeatherPublisher java –classpath %J2EE_HOME%\lib\j2ee.jar;. -Djms.properties=%J2EE_HOME%\config\jms_client.properties com.deitel.advjhtp1.jms.weather.WeatherPublisher 6.Start WeatherSubscriber java –classpath %J2EE_HOME%\lib\j2ee.jar;. -Djms.properties=%J2EE_HOME%\config\jms_client.properties com.deitel.advjhtp1.jmx.weather.WeatherSubscriber

61  2002 Prentice Hall. All rights reserved. 16.4.4 Weather Application: Configuring and Running (cont.) To close application 1.remove factory j2eeadmin –removeJmsFactory WEATHER_FACTORY 2.remove topic j2eeadmin –removeJmsDestination Weather 3.stop J2EE server j2ee -stop

62  2002 Prentice Hall. All rights reserved. 16.5 Message-Driven Enterprise JavaBeans New type of EJB available in EJB version 2.0. –part of Java 2 Enterprise Edition version 1.3 When message is received –container uses any available message-driven bean message-driven beans handle messages from multiple clients Must not maintain state. Developers provide only bean implementation.

63  2002 Prentice Hall. All rights reserved. 16.5.1 Voter Application: Overview Class Voter –posts vote messages to queue –not concerned with receiver’s implementation benefit of loosely coupled systems Class VoteCollectorEJB –message-bean implementation –delegates message to entity-bean Candidate Class Candidate –tallies votes –stores results in database Voting Class TallyDisplay –presents GUI with tallies from database

64  2002 Prentice Hall. All rights reserved. 16.5.1 Voter Application: Overview (cont.) Fig. 16.19 Voter application overview.

65  2002 Prentice Hall. All rights reserved. 16.5.2 Voter Application: Receiver Side Candidate entity EJB represents –vote candidate for which users vote –number of votes for candidate Uses container managed persistence.

66  2002 Prentice Hall. All rights reserved. Outline Fig. 16.20 CandidateHome interface for Candidate EJB. Lines 15-16 Lines 19-20 Lines 23-24 1 // CandidateHome.java 2 // CandidateHome is the home interface for the Candidate EJB. 3 package com.deitel.advjhtp1.jms.mdb; 4 5 // Java core libraries 6 import java.rmi.*; 7 import java.util.*; 8 9 // Java standard extensions 10 import javax.ejb.*; 11 12 public interface CandidateHome extends EJBHome { 13 14 // find Candidate with given name 15 public Candidate findByPrimaryKey( String candidateName ) 16 throws RemoteException, FinderException; 17 18 // find all Candidates 19 public Collection findAllCandidates() 20 throws RemoteException, FinderException; 21 22 // create new Candidate EJB 23 public Candidate create( String candidateName ) 24 throws RemoteException, CreateException; 25 } locate particular Candidate locate Collection of Candidate s create new Candidate with given name and 0 votes

67  2002 Prentice Hall. All rights reserved. Outline Fig. 16.21 Candidate remote interface for Candidate EJB. Line 15 Line 18 Line 21 1 // Candidate.java 2 // Candidate is the remote interface for the Candidate 3 // EJB, which maintains a tally of votes. 4 package com.deitel.advjhtp1.jms.mdb; 5 6 // Java core libraries 7 import java.rmi.RemoteException; 8 9 // Java standard extensions 10 import javax.ejb.EJBObject; 11 12 public interface Candidate extends EJBObject { 13 14 // place vote for this Candidate 15 public void incrementVoteCount() throws RemoteException; 16 17 // get total vote count for this Candidate 18 public Integer getVoteCount() throws RemoteException; 19 20 // get Candidate's name 21 public String getCandidateName() throws RemoteException; 22 } add vote to Candidate current vote tallycandidate’s name

68  2002 Prentice Hall. All rights reserved. Outline Fig. 16.22 CandidateEJB class to maintain candidate tallies. Lines 17-18 Lines 21-25 1 // CandidateEJB.java 2 // CandidateEJB is an entity EJB that uses container-managed 3 // persistence to persist its Candidate and its vote tally. 4 package com.deitel.advjhtp1.jms.mdb; 5 6 // Java core libraries 7 import java.rmi.RemoteException; 8 9 // Java standard extensions 10 import javax.ejb.*; 11 12 public class CandidateEJB implements EntityBean { 13 14 private EntityContext entityContext; 15 16 // container-managed fields 17 public Integer voteCount; 18 public String name; 19 20 // place vote for this Candidate 21 public void incrementVoteCount() 22 { 23 int newVoteCount = voteCount.intValue() + 1; 24 voteCount = new Integer( newVoteCount ); 25 } 26 27 // get total vote count for this Candidate 28 public Integer getVoteCount() 29 { 30 return voteCount; 31 } 32 container-managed fields voteCount and name increment vote tally

69  2002 Prentice Hall. All rights reserved. Outline Fig. 16.22 CandidateEJB class to maintain candidate tallies. Lines 34-37 Lines 40-47 33 // get Candidate's name 34 public String getCandidateName() 35 { 36 return name; 37 } 38 39 // create new Candidate 40 public String ejbCreate( String candidateName ) 41 throws CreateException 42 { 43 name = candidateName; 44 voteCount = new Integer( 0 ); 45 46 return null; 47 } 48 49 // do post-creation tasks when creating new Candidate 50 public void ejbPostCreate( String candidateName ) {} 51 52 // set EntityContext 53 public void setEntityContext( EntityContext context ) 54 { 55 entityContext = context; 56 } 57 58 // unset EntityContext 59 public void unsetEntityContext() 60 { 61 entityContext = null; 62 } 63 64 // activate Candidate instance 65 public void ejbActivate() 66 { 67 name = ( String ) entityContext.getPrimaryKey(); return candidate nameinitializes new candidate with specified name and initializes vote count to 0

70  2002 Prentice Hall. All rights reserved. Outline Fig. 16.22 CandidateEJB class to maintain candidate tallies. 68 } 69 70 // passivate Candidate instance 71 public void ejbPassivate() 72 { 73 name = null; 74 } 75 76 // load Candidate from database 77 public void ejbLoad() {} 78 79 // store Candidate in database 80 public void ejbStore() {} 81 82 // remove Candidate from database 83 public void ejbRemove() {} 84 }

71  2002 Prentice Hall. All rights reserved. Outline Fig. 16.23 VoteCollectorEJB class tallies votes from Votes queue. Lines 21-48 1 // VoteCollectorEJB.java 2 // VoteCollectorEJB is a MessageDriven EJB that tallies votes. 3 package com.deitel.advjhtp1.jms.mdb; 4 5 // Java core packages 6 import java.util.*; 7 import java.rmi.*; 8 9 // Java extension packages 10 import javax.ejb.*; 11 import javax.rmi.*; 12 import javax.jms.*; 13 import javax.naming.*; 14 15 public class VoteCollectorEJB 16 implements MessageDrivenBean, MessageListener { 17 18 private MessageDrivenContext messageDrivenContext; 19 20 // receive new message 21 public void onMessage( Message message ) 22 { 23 TextMessage voteMessage; 24 25 // retrieve and process message 26 try { 27 28 if ( message instanceof TextMessage ) { 29 voteMessage = ( TextMessage ) message; 30 String vote = voteMessage.getText(); 31 countVote( vote ); 32 33 System.out.println( "Received vote: " + vote ); 34 } // end if 35 called by container whenever vote message is placed in queue

72  2002 Prentice Hall. All rights reserved. Outline Fig. 16.23 VoteCollectorEJB class tallies votes from Votes queue. Lines 60-67 36 else { 37 System.out.println( "Expecting " + 38 "TextMessage object, received " + 39 message.getClass().getName() ); 40 } 41 42 } // end try 43 44 // process JMS exception from message 45 catch ( JMSException jmsException ) { 46 jmsException.printStackTrace(); 47 } 48 } 49 50 // add vote to corresponding tally 51 private void countVote( String vote ) 52 { 53 // CandidateHome reference for finding/creating Candidates 54 CandidateHome candidateHome = null; 55 56 // find Candidate and increment vote count 57 try { 58 59 // look up Candidate EJB 60 Context initialContext = new InitialContext(); 61 62 Object object = initialContext.lookup( 63 "java:comp/env/ejb/Candidate" ); 64 65 candidateHome = 66 ( CandidateHome ) PortableRemoteObject.narrow( 67 object, CandidateHome.class ); 68 obtain reference to Candidate EJB

73  2002 Prentice Hall. All rights reserved. Outline Fig. 16.23 VoteCollectorEJB class tallies votes from Votes queue. Lines 70-71 Line 74 Lines 83-84 69 // find Candidate for whom the user voted 70 Candidate candidate = 71 candidateHome.findByPrimaryKey( vote ); 72 73 // increment Candidate's vote count 74 candidate.incrementVoteCount(); 75 76 } // end try 77 78 // if Candidate not found, create new Candidate 79 catch ( FinderException finderException ) { 80 81 // create new Candidate and increment its vote count 82 try { 83 Candidate newCandidate = candidateHome.create( vote ); 84 newCandidate.incrementVoteCount(); 85 } 86 87 // handle exceptions creating new Candidate 88 catch ( Exception exception ) { 89 throw new EJBException( exception ); 90 } 91 92 } // end FinderException catch 93 94 // handle exception when looking up OrderProducts EJB 95 catch ( NamingException namingException ) { 96 throw new EJBException( namingException ); 97 } 98 99 // handle exception when invoking OrderProducts methods 100 catch ( RemoteException remoteException ) { 101 throw new EJBException( remoteException ); 102 } 103 find particular Candidate increment vote count create new Candidate if specified candidate name not found

74  2002 Prentice Hall. All rights reserved. Outline Fig. 16.23 VoteCollectorEJB class tallies votes from Votes queue. 104 } // end method countVote 105 106 // set message driven context 107 public void setMessageDrivenContext( 108 MessageDrivenContext context ) 109 { 110 messageDrivenContext = context; 111 } 112 113 // create bean instance 114 public void ejbCreate() {} 115 116 // remove bean instance 117 public void ejbRemove() {} 118 }

75  2002 Prentice Hall. All rights reserved. Outline Fig. 16.24 TallyDisplay displays candidate tallies from database. 1 // TallyDisplay.java 2 // TallyDisplay displays the votes from database. 3 package com.deitel.advjhtp1.jms.mdb; 4 5 // Java core packages 6 import java.awt.*; 7 import java.awt.event.*; 8 import java.rmi.*; 9 import java.util.*; 10 import java.util.List; 11 12 // Java extension packages 13 import javax.swing.*; 14 import javax.ejb.*; 15 import javax.rmi.*; 16 import javax.naming.*; 17 18 public class TallyDisplay extends JFrame { 19 20 // TallyDisplay constructor 21 public TallyDisplay() 22 { 23 super( "Vote Tallies" ); 24 25 Container container = getContentPane(); 26 27 // displayPanel displays tally results 28 JPanel displayPanel = new JPanel(); 29 displayPanel.setLayout( new GridLayout( 0, 1 ) ); 30 container.add( new JScrollPane( displayPanel ) ); 31

76  2002 Prentice Hall. All rights reserved. Outline Fig. 16.24 TallyDisplay displays candidate tallies from database. Lines 36-46 Lines 50-59 32 // find Candidates and display tallies 33 try { 34 35 // look up Candidate EJB 36 Context initialContext = new InitialContext(); 37 38 Object object = initialContext.lookup( 39 "Candidate" ); 40 CandidateHome candidateHome = 41 ( CandidateHome ) PortableRemoteObject.narrow( 42 object, CandidateHome.class ); 43 44 // find all Candidates 45 Collection candidates = 46 candidateHome.findAllCandidates(); 47 48 // add TallyPanel with candidate name and 49 // vote count for each candidate 50 Iterator iterator = candidates.iterator(); 51 while ( iterator.hasNext() ) { 52 Candidate candidate = ( Candidate ) iterator.next(); 53 54 // create TallyPanel for Candidate 55 TallyPanel tallyPanel = 56 new TallyPanel( candidate.getCandidateName(), 57 candidate.getVoteCount().intValue() ); 58 displayPanel.add( tallyPanel ); 59 } 60 61 } // end try 62 63 // handle exception finding Candidates 64 catch ( FinderException finderException ) { 65 finderException.printStackTrace(); lookup all Candidate s display snapshot of information

77  2002 Prentice Hall. All rights reserved. Outline Fig. 16.24 TallyDisplay displays candidate tallies from database. 66 } 67 // handle exception looking up Candidate EJB 68 catch ( NamingException namingException ) { 69 namingException.printStackTrace(); 70 } 71 72 // handle exception communicating with Candidate 73 catch ( RemoteException remoteException ) { 74 remoteException.printStackTrace(); 75 } 76 77 } // end TallyDisplay constructor 78 79 // launch TallyDisplay application 80 public static void main( String args[] ) 81 { 82 TallyDisplay tallyDisplay = new TallyDisplay(); 83 tallyDisplay.setDefaultCloseOperation( EXIT_ON_CLOSE ); 84 tallyDisplay.pack(); 85 tallyDisplay.setVisible( true ); 86 } 87 }

78  2002 Prentice Hall. All rights reserved. 16.5.2 Voter Application: Receiver Side (cont.) Fig. 16.25 TallyDisplay displays candidate tallies from database.

79  2002 Prentice Hall. All rights reserved. Outline Fig. 16.26 TallyPanel class displays the name and tally for a candidate. 1 // TallyPanel.java 2 // TallPanel is the GUI component which displays 3 // the name and tally for a vote candidate. 4 package com.deitel.advjhtp1.jms.mdb; 5 6 // Java core packages 7 import java.awt.*; 8 9 // Java extension packages 10 import javax.swing.*; 11 12 public class TallyPanel extends JPanel { 13 14 private JLabel nameLabel; 15 private JTextField tallyField; 16 private String name; 17 private int tally; 18 19 // TallyPanel constructor 20 public TallyPanel( String voteName, int voteTally ) 21 { 22 name = voteName; 23 tally = voteTally; 24 25 nameLabel = new JLabel( name ); 26 tallyField = 27 new JTextField( Integer.toString( tally ), 10 ); 28 tallyField.setEditable( false ); 29 tallyField.setBackground( Color.white ); 30 31 add( nameLabel ); 32 add( tallyField );

80  2002 Prentice Hall. All rights reserved. Outline Fig. 16.26 TallyPanel class displays the name and tally for a candidate. 33 34 } // end TallyPanel constructor 35 36 }

81  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running Apply to file resource.properties jdbcDataSource. number.name=jdbc/Voting jdbcDataSource. number.url=jdbc:cloudscape:rmi:VotingDB;create=true where number is next number in jdbcDataSource entries. Start J2EE server j2ee –verbose Create queue j2eeadmin –addJmsDestination Votes queue Create connection factory j2eeadmin –addJmsFactory VOTE_FACTORY queue Run deploy tool deploytool

82  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Within deploy tool, create new application File -> New Application Browse navigate to parent directory of com package structure File enter VoteCollectorApp.ear as file name New Application OK Add Candidate EJB File -> New Enterprise Bean

83  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Fig. 16.27 EJB JAR settings for VoteCollectorApp application.

84  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Fig. 16.28 Add class files for Candidate EJB.

85  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Fig. 16.29General settings for Candidate EJB.

86  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Fig. 16.30 Entity settings for Candidate EJB.

87  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Fig. 16.31 Entity tab for Candidate EJB.

88  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Fig. 16.32Database settings for Candidate EJB.

89  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Fig. 16.33SQL generation for Candidate EJB.

90  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Fig. 16.34SQL warning for Candidate EJB.

91  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Create VoteCollector File -> New Enterprise Bean

92  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Fig. 16.35 EJB JAR settings for VoteCollector EJB.

93  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Fig. 16.36Add class file for VoteCollector EJB.

94  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Fig. 16.37General settings for VoteCollector EJB.

95  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Fig. 16.38Transaction management settings for the VoteCollector EJB

96  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Fig. 16.39Message-Driven Bean settings for VoteCollector EJB.

97  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Fig. 16.40Enterprise Bean References for VoteCollector EJB.

98  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Fig. 16.41Setting JNDI names for VoteCollectorApp.

99  2002 Prentice Hall. All rights reserved. 16.5.3 Voter Application: Configuring and Running (cont.) Fig. 16.42Deploying the VoteCollector application.


Download ppt " 2002 Prentice Hall. All rights reserved. Chapter 16: Messaging with JMS Outline 16.1 Introduction 16.2 Installation and Configuration of J2EE 1.3 16.3."

Similar presentations


Ads by Google