In the message-driven bean (RockSurveyMDBean), the persistence related instance variables and the persist(), doCommit(), and doRollback() methods are transferred wholesale from RockSurvey2Bean (see Example: The Rock Survey, Take 2 and Example: The Rock Survey, Take 2 (continued)). Since MDBs don't have a SessionContext, the MessageDrivenContext is used instead to get the UserTransaction object:
ut = mdc.getUserTransaction();
And now, what you've all been waiting for: the MDB's onMessage() method:
public void onMessage( Message msg )
{
try
{
if( msg instanceof TextMessage )
{
TextMessage tm = (TextMessage)( msg );
System.out.println( "Message received: " +
tm.getText() );
return;
}
if( msg instanceof ObjectMessage )
{
System.out.println( "RockSurveyData " +
"ObjectMessage received. " );
ObjectMessage om = (ObjectMessage)( msg );
rsd = (RockSurveyData)om.getObject();
if( persist() )
{
System.out.println( "Table data persisted, " );
}
else
{
System.out.println( "Problem persisting data." );
}
return;
}
else
{
System.out.println( "Unknown Message type: " +
msg.getClass().getName() );
}
}
catch( JMSException jmse )
{
System.out.println( "JMSException: " +
jmse.getMessage() );
jmse.printStackTrace();
}
} // end onMessage
onMessage() is prepared to handle TextMessage and ObjectMessage type messages. If it receives a TextMessage, the text is extracted and printed. For ObjectMessages, the contained object is retrieved into a RockSurveyData. Then the persist() method is invoked to update the database and the result is printed. Any other message types are noted and then ignored.