package org.jboss.test.jmsra.bean;
import java.rmi.RemoteException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.EJBException;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueConnection;
import javax.jms.QueueSession;
import javax.jms.QueueReceiver;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.Message;
import javax.jms.JMSException;
import org.apache.log4j.Category;
public class QueueRecBean implements SessionBean
{
private final Category log = Category.getInstance(this.getClass());
private static final String CONNECTION_JNDI = "java:comp/env/jms/MyQueueConnection";
private QueueConnectionFactory factory = null;
private static final String QUEUE_JNDI = "java:comp/env/jms/QueueName";
private SessionContext ctx = null;
private Queue queue = null;
public QueueRecBean()
{
}
public void setSessionContext(SessionContext ctx)
{
this.ctx = ctx;
}
public void ejbCreate()
{
try
{
Context context = new InitialContext();
queue = (Queue) context.lookup(QUEUE_JNDI);
factory = (QueueConnectionFactory) context.lookup(CONNECTION_JNDI);
}
catch (Exception ex)
{
log.debug("failed", ex);
throw new EJBException(ex.toString());
}
}
public void ejbRemove() throws RemoteException
{
}
public void ejbActivate()
{
}
public void ejbPassivate()
{
}
public int getMessage()
{
QueueConnection queueConnection = null;
QueueSession queueSession = null;
int ret;
try
{
queueConnection = factory.createQueueConnection();
queueConnection.start();
queueSession = queueConnection.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
QueueReceiver queueReceiver = queueSession.createReceiver(queue);
log.info("Waiting for message");
Message msg = queueReceiver.receive(500L);
if (msg != null)
{
log.info("Recived message: " + msg);
int nr = msg.getIntProperty(Publisher.JMS_MESSAGE_NR);
log.debug("nr: " + nr);
ret = nr;
}
else
{
log.info("NO message recived");
ret = -1;
}
}
catch (JMSException ex)
{
log.warn("failed", ex);
ctx.setRollbackOnly();
throw new EJBException(ex.toString());
}
finally
{
if (queueConnection != null)
{
try
{
queueConnection.close();
}
catch (Exception e)
{
log.debug("failed", e);
}
}
}
return ret;
}
}