Chapter 16 Messaging with JMS Outline 16 1

  • Slides: 99
Download presentation
Chapter 16: Messaging with JMS Outline 16. 1 Introduction 16. 2 Installation and Configuration

Chapter 16: Messaging with JMS Outline 16. 1 Introduction 16. 2 Installation and Configuration of J 2 EE 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 Java. Beans 16. 5. 1 Voter Application: Overview 16. 5. 2 Voter Application: Receiver Side 16. 5. 3 Voter Application: Configuring and Running 2002 Prentice Hall. All rights reserved.

16. 1 Introduction • Message-oriented middleware – enables components to post messages for other

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 2002 Prentice Hall. All rights reserved.

16. 1 Introduction (cont. ) • Message – composed of • header – message

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 2002 Prentice Hall. All rights reserved.

16. 1 Introduction (cont. ) – composed of 5 types 1. 2. 3. 4.

16. 1 Introduction (cont. ) – composed of 5 types 1. 2. 3. 4. 5. • Bytes. Messages Map. Messages Object. Messages Stream. Messages Text. Messages Message-driven beans – Enterprise Java. Beans 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 2002 Prentice Hall. All rights reserved.

16. 2 Installation and Configuration of J 2 EE 1. 3 • Steps for

16. 2 Installation and Configuration of J 2 EE 1. 3 • Steps for installing J 2 EE 1. 3 – download and unpack appropriate software bundle • http: //java. sun. com/j 2 ee/j 2 sdkee-beta/index. html – set environment variables according to Fig. 16. 1 2002 Prentice Hall. All rights reserved.

16. 2 Installation and Configuration of J 2 EE 1. 3 (cont. ) 2002

16. 2 Installation and Configuration of J 2 EE 1. 3 (cont. ) 2002 Prentice Hall. All rights reserved.

16. 3 Point-To-Point Messaging • Allows clients send messages to message queue. – receiver

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. 2002 Prentice Hall. All rights reserved.

16. 3 Point-To-Point Messaging (cont. ) Fig. 16. 2 Point-to-point messaging model. 2002 Prentice

16. 3 Point-To-Point Messaging (cont. ) Fig. 16. 2 Point-to-point messaging model. 2002 Prentice Hall. All rights reserved.

16. 3. 1 Voter Application: Overview • Tallies votes to favorite computer languages. •

16. 3. 1 Voter Application: Overview • Tallies votes to favorite computer languages. • Class Voter – sends votes as messages to Votes queue • messages are simple Text. Message objects – body contains candidate name • Class Vote. Collector – consumes messages and tallies votes – updates display 2002 Prentice Hall. All rights reserved.

16. 3. 1 Voter Application: Overview (cont. ) Fig. 16. 3 Voter application overview.

16. 3. 1 Voter Application: Overview (cont. ) Fig. 16. 3 Voter application overview. 2002 Prentice Hall. All rights reserved.

16. 3. 2 Voter Application: Sender Side • Consists of single class, Voter. –

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 // Voter. java // Voter is the GUI that allows the client to vote // for a programming language. Voter sends the vote // to the "Votes" queue as a Text. Message. package com. deitel. advjhtp 1. jms. voter; Outline // Java core packages import java. awt. *; import java. awt. event. *; // Java extension packages import javax. swing. *; import javax. jms. *; import javax. naming. *; contains JMS API classes and interfaces public class Voter extends JFrame { private String selected. Language; // JMS variables private Queue. Connection queue. Connection ; private Queue. Session queue. Session ; private Queue. Sender queue. Sender ; Fig. 16. 4 Voter class submits votes as messages to queue. Line 13 // Voter constructor public Voter() { // lay out user interface super( "Voter" ); Container container = get. Content. Pane(); container. set. Layout( new Border. Layout() ); 2002 Prentice Hall. All rights reserved.

34 35 36 37 38 39 40 41 42 43 44 45 46 47

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 JText. Area vote. Area = new JText. Area( "Please vote for yourn" + "favorite programming language" ); vote. Area. set. Editable( false ); container. add( vote. Area, Border. Layout. NORTH ); Outline JPanel languages. Panel = new JPanel(); languages. Panel. set. Layout( new Grid. Layout( 0, 1 ) ); // add each language as its own JCheck. Box // Button. Group ensures exactly one language selected Button. Group languages. Group = new Button. Group(); Check. Box. Handler check. Box. Handler = new Check. Box. Handler(); String languages[] = { "C", "C++", "Java", "Lisp", "Python" }; selected. Language = ""; // create JCheck. Box for each language // and add to Button. Group and JPanel for ( int i = 0; i < languages. length; i++ ) { JCheck. Box check. Box = new JCheck. Box( languages[ i ] ); check. Box. add. Item. Listener( check. Box. Handler ); languages. Panel. add( check. Box ); languages. Group. add( check. Box ); } Fig. 16. 4 Voter class submits votes as messages to queue. container. add( languages. Panel, Border. Layout. CENTER ); // create button to submit vote JButton submit. Button = new JButton( "Submit vote!" ); container. add( submit. Button, Border. Layout. SOUTH ); 2002 Prentice Hall. All rights reserved.

66 67 68 69 70 71 72 73 74 75 76 77 78 79

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 // invoke method submit. Vote when submit. Button clicked submit. Button. add. Action. Listener ( Outline new Action. Listener() { public void action. Performed ( Action. Event event ) { submit. Vote (); } } ); // invoke method quit when window closed add. Window. Listener( new Window. Adapter() { public void window. Closing( Window. Event event ) { quit(); } } Fig. 16. 4 Voter class submits votes as messages to queue. ); Line 92 // connect to message queue try { Lines 96 -100 // create JNDI context Context jndi. Context = new Initial. Context(); // retrieve queue connection factory and // queue from JNDI context Queue. Connection. Factory queue. Connection. Factory = ( Queue. Connection. Factory ) jndi. Context. lookup( "VOTE_FACTORY" ); Queue queue = ( Queue ) jndi. Context. lookup( "Votes" ); create JNDI context server administrator responsible for creating queue connection factory and 2002 queue Prentice Hall. All rights reserved.

101 102 103 104 105 106 107 108 109 110 111 112 113 114

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 // create connection, session and sender queue. Connection = queue. Connection. Factory. create. Queue. Connection(); queue. Session = queue. Connection. create. Queue. Session( false, Session. AUTO_ACKNOWLEDGE ); queue. Sender = queue. Session. create. Sender( queue ); } // process Naming exception from JNDI context catch ( Naming. Exception naming. Exception ) { naming. Exception. print. Stack. Trace(); System. exit( 1 ); } // process JMS exception from queue connection or session catch ( JMSException jms. Exception ) { jms. Exception. print. Stack. Trace(); System. exit( 1 ); } } // end Voter constructor // submit selected vote to "Votes" queue as Text. Message public void submit. Vote() { if ( selected. Language != "" ) { // create text message containing selected language try { Text. Message vote. Message = queue. Session. create. Text. Message(); vote. Message. set. Text( selected. Language ); Outline create Queue. Connection create. Voter Fig. 16. 4 Queue. Session class submits votes as messages to post messages through queue. Queue. Sender instance Lines 102 -103 Lines 104 -106 Lines 107 Lines 131 -132 Line 133 message instance set body of message 2002 Prentice Hall. All rights reserved.

135 136 137 138 139 140 141 142 143 144 145 146 147 148

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

167 168 169 170 171 172 173 174 175 176 177 178 179 180

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 // launch Voter application public static void main( String args[] ) { Voter voter = new Voter(); voter. pack(); voter. set. Visible( true ); } Outline // Check. Box. Handler handles event when checkbox checked private class Check. Box. Handler implements Item. Listener { // checkbox event public void item. State. Changed( Item. Event event ) { // update selected. Language JCheck. Box source = ( JCheck. Box ) event. get. Source(); selected. Language = source. get. Text(); } } } Fig. 16. 4 Voter class submits votes as messages to queue. 2002 Prentice Hall. All rights reserved.

16. 3. 2 Voter Application: Sender Side (cont. ) Fig. 16. 5 Voter application

16. 3. 2 Voter Application: Sender Side (cont. ) Fig. 16. 5 Voter application votes for favorite programming language 2002 Prentice Hall. All rights reserved.

16. 3. 3 Voter Application: Receiver Side • Class Vote. Collector intended receiver –

16. 3. 3 Voter Application: Receiver Side • Class Vote. Collector intended receiver – tallies and displays votes • Votes queue can be populated before Vote. Collector connects. 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // Vote. Collector. java // Vote. Collector tallies and displays the votes // posted as Text. Messages to the "Votes" queue. package com. deitel. advjhtp 1. jms. voter; Outline // Java core packages import java. awt. *; import java. awt. event. *; import java. util. *; // Java extension packages import javax. swing. *; import javax. jms. *; import javax. naming. *; public class Vote. Collector extends JFrame { private JPanel display. Panel; private Map tallies = new Hash. Map(); // JMS variables private Queue. Connection queue. Connection ; Fig. 16. 6 Vote. Collector class retrieves and tallies votes. // Vote. Collector constructor public Vote. Collector() { super( "Vote Tallies" ); Container container = get. Content. Pane(); // display. Panel will display tally results display. Panel = new JPanel(); display. Panel. set. Layout( new Grid. Layout( 0, 1 ) ); container. add( new JScroll. Pane( display. Panel ) ); 2002 Prentice Hall. All rights reserved.

36 37 38 39 40 41 42 43 44 45 46 47 48 49

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 // invoke method quit when window closed add. Window. Listener( Outline new Window. Adapter() { public void window. Closing( Window. Event event ) { quit(); } } ); // connect to "Votes" queue try { // create JNDI context Context jndi. Context = new Initial. Context(); // retrieve queue connection factory // and queue from JNDI context Queue. Connection. Factory queue. Connection. Factory = ( Queue. Connection. Factory ) jndi. Context. lookup( "VOTE_FACTORY" ); Queue queue = ( Queue ) jndi. Context. lookup( "Votes" ); // create connection, session and receiver queue. Connection = queue. Connection. Factory. create. Queue. Connection(); Queue. Session queue. Session = queue. Connection. create. Queue. Session( false, Session. AUTO_ACKNOWLEDGE ); Queue. Receiver queue. Receiver = queue. Session. create. Receiver( queue ); Fig. 16. 6 Vote. Collector class retrieves and tallies votes. create JNDI context Line 51 Lines 55 -57 get queue connection factory Lines 61 -65 Lines 66 -67 create Queue. Session create votes receiver 2002 Prentice Hall. All rights reserved.

69 70 71 72 73 74 75 76 77 78 79 80 81 82

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 Outline // initialize and set message listener queue. Receiver. set. Message. Listener( new Vote. Listener( this ) ); // start connection queue. Connection. start(); } activate connection register listener // process Naming exception from JNDI context catch ( Naming. Exception naming. Exception ) { naming. Exception. print. Stack. Trace(); System. exit( 1 ); } // process JMS exception from queue connection or session catch ( JMSException jms. Exception ) { jms. Exception. print. Stack. Trace(); System. exit( 1 ); } } // end Vote. Collector constructor // add vote to corresponding tally public void add. Vote( String vote ) { if ( tallies. contains. Key( vote ) ) { Fig. 16. 6 Vote. Collector class retrieves and tallies votes. Lines 70 -71 Lines 74 updates tallies and. Lines display. 92 -109 Callback method for Vote. Listener instance // if vote already has corresponding tally Tally. Panel tally. Panel = ( Tally. Panel ) tallies. get( vote ); tally. Panel. update. Tally(); } 2002 Prentice Hall. All rights reserved.

102 103 104 105 106 107 108 109 110 111 112 113 114 115

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 // add to GUI and tallies else { Tally. Panel tally. Panel = new Tally. Panel( vote, 1 ); display. Panel. add( tally. Panel ); tallies. put( vote, tally. Panel ); validate(); } Outline } // quit application public void quit() { if ( queue. Connection != null ) { // close the queue connection if it exists try { queue. Connection. close(); } // process JMS exception catch ( JMSException jms. Exception ) { jms. Exception. print. Stack. Trace(); System. exit( 1 ); } Fig. 16. 6 Vote. Collector close queue classconnection retrieves and tallies votes. Line 118 } System. exit( 0 ); } // end method quit 2002 Prentice Hall. All rights reserved.

133 134 135 136 137 138 139 140 // launch Vote. Collector public static

133 134 135 136 137 138 139 140 // launch Vote. Collector public static void main( String args[] ) { Vote. Collector vote. Collector = new Vote. Collector(); vote. Collector. set. Size( 200, 200 ); vote. Collector. set. Visible( true ); } Outline } Fig. 16. 6 Vote. Collector class retrieves and tallies votes. 2002 Prentice Hall. All rights reserved.

16. 3. 3 Voter Application: Receiver Side (cont. ) Fig. 16. 7 Vote. Collector

16. 3. 3 Voter Application: Receiver Side (cont. ) Fig. 16. 7 Vote. Collector tallies and displays votes. 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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

36 37 38 39 40 41 42 43 44 45 46 47 48 49

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 else { System. out. println( "Expecting " + "Text. Message object, received " + message. get. Class(). get. Name() ); } Outline } // process JMS exception from message catch ( JMSException jms. Exception ) { jms. Exception. print. Stack. Trace(); } } // end method on. Message } Fig. 16. 8 Vote. Listener class receives messages from the queue. 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // Tally. Panel. java // Tall. Panel is the GUI component which displays // the name and tally for a vote candidate. package com. deitel. advjhtp 1. jms. voter; Outline // Java core packages import java. awt. *; // Java extension packages import javax. swing. *; public class Tally. Panel extends JPanel { private JLabel name. Label; JText. Field tally. Field; String name; int tally; // Tally. Panel constructor public Tally. Panel( String vote. Name, int vote. Tally ) { name = vote. Name; tally = vote. Tally; Fig. 16. 9 Tally. Panel class displays candidate name and tally. name. Label = new JLabel( name ); tally. Field = new JText. Field( Integer. to. String( tally ), 10 ); tally. Field. set. Editable( false ); tally. Field. set. Background( Color. white ); add( name. Label ); add( tally. Field ); } // end Tally. Panel constructor 2002 Prentice Hall. All rights reserved.

36 37 38 39 40 41 42 // update tally by one vote public

36 37 38 39 40 41 42 // update tally by one vote public void update. Tally() { tally++; tally. Field. set. Text( Integer. to. String( tally ) ); } Outline } increments tally by one Fig. 16. 9 Tally. Panel class displays candidate name and tally. 2002 Prentice Hall. All rights reserved.

16. 3. 4 Voter Application: Configuring and Running 1. Start J 2 EE server

16. 3. 4 Voter Application: Configuring and Running 1. Start J 2 EE server j 2 ee –verbose 2. Create Votes queue (in new window) j 2 eeadmin –add. Jms. Destination Votes queue 3. Verify queue was created j 2 eeadmin –list. Jms. Destination 4. Create connection factory j 2 eeadmin –add. Jms. Factory VOTE_FACTORY queue 5. Start Vote. Collector java –classpath %J 2 EE_HOME%libj 2 ee. jar; . -Djms. properties=%J 2 EE_HOME%configjms_client. properties com. deitel. advjhtp 1. jms. voter. Vote. Collector 6. Start Voter (in new window) java –classpath %J 2 EE_HOME%libj 2 ee. jar; . -Djms. properties=%J 2 EE_HOME%configjms_client. properties com. deitel. advjhtp 1. jms. voter. Voter 2002 Prentice Hall. All rights reserved.

16. 3. 4 Voter Application: Configuring and Running (cont. ) • Once application finished

16. 3. 4 Voter Application: Configuring and Running (cont. ) • Once application finished – remove connection factory j 2 eeadmin –remove. Jms. Factory VOTE_FACTORY – remote topic j 2 eeadmin –remove. Jms. Destination Votes – stop J 2 EE server j 2 ee -stop 2002 Prentice Hall. All rights reserved.

16. 4 Publish/Subscribe Messaging • Allows multiple clients to – connect to topic on

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 2002 Prentice Hall. All rights reserved.

16. 4 Publish/Subscribe Messaging (cont. ) Fig. 16. 10 Publish/subscribe messaging model. 2002 Prentice

16. 4 Publish/Subscribe Messaging (cont. ) Fig. 16. 10 Publish/subscribe messaging model. 2002 Prentice Hall. All rights reserved.

16. 4. 1 Weather Application: Overview • Class Weather. Publisher – retrieves weather updates

16. 4. 1 Weather Application: Overview • Class Weather. Publisher – retrieves weather updates from URL – publishes information as messages to topic • Class Weather. Subscriber – provides GUI • enables user to select desired cities – subscribes to Weather topic • receives corresponding messages • uses message selector 2002 Prentice Hall. All rights reserved.

16. 4. 1 Weather Application: Overview (cont. ) Fig. 16. 11 Weather application overview.

16. 4. 1 Weather Application: Overview (cont. ) Fig. 16. 11 Weather application overview. 2002 Prentice Hall. All rights reserved.

16. 4. 2 Weather Application: Publisher Side • Class Weather. Publisher – retrieves weather

16. 4. 2 Weather Application: Publisher Side • Class Weather. Publisher – retrieves weather updates from National Weather Service – publishes weather updates to Weather topic – messages of type Object. Message • String property City specifies corresponding city 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // Weather. Publisher. java // Weather. Publisher retrieves weather conditions from the National // Weather Service and publishes them to the Weather topic // as Object. Messages containing Weather. Beans. The city name is // used in a String property "City" in the message header. package com. deitel. advjhtp 1. jms. weather; // Java core packages import java. io. *; import java. net. *; import java. util. *; // Java extension packages import javax. jms. *; import javax. naming. *; // Deitel packages import com. deitel. advjhtp 1. rmi. weather. Weather. Bean; public class Weather. Publisher extends Timer. Task { Outline Fig. 16. 12 Weather. Publisher class publishes messages to Weather topic. private Buffered. Reader in; private Topic. Connection topic. Connection ; // Weather. Publisher constructor public Weather. Publisher() { // update weather conditions every minute Timer timer = new Timer(); timer. schedule. At. Fixed. Rate( this, 0, 60000 ); // allow user to quit Input. Stream. Reader input. Stream. Reader = new Input. Stream. Reader( System. in ); char answer = ''; 2002 Prentice Hall. All rights reserved.

36 37 38 39 40 41 42 43 44 45 46 47 48 49

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

71 72 73 74 75 76 77 78 79 80 81 82 83 84

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 Outline // process IO exception from closing connection // to NWS Web server catch ( IOException io. Exception ) { io. Exception. print. Stack. Trace(); System. exit( 1 ); } System. exit( 0 ); } // end Weather. Publisher constructor // get weather information from NWS public void run() { // connect to topic "Weather" try { System. out. println( "Update weather information. . . " ); // create JNDI context Context jndi. Context = new Initial. Context(); String topic. Name = "Weather"; // retrieve topic connection factory and topic // from JNDI context Topic. Connection. Factory topic. Connection. Factory = ( Topic. Connection. Factory ) jndi. Context. lookup( "WEATHER_FACTORY" ); Topic topic = ( Topic ) jndi. Context. lookup( topic. Name ); // create connection, session, publisher and message topic. Connection = topic. Connection. Factory. create. Topic. Connection(); Fig. 16. 12 Weather. Publisher class publishes messages to Weather topic. create JNDI Line 90 context Line 95 -97 Line 103 -104 look up Topic. Connection. Factory and Topic create Topic. Connection 2002 Prentice Hall. All rights reserved.

106 107 108 109 110 111 112 113 114 115 116 117 118 119

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 Outline Topic. Session topic. Session = topic. Connection. create. Topic. Session( false, Session. AUTO_ACKNOWLEDGE ); Topic. Publisher topic. Publisher = topic. Session. create. Publisher( topic ); create Topic. Session obtain Topic. Publisher Object. Message message = topic. Session. create. Object. Message(); // connect to National Weather Service // and publish conditions to topic // National Weather Service Travelers Forecast page URL url = new URL( "http: //iwin. nws. noaa. gov/iwin/us/traveler. html" ); // set up text input stream to read Web page contents in = new Buffered. Reader( new Input. Stream. Reader( url. open. Stream() ) ); // helps determine starting point of data on Web page String separator = "TAV 12"; // locate separator string in Web page while ( !in. read. Line(). starts. With( separator ) ) ; // do nothing Fig. 16. 12 Weather. Publisher will contain Weather. Bean objects class publishes messages to Weather topic. Lines 106 -108 Lines 110 -111 Lines 113 -114 // strings representing headers on Travelers Forecast // Web page for daytime and nighttime weather String day. Header = "CITY WEA HI/LO" ; String night. Header = "CITY WEA LO/HI" ; 2002 Prentice Hall. All rights reserved.

141 142 143 144 145 146 147 148 149 150 151 152 153 154

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

176 177 178 179 180 181 182 183 184 185 186 187 188 189

176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 topic. Publisher. publish( message ); Outline System. out. println( "published message for city: " + weather. get. City. Name() ); input. Line = in. read. Line(); // get next city's info } System. out. println( "Weather information updated. " ); publish message to topic } // end try // process Naming exception from JNDI context catch ( Naming. Exception naming. Exception ) { naming. Exception. print. Stack. Trace(); System. exit( 1 ); } // process JMS exception from connection, // session, publisher or message catch ( JMSException jms. Exception ) { jms. Exception. print. Stack. Trace(); System. exit( 1 ); } Fig. 16. 12 Weather. Publisher class publishes messages to Weather topic. Line 176 // process failure to connect to National Weather Service catch ( java. net. Connect. Exception connect. Exception ) { connect. Exception. print. Stack. Trace(); System. exit( 1 ); } // process other exceptions catch ( Exception exception ) { exception. print. Stack. Trace(); System. exit( 1 ); 2002 Prentice Hall. All rights reserved.

211 212 213 214 215 216 217 218 219 220 221 222 223 }

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

16. 4. 2 Weather Application: Publisher Side (cont. ) Fig. 16. 13 Weather. Publisher

16. 4. 2 Weather Application: Publisher Side (cont. ) Fig. 16. 13 Weather. Publisher publishing weather update messages. 2002 Prentice Hall. All rights reserved.

16. 4. 3 Weather Application: Subscriber Side • Subscribes to Weather topic. – receives

16. 4. 3 Weather Application: Subscriber Side • Subscribes to Weather topic. – receives weather updates for selected cities • Presents GUI for user. 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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

25 26 27 28 29 30 31 32 33 34 35 36 37 38

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

57 58 59 60 61 62 63 64 65 66 67 68 69 70

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 Outline // retrieve topic connection factory // from JNDI context Topic. Connection. Factory topic. Connection. Factory = ( Topic. Connection. Factory ) jndi. Context. lookup( "WEATHER_FACTORY" ); // retrieve topic from JNDI context String topic. Name = "Weather"; obtain Topic. Connection. Factory topic = ( Topic ) jndi. Context. lookup( topic. Name ); Fig. 16. 14 Weather. Subscribe creater. Topic class allows user create Topic. Connection to receive weather updates. // create topic connection topic. Connection = topic. Connection. Factory. create. Topic. Connection(); // create topic session topic. Session = topic. Connection. create. Topic. Session( false, Session. AUTO_ACKNOWLEDGE ); // initialize listener topic. Listener = new Weather. Listener( weather. Display ); } // process Naming exception from JNDI context catch ( Naming. Exception naming. Exception ) { naming. Exception. print. Stack. Trace(); } Line 65 initialize Weather. Listener Lines 68 -69 // process JMS exceptions from topic connection or session catch ( JMSException jms. Exception ) { jms. Exception. print. Stack. Trace(); } // lay out user interface Container container = get. Content. Pane(); container. set. Layout( new Border. Layout() ); create Topic. Session Lines 59 -61 Lines 72 -73 Line 76 2002 Prentice Hall. All rights reserved.

92 93 94 95 96 97 98 99 100 101 102 103 104 105

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 JPanel selection. Panel = new JPanel(); selection. Panel. set. Layout( new Border. Layout() ); Outline JLabel selection. Label = new JLabel( "Select Cities" ); selection. Panel. add( selection. Label, Border. Layout. NORTH ); // create list of cities for which users // can request weather updates cities. List = new JList( cities ); selection. Panel. add( new JScroll. Pane( cities. List ), Border. Layout. CENTER ); JButton get. Weather. Button = new JButton( "Get Weather. . . " ); selection. Panel. add( get. Weather. Button, Border. Layout. SOUTH ); // invoke method get. Weather when get. Weather. Button clicked get. Weather. Button. add. Action. Listener ( new Action. Listener() { Fig. 16. 14 Weather. Subscribe r class allows user to receive weather updates. public void action. Performed ( Action. Event event ) { get. Weather (); } } ); // end call to add. Action. Listener container. add( selection. Panel, Border. Layout. WEST ); container. add( weather. Display, Border. Layout. CENTER ); // invoke method quit when window closed add. Window. Listener( 2002 Prentice Hall. All rights reserved.

127 128 129 130 131 132 133 134 135 136 137 138 139 140

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 Outline new Window. Adapter() { public void window. Closing( Window. Event event ) { quit(); } } ); // end call to add. Window. Listener } // end Weather. Subscriber constructor // get weather information for selected cities public void get. Weather() { // retrieve selected indices int selected. Indices[] = cities. List. get. Selected. Indices(); if ( selected. Indices. length > 0 ) { // if topic subscriber exists, method has // been called before if ( topic. Subscriber != null ) { // close previous topic subscriber try { topic. Subscriber. close(); } Fig. 16. 14 Weather. Subscribe r class allows user to receive weather updates. Line 153 remove previous subscriber so that new subscriber can filter newly selected cities // process JMS exception catch ( JMSException jms. Exception ) { jms. Exception. print. Stack. Trace(); } 2002 Prentice Hall. All rights reserved.

161 162 163 164 165 166 167 168 169 170 171 172 173 174

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 Outline // clear previous cities from display weather. Display. clear. Cities(); } // create message selector to retrieve specified cities String. Buffer message. Selector = new String. Buffer(); message. Selector. append( "City = '" + cities[ selected. Indices[ 0 ] ] + "'" ); for ( int i = 1; i < selected. Indices. length; i++ ) { message. Selector. append( " OR City = '" + cities[ selected. Indices[ i ] ] + "'" ); } // create topic subscriber and subscription try { topic. Subscriber = topic. Session. create. Subscriber( topic, message. Selector. to. String(), false ); topic. Subscriber. set. Message. Listener( topic. Listener topic. Connection. start(); create Message. Selector Fig. 16. 14 Weather. Subscribe r class allows user to receive weather updates. create Topic. Subscriber ); Lines 166 -173 begin receiving messages Lines 177 -178 JOption. Pane. show. Message. Dialog( this, "A weather update should be arriving soon. . . " ); } Line 180 // process JMS exception catch ( JMSException jms. Exception ) { jms. Exception. print. Stack. Trace(); } } // end if } // end method get. Weather 2002 Prentice Hall. All rights reserved.

195 196 197 198 199 200 201 202 203 204 205 206 207 208

195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 Outline // quit Weather. Subscriber application public void quit() { // close connection and subscription to topic try { // close topic subscriber if ( topic. Subscriber != null ) { topic. Subscriber. close(); } // close topic connection topic. Connection. close(); } close subscriber close connection // process JMS exception catch ( JMSException jms. Exception ) { jms. Exception. print. Stack. Trace(); System. exit( 1 ); } System. exit( 0 ); } // end method quit Fig. 16. 14 Weather. Subscribe r class allows user to receive weather updates. Line 203 Line 207 // launch Weather. Subscriber application public static void main( String args [] ) { Weather. Subscriber subscriber = new Weather. Subscriber(); subscriber. pack(); subscriber. set. Visible( true ); } } 2002 Prentice Hall. All rights reserved.

16. 4. 3 Weather Application: Subscriber Side (cont. ) Fig. 16. 15 Weather. Subscriber

16. 4. 3 Weather Application: Subscriber Side (cont. ) Fig. 16. 15 Weather. Subscriber selecting cities for weather updates. 2002 Prentice Hall. All rights reserved.

16. 4. 3 Weather Application: Subscriber Side (cont. ) Fig. 16 Weather. Subscriber having

16. 4. 3 Weather Application: Subscriber Side (cont. ) Fig. 16 Weather. Subscriber having received updated weather conditions. 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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

34 35 36 37 38 39 40 41 42 43 44 45 46 47

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 Outline // get Weather. Bean from Object. Message object. Message = ( Object. Message ) message; Weather. Bean weather. Bean = ( Weather. Bean ) object. Message. get. Object(); // add Weather. Bean to display weather. Display. add. Item( weather. Bean ); } // end if obtain Weather. Bean display contents else { System. out. println( "Expected Object. Message, " + " but received " + message. get. Class(). get. Name() ); } } // end try // process JMS exception from message catch ( JMSException jms. Exception ) { jms. Exception. print. Stack. Trace(); } } // end method on. Message } Fig. 16. 17 Weather. Listener class subscribes to Weather topic to receive weather forecasts. Lines 35 -38 Line 41 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 // Weather. Display. java // Weather. Display extends JPanel to display results // of client's request for weather conditions. package com. deitel. advjhtp 1. jms. weather; Outline // Java core packages import java. awt. *; import java. awt. event. *; import java. util. *; // Java extension packages import javax. swing. *; // Deitel packages import com. deitel. advjhtp 1. rmi. weather. *; public class Weather. Display extends JPanel { // Weather. List. Model and Map for storing Weather. Beans private Weather. List. Model weather. List. Model ; private Map weather. Items; Fig. 16. 18 Weather. Display displays Weather. Beans in a Jlist using a Weather. Cell. Rende rer. // Weather. Display constructor public Weather. Display() { set. Layout( new Border. Layout() ); Image. Icon header. Image = new Image. Icon( Weather. Display. class. get. Resource( "images/header. jpg" ) ); add( new JLabel( header. Image ), Border. Layout. NORTH ); 2002 Prentice Hall. All rights reserved.

33 34 35 36 37 38 39 40 41 42 43 44 45 46

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 // use JList to display updated weather conditions // for requested cities weather. List. Model = new Weather. List. Model(); JList weather. JList = new JList( weather. List. Model ); weather. JList. set. Cell. Renderer( new Weather. Cell. Renderer() ); Outline add( new JScroll. Pane( weather. JList ), Border. Layout. CENTER ); // maintain Weather. Bean items in Hash. Map weather. Items = new Hash. Map(); } // end Weather. Display constructor // add Weather. Bean item to display public void add. Item( Weather. Bean weather ) { String city = weather. get. City. Name(); // check whether city is already in display if ( weather. Items. contains. Key( city ) ) { // if city is in Map, and therefore in display // remove previous Weather. Bean object Weather. Bean previous. Weather = ( Weather. Bean ) weather. Items. remove( city ); weather. List. Model. remove( previous. Weather ); } // add Weather. Bean to Map and Weather. List. Model weather. List. Model. add( weather ); weather. Items. put( city, weather ); Fig. 16. 18 Weather. Display displays Weather. Beans in a Jlist using a Weather. Cell. Rende rer. Lines 56 -58 remove if bean Lines 62 -63 previously existing add new bean to list } // end method add. Item 2002 Prentice Hall. All rights reserved.

66 67 68 69 70 71 72 73 // clear all cities from display

66 67 68 69 70 71 72 73 // clear all cities from display public void clear. Cities() { weather. Items. clear(); weather. List. Model. clear(); } Outline } Fig. 16. 18 Weather. Display displays Weather. Beans in a Jlist using a Weather. Cell. Rende rer. 2002 Prentice Hall. All rights reserved.

16. 4. 4 Weather Application: Configuring and Running 1. Start J 2 EE server

16. 4. 4 Weather Application: Configuring and Running 1. Start J 2 EE server j 2 ee –verbose 2. Create Weather topic (new window) j 2 eeadmin –add. Jms. Destination Weather topic 3. Verify topic selected j 2 eeadmin –list. Jms. Destination 4. Create connection factory j 2 eeadmin –add. Jms. Factory WEATHER_FACTORY topic 5. Start Weather. Publisher java –classpath %J 2 EE_HOME%libj 2 ee. jar; . -Djms. properties=%J 2 EE_HOME%configjms_client. properties com. deitel. advjhtp 1. jms. weather. Weather. Publisher 6. Start Weather. Subscriber java –classpath %J 2 EE_HOME%libj 2 ee. jar; . -Djms. properties=%J 2 EE_HOME%configjms_client. properties com. deitel. advjhtp 1. jmx. weather. Weather. Subscriber 2002 Prentice Hall. All rights reserved.

16. 4. 4 Weather Application: Configuring and Running (cont. ) • To close application

16. 4. 4 Weather Application: Configuring and Running (cont. ) • To close application 1. remove factory j 2 eeadmin –remove. Jms. Factory WEATHER_FACTORY 2. remove topic j 2 eeadmin –remove. Jms. Destination Weather 3. stop J 2 EE server j 2 ee -stop 2002 Prentice Hall. All rights reserved.

16. 5 Message-Driven Enterprise Java. Beans • New type of EJB available in EJB

16. 5 Message-Driven Enterprise Java. Beans • 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. 2002 Prentice Hall. All rights reserved.

16. 5. 1 Voter Application: Overview • Class Voter – posts vote messages to

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 Vote. Collector. EJB – message-bean implementation – delegates message to entity-bean Candidate • Class Candidate – tallies votes – stores results in database Voting • Class Tally. Display – presents GUI with tallies from database 2002 Prentice Hall. All rights reserved.

16. 5. 1 Voter Application: Overview (cont. ) Fig. 16. 19 Voter application overview.

16. 5. 1 Voter Application: Overview (cont. ) Fig. 16. 19 Voter application overview. 2002 Prentice Hall. All rights reserved.

16. 5. 2 Voter Application: Receiver Side • Candidate entity EJB represents – vote

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. 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // Candidate. Home. java // Candidate. Home is the home interface for the Candidate EJB. package com. deitel. advjhtp 1. jms. mdb; Outline // Java core libraries import java. rmi. *; import java. util. *; // Java standard extensions import javax. ejb. *; public interface Candidate. Home extends EJBHome { // find Candidate with given name public Candidate find. By. Primary. Key( String candidate. Name ) throws Remote. Exception, Finder. Exception; // find all Candidates public Collection find. All. Candidates() throws Remote. Exception, Finder. Exception; // create new Candidate EJB public Candidate create( String candidate. Name ) throws Remote. Exception, Create. Exception; } Fig. 16. 20 Candidate. Home locateinterface particular for Candidate EJB. Candidate Lines 15 -16 of locate Collection Candidates Lines 19 -20 create new Candidate with Lines 23 -24 given name and 0 votes 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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

33 34 35 36 37 38 39 40 41 42 43 44 45 46

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 // get Candidate's name public String get. Candidate. Name() { return name; } Outline return candidate name // create new Candidate public String ejb. Create( String candidate. Name ) throws Create. Exception { name = candidate. Name; vote. Count = new Integer( 0 ); initializes new candidate with specified name and Fig. 16. 22 return null; initializes vote count to 0 } Candidate. EJB class to maintain // do post-creation tasks when creating new Candidate candidate tallies. public void ejb. Post. Create( String candidate. Name ) {} // set Entity. Context public void set. Entity. Context( Entity. Context context ) { entity. Context = context; } Lines 34 -37 Lines 40 -47 // unset Entity. Context public void unset. Entity. Context() { entity. Context = null; } // activate Candidate instance public void ejb. Activate() { name = ( String ) entity. Context. get. Primary. Key(); 2002 Prentice Hall. All rights reserved.

68 69 70 71 72 73 74 75 76 77 78 79 80 81

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 } Outline // passivate Candidate instance public void ejb. Passivate() { name = null; } // load Candidate from database public void ejb. Load() {} // store Candidate in database public void ejb. Store() {} // remove Candidate from database public void ejb. Remove() {} } Fig. 16. 22 Candidate. EJB class to maintain candidate tallies. 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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

36 37 38 39 40 41 42 43 44 45 46 47 48 49

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 else { System. out. println( "Expecting " + "Text. Message object, received " + message. get. Class(). get. Name() ); } Outline } // end try // process JMS exception from message catch ( JMSException jms. Exception ) { jms. Exception. print. Stack. Trace(); } } // add vote to corresponding tally private void count. Vote( String vote ) { // Candidate. Home reference for finding/creating Candidates Candidate. Home candidate. Home = null; // find Candidate and increment vote count try { Fig. 16. 23 Vote. Collector. EJB class tallies votes from Votes queue. Lines 60 -67 // look up Candidate EJB Context initial. Context = new Initial. Context(); Object object = initial. Context. lookup( "java: comp/env/ejb/Candidate" ); obtain reference to Candidate EJB candidate. Home = ( Candidate. Home ) Portable. Remote. Object. narrow( object, Candidate. Home. class ); 2002 Prentice Hall. All rights reserved.

69 70 71 72 73 74 75 76 77 78 79 80 81 82

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 Outline // find Candidate for whom the user voted Candidate candidate = candidate. Home. find. By. Primary. Key( vote ); // increment Candidate's vote count candidate. increment. Vote. Count(); } // end try find particular Candidate increment vote count // if Candidate not found, create new Candidate catch ( Finder. Exception finder. Exception ) { // create new Candidate and increment its vote count try { Candidate new. Candidate = candidate. Home. create( vote ); new. Candidate. increment. Vote. Count(); } // handle exceptions creating new Candidate catch ( Exception exception ) { throw new EJBException( exception ); } } // end Finder. Exception catch Fig. 16. 23 Vote. Collector. EJB class tallies votes from Votes queue. create new 70 -71 Candidate Lines if specified candidate name 74 not found Lines 83 -84 // handle exception when looking up Order. Products EJB catch ( Naming. Exception naming. Exception ) { throw new EJBException( naming. Exception ); } // handle exception when invoking Order. Products methods catch ( Remote. Exception remote. Exception ) { throw new EJBException( remote. Exception ); } 2002 Prentice Hall. All rights reserved.

104 105 106 107 108 109 110 111 112 113 114 115 116 117

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 } // end method count. Vote Outline // set message driven context public void set. Message. Driven. Context ( Message. Driven. Context context ) { message. Driven. Context = context; } // create bean instance public void ejb. Create() {} // remove bean instance public void ejb. Remove() {} } Fig. 16. 23 Vote. Collector. EJB class tallies votes from Votes queue. 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

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

32 33 34 35 36 37 38 39 40 41 42 43 44 45

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 // find Candidates and display tallies try { Outline // look up Candidate EJB Context initial. Context = new Initial. Context(); Object object = initial. Context. lookup( "Candidate" ); Candidate. Home candidate. Home = ( Candidate. Home ) Portable. Remote. Object. narrow( object, Candidate. Home. class ); // find all Candidates Collection candidates = candidate. Home. find. All. Candidates(); // add Tally. Panel with candidate name and // vote count for each candidate Iterator iterator = candidates. iterator(); while ( iterator. has. Next() ) { Candidate candidate = ( Candidate ) iterator. next(); // create Tally. Panel for Candidate Tally. Panel tally. Panel = new Tally. Panel( candidate. get. Candidate. Name(), candidate. get. Vote. Count(). int. Value() ); display. Panel. add( tally. Panel ); Fig. 16. 24 lookup all Candidates Tally. Display displays candidate tallies from database. Lines 36 -46 Lines 50 -59 display snapshot of information } } // end try // handle exception finding Candidates catch ( Finder. Exception finder. Exception ) { finder. Exception. print. Stack. Trace(); 2002 Prentice Hall. All rights reserved.

66 67 68 69 70 71 72 73 74 75 76 77 78 79

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 } // handle exception looking up Candidate EJB catch ( Naming. Exception naming. Exception ) { naming. Exception. print. Stack. Trace(); } Outline // handle exception communicating with Candidate catch ( Remote. Exception remote. Exception ) { remote. Exception. print. Stack. Trace(); } } // end Tally. Display constructor // launch Tally. Display application public static void main( String args[] ) { Tally. Display tally. Display = new Tally. Display(); tally. Display. set. Default. Close. Operation ( EXIT_ON_CLOSE ); tally. Display. pack(); tally. Display. set. Visible( true ); } } Fig. 16. 24 Tally. Display displays candidate tallies from database. 2002 Prentice Hall. All rights reserved.

16. 5. 2 Voter Application: Receiver Side (cont. ) Fig. 16. 25 Tally. Display

16. 5. 2 Voter Application: Receiver Side (cont. ) Fig. 16. 25 Tally. Display displays candidate tallies from database. 2002 Prentice Hall. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 // Tally. Panel. java // Tall. Panel is the GUI component which displays // the name and tally for a vote candidate. package com. deitel. advjhtp 1. jms. mdb; Outline // Java core packages import java. awt. *; // Java extension packages import javax. swing. *; public class Tally. Panel extends JPanel { private JLabel name. Label; JText. Field tally. Field; String name; int tally; // Tally. Panel constructor public Tally. Panel( String vote. Name, int vote. Tally ) { name = vote. Name; tally = vote. Tally; Fig. 16. 26 Tally. Panel class displays the name and tally for a candidate. name. Label = new JLabel( name ); tally. Field = new JText. Field( Integer. to. String( tally ), 10 ); tally. Field. set. Editable( false ); tally. Field. set. Background( Color. white ); add( name. Label ); add( tally. Field ); 2002 Prentice Hall. All rights reserved.

33 34 35 36 } // end Tally. Panel constructor Outline } Fig. 16.

33 34 35 36 } // end Tally. Panel constructor Outline } Fig. 16. 26 Tally. Panel class displays the name and tally for a candidate. 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running • Apply to file resource. properties

16. 5. 3 Voter Application: Configuring and Running • Apply to file resource. properties jdbc. Data. Source. number. name=jdbc/Voting jdbc. Data. Source. number. url=jdbc: cloudscape: rmi: Voting. DB; create=true where number is next number in jdbc. Data. Source entries. • Start J 2 EE server j 2 ee –verbose • Create queue j 2 eeadmin –add. Jms. Destination Votes queue • Create connection factory j 2 eeadmin –add. Jms. Factory VOTE_FACTORY queue • Run deploy tool deploytool 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) • Within deploy tool,

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 Vote. Collector. App. ear as file name New Application OK • Add Candidate EJB File -> New Enterprise Bean 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 27 EJB

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 27 EJB JAR settings for Vote. Collector. App application. 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 28 Add

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 28 Add class files for Candidate EJB. 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 29 General

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 29 General settings for Candidate EJB. 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 30 Entity

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 30 Entity settings for Candidate EJB. 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 31 Entity

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 31 Entity tab for Candidate EJB. 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 32 Database

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 32 Database settings for Candidate EJB. 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 33 SQL

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 33 SQL generation for Candidate EJB. 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 34 SQL

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 34 SQL warning for Candidate EJB. 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) • Create Vote. Collector

16. 5. 3 Voter Application: Configuring and Running (cont. ) • Create Vote. Collector File -> New Enterprise Bean 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 35 EJB

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 35 EJB JAR settings for Vote. Collector EJB. 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 36 Add

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 36 Add class file for Vote. Collector EJB. 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 37 General

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 37 General settings for Vote. Collector EJB. 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 38 Transaction

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 38 Transaction management settings for the Vote. Collector EJB 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 39 Message-Driven

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 39 Message-Driven Bean settings for Vote. Collector EJB. 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 40 Enterprise

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 40 Enterprise Bean References for Vote. Collector EJB. 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 41 Setting

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 41 Setting JNDI names for Vote. Collector. App. 2002 Prentice Hall. All rights reserved.

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 42 Deploying

16. 5. 3 Voter Application: Configuring and Running (cont. ) Fig. 16. 42 Deploying the Vote. Collector application. 2002 Prentice Hall. All rights reserved.