Server.java is a server that converts the text of requests to upper case and returns the result to the original sender. It starts by creating a connection and a session:
// Load JNDI properties
Properties properties=new Properties();
properties.load(this.getClass().getResourceAsStream("requestResponse.properties"));
//Create the initial context
Context ctx=new InitialContext(properties);
// Lookup the connection factory
ConnectionFactory conFac = (ConnectionFactory) ctx.lookup("qpidConnectionfactory");
// create the connection
QueueConnection connection = (QueueConnection) conFac.createConnection();
connection.setExceptionListener(new ExceptionListener()
{
public void onException(JMSException jmse)
{
// The connection may have broken invoke reconnect code if available.
System.err.println(CLASS + ": The sample received an exception through the ExceptionListener");
System.exit(0);
}
});
Session session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Next, it creates a Consumer to receive requests from the request queue, and a Producer to send responses:
Queue destination = (Queue) ctx.lookup("requestQueue");
MessageConsumer messageConsumer = session.createConsumer(destination);
MessageProducer messageProducer;
Now we start the connection so we can receive requests:
connection.start();
When a message is received, it is checked to see if it is a text message and has a ReplyTo field; if it does, the request is converted to upper case and the response is sent:
Message requestMessage;
TextMessage responseMessage;
boolean end=false;
while (!end)
{
requestMessage=messageConsumer.receive();
String text;
if (requestMessage instanceof TextMessage)
{
text=((TextMessage) requestMessage).getText();
}
else
{
byte[] body=new byte[(int) ((BytesMessage) requestMessage).getBodyLength()];
((BytesMessage) requestMessage).readBytes(body);
text=new String(body);
}
if (requestMessage.getJMSReplyTo() != null)
{
responseMessage=session.createTextMessage();
responseMessage.setText(text.toUpperCase());
messageProducer=session.createProducer(requestMessage.getJMSReplyTo());
messageProducer.send(responseMessage);
}
}
Then we close the connection and the JNDI context:
connection.close(); getInitialContext().close();