001    package com.mockrunner.mock.jms;
002    
003    import java.util.Iterator;
004    import java.util.List;
005    
006    import javax.jms.JMSException;
007    import javax.jms.Message;
008    import javax.jms.MessageListener;
009    import javax.jms.Queue;
010    
011    /**
012     * Mock implementation of JMS <code>Queue</code>.
013     */
014    public class MockQueue extends MockDestination implements Queue
015    {
016        private String name;
017        
018        public MockQueue(String name)
019        {
020            this.name = name;
021        }
022        
023        public String getQueueName() throws JMSException
024        {
025            return name;
026        }
027        
028        /**
029         * Adds a message to this <code>Queue</code> that will
030         * be propagated to the corresponding receiver. Only one
031         * receiver will get the message. The order is not
032         * predictable.
033         * @param message the message
034         */
035        public void addMessage(Message message) throws JMSException
036        {
037            addReceivedMessage(message);    
038            boolean isConsumed = false;
039            Iterator sessionsIterator = sessionSet().iterator();
040            while(sessionsIterator.hasNext() && !isConsumed)
041            {
042                MockSession session = (MockSession)sessionsIterator.next();
043                MessageListener globalListener = session.getMessageListener();
044                if(null != globalListener)
045                {
046                    globalListener.onMessage(message);
047                    isConsumed = true;
048                    acknowledgeMessage(message, session);
049                }
050                else
051                {
052                    List receivers = session.getQueueTransmissionManager().getQueueReceiverList(name);
053                    for(int ii = 0; ii < receivers.size() && !isConsumed; ii++)
054                    {
055                        MockQueueReceiver receiver = (MockQueueReceiver)receivers.get(ii);
056                        if(receiver.canConsume(message))
057                        {
058                            receiver.receiveMessage(message);
059                            isConsumed = true;
060                            acknowledgeMessage(message, session);
061                        }
062                    }
063                }
064            }
065            if(!isConsumed)
066            {
067                addCurrentMessage(message);
068            }
069        }
070    }