001: package org.mockejb.jms;
002:
003: import java.util.*;
004: import javax.jms.*;
005:
006: /**
007: * Destination where messages are sent.
008: * Messages are kept in list, ordered by priority.
009: *
010: * @author Dimitar Gospodinov
011: */
012: abstract class MockDestination implements Destination {
013:
014: private String name;
015: // Need to keep copy of each message in order to be able to test synchronous consumers
016: private List messages = new ArrayList();
017: // Consumers interested in this destination
018: private List consumers = new ArrayList();
019:
020: /**
021: * Creates new destination with name <code>name</code>
022: * @param name
023: */
024: MockDestination(String name) {
025: this .name = name;
026: }
027:
028: /**
029: * Returns this destination's name.
030: */
031: public String getName() {
032: return name;
033: }
034:
035: /**
036: * Adds message <code>msg</code> to this destination.
037: * @param msg
038: * @throws JMSException
039: */
040: void addMessage(Message msg) throws JMSException {
041:
042: MessageImpl sentMsg = MessageUtility.copyMessage(msg, true);
043:
044: int i = 0;
045: while (i < messages.size()) {
046: if (msg.getJMSPriority() > ((Message) messages.get(i))
047: .getJMSPriority()) {
048: break;
049: }
050: i++;
051: }
052: messages.add(i, sentMsg);
053:
054: // Send message to all registered consumers
055: Iterator it = consumers.iterator();
056: while (it.hasNext()) {
057: MockConsumer cons = (MockConsumer) it.next();
058: cons.consume(sentMsg);
059: }
060: }
061:
062: /**
063: * Removes all messages from this destination.
064: *
065: */
066: public void clear() {
067: messages.clear();
068: }
069:
070: /**
071: * Returns string representation of this destination.
072: */
073: public String toString() {
074: return this .getClass().getName() + " with name: " + getName();
075: }
076:
077: /**
078: * Returns number of messages in this destination.
079: */
080: public int size() {
081: return messages.size();
082: }
083:
084: /**
085: * Retrieves message at index <code>index</code>.
086: * @param index
087: */
088: public Message getMessageAt(int index) {
089: return (Message) messages.get(index);
090: }
091:
092: /**
093: * Retruns ordered <code>List</code> with all messages sent to
094: * this destination. Higher priority messages appear first in the list.
095: */
096: public List getMessages() {
097: return messages;
098: }
099:
100: void registerConsumer(MockConsumer consumer) throws JMSException {
101: cleanConsumers();
102: consumer.consume(messages);
103: consumers.add(consumer);
104: }
105:
106: void removeConsumer(MockConsumer consumer) {
107: consumers.remove(consumer);
108: }
109:
110: private void cleanConsumers() {
111: ListIterator it = consumers.listIterator();
112: while (it.hasNext()) {
113: MockConsumer cons = (MockConsumer) it.next();
114: if (cons.isClosed()) {
115: it.remove();
116: }
117: }
118: }
119:
120: }
|