More checkstyle violation fixes

git-svn-id: https://svn.apache.org/repos/asf/activemq/trunk@564679 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Hiram R. Chirino 2007-08-10 16:57:01 +00:00
parent 9cde47f42c
commit ecf89a60bf
209 changed files with 2081 additions and 1866 deletions

View File

@ -61,8 +61,6 @@ public class ActiveMQConnectionConsumer implements ConnectionConsumer, ActiveMQD
private ConsumerInfo consumerInfo; private ConsumerInfo consumerInfo;
private boolean closed; private boolean closed;
protected final List messageQueue = Collections.synchronizedList(new LinkedList());
/** /**
* Create a ConnectionConsumer * Create a ConnectionConsumer
* *

View File

@ -118,6 +118,22 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne
this(createURI(brokerURL)); this(createURI(brokerURL));
} }
public ActiveMQConnectionFactory(URI brokerURL) {
setBrokerURL(brokerURL.toString());
}
public ActiveMQConnectionFactory(String userName, String password, URI brokerURL) {
setUserName(userName);
setPassword(password);
setBrokerURL(brokerURL.toString());
}
public ActiveMQConnectionFactory(String userName, String password, String brokerURL) {
setUserName(userName);
setPassword(password);
setBrokerURL(brokerURL);
}
/** /**
* Returns a copy of the given connection factory * Returns a copy of the given connection factory
*/ */
@ -142,22 +158,6 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne
} }
} }
public ActiveMQConnectionFactory(URI brokerURL) {
setBrokerURL(brokerURL.toString());
}
public ActiveMQConnectionFactory(String userName, String password, URI brokerURL) {
setUserName(userName);
setPassword(password);
setBrokerURL(brokerURL.toString());
}
public ActiveMQConnectionFactory(String userName, String password, String brokerURL) {
setUserName(userName);
setPassword(password);
setBrokerURL(brokerURL);
}
/** /**
* @return Returns the Connection. * @return Returns the Connection.
*/ */
@ -252,8 +252,9 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne
transport.start(); transport.start();
if (clientID != null) if (clientID != null) {
connection.setDefaultClientID(clientID); connection.setDefaultClientID(clientID);
}
return connection; return connection;
} catch (JMSException e) { } catch (JMSException e) {

View File

@ -19,6 +19,7 @@ package org.apache.activemq;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map;
import javax.jms.IllegalStateException; import javax.jms.IllegalStateException;
import javax.jms.InvalidDestinationException; import javax.jms.InvalidDestinationException;
@ -100,7 +101,7 @@ public class ActiveMQInputStream extends InputStream implements ActiveMQDispatch
// Allows the options on the destination to configure the consumerInfo // Allows the options on the destination to configure the consumerInfo
if (dest.getOptions() != null) { if (dest.getOptions() != null) {
HashMap options = new HashMap(dest.getOptions()); Map<String, String> options = new HashMap<String, String>(dest.getOptions());
IntrospectionSupport.setProperties(this.info, options, "consumer."); IntrospectionSupport.setProperties(this.info, options, "consumer.");
} }
@ -145,8 +146,9 @@ public class ActiveMQInputStream extends InputStream implements ActiveMQDispatch
throw JMSExceptionSupport.create(e); throw JMSExceptionSupport.create(e);
} }
if (md == null || unconsumedMessages.isClosed() || md.getMessage().isExpired()) if (md == null || unconsumedMessages.isClosed() || md.getMessage().isExpired()) {
return null; return null;
}
deliveredCounter++; deliveredCounter++;
if ((0.75 * info.getPrefetchSize()) <= deliveredCounter) { if ((0.75 * info.getPrefetchSize()) <= deliveredCounter) {
@ -172,15 +174,17 @@ public class ActiveMQInputStream extends InputStream implements ActiveMQDispatch
public int read() throws IOException { public int read() throws IOException {
fillBuffer(); fillBuffer();
if (eosReached) if (eosReached) {
return -1; return -1;
}
return buffer[pos++] & 0xff; return buffer[pos++] & 0xff;
} }
public int read(byte[] b, int off, int len) throws IOException { public int read(byte[] b, int off, int len) throws IOException {
fillBuffer(); fillBuffer();
if (eosReached) if (eosReached) {
return -1; return -1;
}
int max = Math.min(len, buffer.length - pos); int max = Math.min(len, buffer.length - pos);
System.arraycopy(buffer, pos, b, off, max); System.arraycopy(buffer, pos, b, off, max);
@ -190,8 +194,9 @@ public class ActiveMQInputStream extends InputStream implements ActiveMQDispatch
} }
private void fillBuffer() throws IOException { private void fillBuffer() throws IOException {
if (eosReached || (buffer != null && buffer.length > pos)) if (eosReached || (buffer != null && buffer.length > pos)) {
return; return;
}
try { try {
while (true) { while (true) {
ActiveMQMessage m = receive(); ActiveMQMessage m = receive();

View File

@ -16,9 +16,11 @@
*/ */
package org.apache.activemq; package org.apache.activemq;
import java.util.LinkedHashMap; import java.util.Map;
import javax.jms.JMSException; import javax.jms.JMSException;
import javax.jms.Message; import javax.jms.Message;
import org.apache.activemq.broker.region.MessageReference; import org.apache.activemq.broker.region.MessageReference;
import org.apache.activemq.command.MessageId; import org.apache.activemq.command.MessageId;
import org.apache.activemq.command.ProducerId; import org.apache.activemq.command.ProducerId;
@ -36,7 +38,7 @@ public class ActiveMQMessageAudit {
private static final int DEFAULT_WINDOW_SIZE = 1024; private static final int DEFAULT_WINDOW_SIZE = 1024;
private static final int MAXIMUM_PRODUCER_COUNT = 128; private static final int MAXIMUM_PRODUCER_COUNT = 128;
private int windowSize; private int windowSize;
private LinkedHashMap<Object, BitArrayBin> map; private Map<Object, BitArrayBin> map;
/** /**
* Default Constructor windowSize = 1024, maximumNumberOfProducersToTrack = * Default Constructor windowSize = 1024, maximumNumberOfProducersToTrack =

View File

@ -20,6 +20,7 @@ import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -178,7 +179,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
// Allows the options on the destination to configure the consumerInfo // Allows the options on the destination to configure the consumerInfo
if (dest.getOptions() != null) { if (dest.getOptions() != null) {
HashMap options = new HashMap(dest.getOptions()); Map<String, String> options = new HashMap<String, String>(dest.getOptions());
IntrospectionSupport.setProperties(this.info, options, "consumer."); IntrospectionSupport.setProperties(this.info, options, "consumer.");
} }
@ -208,8 +209,9 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
throw e; throw e;
} }
if (session.connection.isStarted()) if (session.connection.isStarted()) {
start(); start();
}
} }
public StatsImpl getStats() { public StatsImpl getStats() {
@ -345,13 +347,15 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
this.messageListener = listener; this.messageListener = listener;
if (listener != null) { if (listener != null) {
boolean wasRunning = session.isRunning(); boolean wasRunning = session.isRunning();
if (wasRunning) if (wasRunning) {
session.stop(); session.stop();
}
session.redispatch(this, unconsumedMessages); session.redispatch(this, unconsumedMessages);
if (wasRunning) if (wasRunning) {
session.start(); session.start();
}
} }
} }
@ -436,8 +440,9 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
sendPullCommand(0); sendPullCommand(0);
MessageDispatch md = dequeue(-1); MessageDispatch md = dequeue(-1);
if (md == null) if (md == null) {
return null; return null;
}
beforeMessageIsConsumed(md); beforeMessageIsConsumed(md);
afterMessageIsConsumed(md, false); afterMessageIsConsumed(md, false);
@ -501,8 +506,9 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
md = dequeue(timeout); md = dequeue(timeout);
} }
if (md == null) if (md == null) {
return null; return null;
}
beforeMessageIsConsumed(md); beforeMessageIsConsumed(md);
afterMessageIsConsumed(md, false); afterMessageIsConsumed(md, false);
@ -532,8 +538,9 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
md = dequeue(0); md = dequeue(0);
} }
if (md == null) if (md == null) {
return null; return null;
}
beforeMessageIsConsumed(md); beforeMessageIsConsumed(md);
afterMessageIsConsumed(md, false); afterMessageIsConsumed(md, false);
@ -695,14 +702,16 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
} }
private void afterMessageIsConsumed(MessageDispatch md, boolean messageExpired) throws JMSException { private void afterMessageIsConsumed(MessageDispatch md, boolean messageExpired) throws JMSException {
if (unconsumedMessages.isClosed()) if (unconsumedMessages.isClosed()) {
return; return;
}
if (messageExpired) { if (messageExpired) {
ackLater(md, MessageAck.DELIVERED_ACK_TYPE); ackLater(md, MessageAck.DELIVERED_ACK_TYPE);
} else { } else {
stats.onMessage(); stats.onMessage();
if (session.isTransacted()) { if( session.isTransacted() ) {
} else if (session.isAutoAcknowledge()) { // Do nothing.
} else if(session.isAutoAcknowledge()) {
if (!deliveredMessages.isEmpty()) { if (!deliveredMessages.isEmpty()) {
if (optimizeAcknowledge) { if (optimizeAcknowledge) {
if (deliveryingAcknowledgements.compareAndSet(false, true)) { if (deliveryingAcknowledgements.compareAndSet(false, true)) {
@ -770,7 +779,8 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
// When using DUPS ok, we do a real ack. // When using DUPS ok, we do a real ack.
if (ackType == MessageAck.STANDARD_ACK_TYPE) { if (ackType == MessageAck.STANDARD_ACK_TYPE) {
deliveredCounter = additionalWindowSize = 0; deliveredCounter = 0;
additionalWindowSize = 0;
} }
} }
} }
@ -782,8 +792,9 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
* @throws JMSException * @throws JMSException
*/ */
public void acknowledge() throws JMSException { public void acknowledge() throws JMSException {
if (deliveredMessages.isEmpty()) if (deliveredMessages.isEmpty()) {
return; return;
}
// Acknowledge the last message. // Acknowledge the last message.
MessageDispatch lastMd = deliveredMessages.get(0); MessageDispatch lastMd = deliveredMessages.get(0);
@ -822,13 +833,14 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
} }
} }
} }
if (deliveredMessages.isEmpty()) if (deliveredMessages.isEmpty()) {
return; return;
}
// Only increase the redlivery delay after the first redelivery.. // Only increase the redlivery delay after the first redelivery..
if (rollbackCounter > 0) if (rollbackCounter > 0) {
redeliveryDelay = redeliveryPolicy.getRedeliveryDelay(redeliveryDelay); redeliveryDelay = redeliveryPolicy.getRedeliveryDelay(redeliveryDelay);
}
rollbackCounter++; rollbackCounter++;
if (redeliveryPolicy.getMaximumRedeliveries() != RedeliveryPolicy.NO_MAXIMUM_REDELIVERIES && rollbackCounter > redeliveryPolicy.getMaximumRedeliveries()) { if (redeliveryPolicy.getMaximumRedeliveries() != RedeliveryPolicy.NO_MAXIMUM_REDELIVERIES && rollbackCounter > redeliveryPolicy.getMaximumRedeliveries()) {
// We need to NACK the messages so that they get sent to the // We need to NACK the messages so that they get sent to the
@ -858,8 +870,9 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
Scheduler.executeAfterDelay(new Runnable() { Scheduler.executeAfterDelay(new Runnable() {
public void run() { public void run() {
try { try {
if (started.get()) if (started.get()) {
start(); start();
}
} catch (JMSException e) { } catch (JMSException e) {
session.connection.onAsyncException(e); session.connection.onAsyncException(e);
} }

View File

@ -17,6 +17,7 @@
package org.apache.activemq; package org.apache.activemq;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import javax.jms.Destination; import javax.jms.Destination;
@ -70,10 +71,10 @@ import org.apache.activemq.util.IntrospectionSupport;
public class ActiveMQMessageProducer extends ActiveMQMessageProducerSupport implements StatsCapable, Disposable { public class ActiveMQMessageProducer extends ActiveMQMessageProducerSupport implements StatsCapable, Disposable {
protected ProducerInfo info; protected ProducerInfo info;
protected boolean closed;
private JMSProducerStatsImpl stats; private JMSProducerStatsImpl stats;
private AtomicLong messageSequence; private AtomicLong messageSequence;
protected boolean closed;
private long startTime; private long startTime;
private MessageTransformer transformer; private MessageTransformer transformer;
private UsageManager producerWindow; private UsageManager producerWindow;
@ -83,7 +84,7 @@ public class ActiveMQMessageProducer extends ActiveMQMessageProducerSupport impl
this.info = new ProducerInfo(producerId); this.info = new ProducerInfo(producerId);
this.info.setWindowSize(session.connection.getProducerWindowSize()); this.info.setWindowSize(session.connection.getProducerWindowSize());
if (destination != null && destination.getOptions() != null) { if (destination != null && destination.getOptions() != null) {
HashMap options = new HashMap(destination.getOptions()); Map<String, String> options = new HashMap<String, String>(destination.getOptions());
IntrospectionSupport.setProperties(this.info, options, "producer."); IntrospectionSupport.setProperties(this.info, options, "producer.");
} }
this.info.setDestination(destination); this.info.setDestination(destination);

View File

@ -39,11 +39,12 @@ import org.apache.activemq.util.IOExceptionSupport;
public class ActiveMQOutputStream extends OutputStream implements Disposable { public class ActiveMQOutputStream extends OutputStream implements Disposable {
// Send down 64k messages. // Send down 64k messages.
final byte buffer[] = new byte[64 * 1024];
protected int count; protected int count;
final byte buffer[] = new byte[64 * 1024];
private final ActiveMQConnection connection; private final ActiveMQConnection connection;
private final HashMap properties; private final Map<String, Object> properties;
private final ProducerInfo info; private final ProducerInfo info;
private long messageSequence; private long messageSequence;
@ -52,13 +53,13 @@ public class ActiveMQOutputStream extends OutputStream implements Disposable {
private final int priority; private final int priority;
private final long timeToLive; private final long timeToLive;
public ActiveMQOutputStream(ActiveMQConnection connection, ProducerId producerId, ActiveMQDestination destination, Map properties, int deliveryMode, int priority, public ActiveMQOutputStream(ActiveMQConnection connection, ProducerId producerId, ActiveMQDestination destination, Map<String, Object> properties, int deliveryMode, int priority,
long timeToLive) throws JMSException { long timeToLive) throws JMSException {
this.connection = connection; this.connection = connection;
this.deliveryMode = deliveryMode; this.deliveryMode = deliveryMode;
this.priority = priority; this.priority = priority;
this.timeToLive = timeToLive; this.timeToLive = timeToLive;
this.properties = properties == null ? null : new HashMap(properties); this.properties = properties == null ? null : new HashMap<String, Object>(properties);
if (destination == null) { if (destination == null) {
throw new InvalidDestinationException("Don't understand null destinations"); throw new InvalidDestinationException("Don't understand null destinations");

View File

@ -109,8 +109,9 @@ public class ActiveMQQueueBrowser implements QueueBrowser, Enumeration {
} }
private void destroyConsumer() { private void destroyConsumer() {
if (consumer == null) if (consumer == null) {
return; return;
}
try { try {
consumer.close(); consumer.close();
consumer = null; consumer = null;
@ -130,8 +131,9 @@ public class ActiveMQQueueBrowser implements QueueBrowser, Enumeration {
public Enumeration getEnumeration() throws JMSException { public Enumeration getEnumeration() throws JMSException {
checkClosed(); checkClosed();
if (consumer == null) if (consumer == null) {
consumer = createConsumer(); consumer = createConsumer();
}
return this; return this;
} }
@ -148,8 +150,9 @@ public class ActiveMQQueueBrowser implements QueueBrowser, Enumeration {
while (true) { while (true) {
synchronized (this) { synchronized (this) {
if (consumer == null) if (consumer == null) {
return false; return false;
}
} }
if (consumer.getMessageSize() > 0) { if (consumer.getMessageSize() > 0) {
@ -172,14 +175,16 @@ public class ActiveMQQueueBrowser implements QueueBrowser, Enumeration {
while (true) { while (true) {
synchronized (this) { synchronized (this) {
if (consumer == null) if (consumer == null) {
return null; return null;
}
} }
try { try {
Message answer = consumer.receiveNoWait(); Message answer = consumer.receiveNoWait();
if (answer != null) if (answer != null) {
return answer; return answer;
}
} catch (JMSException e) { } catch (JMSException e) {
this.session.connection.onAsyncException(e); this.session.connection.onAsyncException(e);
return null; return null;

View File

@ -105,8 +105,9 @@ public class ActiveMQQueueSession implements QueueSession {
* @throws JMSException * @throws JMSException
*/ */
public MessageConsumer createConsumer(Destination destination) throws JMSException { public MessageConsumer createConsumer(Destination destination) throws JMSException {
if (destination instanceof Topic) if (destination instanceof Topic) {
throw new InvalidDestinationException("Topics are not supported by a QueueSession"); throw new InvalidDestinationException("Topics are not supported by a QueueSession");
}
return next.createConsumer(destination); return next.createConsumer(destination);
} }
@ -117,8 +118,9 @@ public class ActiveMQQueueSession implements QueueSession {
* @throws JMSException * @throws JMSException
*/ */
public MessageConsumer createConsumer(Destination destination, String messageSelector) throws JMSException { public MessageConsumer createConsumer(Destination destination, String messageSelector) throws JMSException {
if (destination instanceof Topic) if (destination instanceof Topic) {
throw new InvalidDestinationException("Topics are not supported by a QueueSession"); throw new InvalidDestinationException("Topics are not supported by a QueueSession");
}
return next.createConsumer(destination, messageSelector); return next.createConsumer(destination, messageSelector);
} }
@ -197,8 +199,9 @@ public class ActiveMQQueueSession implements QueueSession {
* @throws JMSException * @throws JMSException
*/ */
public MessageProducer createProducer(Destination destination) throws JMSException { public MessageProducer createProducer(Destination destination) throws JMSException {
if (destination instanceof Topic) if (destination instanceof Topic) {
throw new InvalidDestinationException("Topics are not supported by a QueueSession"); throw new InvalidDestinationException("Topics are not supported by a QueueSession");
}
return next.createProducer(destination); return next.createProducer(destination);
} }

View File

@ -194,8 +194,8 @@ public class ActiveMQSession implements Session, QueueSession, TopicSession, Sta
protected final ActiveMQSessionExecutor executor = new ActiveMQSessionExecutor(this); protected final ActiveMQSessionExecutor executor = new ActiveMQSessionExecutor(this);
protected final AtomicBoolean started = new AtomicBoolean(false); protected final AtomicBoolean started = new AtomicBoolean(false);
protected final CopyOnWriteArrayList consumers = new CopyOnWriteArrayList(); protected final CopyOnWriteArrayList<ActiveMQMessageConsumer> consumers = new CopyOnWriteArrayList<ActiveMQMessageConsumer>();
protected final CopyOnWriteArrayList producers = new CopyOnWriteArrayList(); protected final CopyOnWriteArrayList<ActiveMQMessageProducer> producers = new CopyOnWriteArrayList<ActiveMQMessageProducer>();
protected boolean closed; protected boolean closed;
protected boolean asyncDispatch; protected boolean asyncDispatch;
@ -235,8 +235,9 @@ public class ActiveMQSession implements Session, QueueSession, TopicSession, Sta
setTransformer(connection.getTransformer()); setTransformer(connection.getTransformer());
setBlobTransferPolicy(connection.getBlobTransferPolicy()); setBlobTransferPolicy(connection.getBlobTransferPolicy());
if (connection.isStarted()) if (connection.isStarted()) {
start(); start();
}
} }
@ -495,7 +496,7 @@ public class ActiveMQSession implements Session, QueueSession, TopicSession, Sta
*/ */
public boolean getTransacted() throws JMSException { public boolean getTransacted() throws JMSException {
checkClosed(); checkClosed();
return ((acknowledgementMode == Session.SESSION_TRANSACTED) || (transactionContext.isInXATransaction())); return (acknowledgementMode == Session.SESSION_TRANSACTED) || (transactionContext.isInXATransaction());
} }
/** /**
@ -588,15 +589,15 @@ public class ActiveMQSession implements Session, QueueSession, TopicSession, Sta
void clearMessagesInProgress() { void clearMessagesInProgress() {
executor.clearMessagesInProgress(); executor.clearMessagesInProgress();
for (Iterator iter = consumers.iterator(); iter.hasNext();) { for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer)iter.next(); ActiveMQMessageConsumer consumer = iter.next();
consumer.clearMessagesInProgress(); consumer.clearMessagesInProgress();
} }
} }
void deliverAcks() { void deliverAcks() {
for (Iterator iter = consumers.iterator(); iter.hasNext();) { for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer)iter.next(); ActiveMQMessageConsumer consumer = iter.next();
consumer.deliverAcks(); consumer.deliverAcks();
} }
} }
@ -607,14 +608,14 @@ public class ActiveMQSession implements Session, QueueSession, TopicSession, Sta
try { try {
executor.stop(); executor.stop();
for (Iterator iter = consumers.iterator(); iter.hasNext();) { for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer)iter.next(); ActiveMQMessageConsumer consumer = iter.next();
consumer.dispose(); consumer.dispose();
} }
consumers.clear(); consumers.clear();
for (Iterator iter = producers.iterator(); iter.hasNext();) { for (Iterator<ActiveMQMessageProducer> iter = producers.iterator(); iter.hasNext();) {
ActiveMQMessageProducer producer = (ActiveMQMessageProducer)iter.next(); ActiveMQMessageProducer producer = iter.next();
producer.dispose(); producer.dispose();
} }
producers.clear(); producers.clear();
@ -684,8 +685,8 @@ public class ActiveMQSession implements Session, QueueSession, TopicSession, Sta
throw new IllegalStateException("This session is transacted"); throw new IllegalStateException("This session is transacted");
} }
for (Iterator iter = consumers.iterator(); iter.hasNext();) { for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
ActiveMQMessageConsumer c = (ActiveMQMessageConsumer)iter.next(); ActiveMQMessageConsumer c = iter.next();
c.rollback(); c.rollback();
} }
@ -1422,8 +1423,8 @@ public class ActiveMQSession implements Session, QueueSession, TopicSession, Sta
* @see javax.jms.Session#CLIENT_ACKNOWLEDGE * @see javax.jms.Session#CLIENT_ACKNOWLEDGE
*/ */
public void acknowledge() throws JMSException { public void acknowledge() throws JMSException {
for (Iterator iter = consumers.iterator(); iter.hasNext();) { for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
ActiveMQMessageConsumer c = (ActiveMQMessageConsumer)iter.next(); ActiveMQMessageConsumer c = iter.next();
c.acknowledge(); c.acknowledge();
} }
} }
@ -1486,8 +1487,8 @@ public class ActiveMQSession implements Session, QueueSession, TopicSession, Sta
*/ */
protected void start() throws JMSException { protected void start() throws JMSException {
started.set(true); started.set(true);
for (Iterator iter = consumers.iterator(); iter.hasNext();) { for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
ActiveMQMessageConsumer c = (ActiveMQMessageConsumer)iter.next(); ActiveMQMessageConsumer c = iter.next();
c.start(); c.start();
} }
executor.start(); executor.start();
@ -1500,8 +1501,8 @@ public class ActiveMQSession implements Session, QueueSession, TopicSession, Sta
*/ */
protected void stop() throws JMSException { protected void stop() throws JMSException {
for (Iterator iter = consumers.iterator(); iter.hasNext();) { for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
ActiveMQMessageConsumer c = (ActiveMQMessageConsumer)iter.next(); ActiveMQMessageConsumer c = iter.next();
c.stop(); c.stop();
} }
@ -1716,8 +1717,8 @@ public class ActiveMQSession implements Session, QueueSession, TopicSession, Sta
} }
Collections.reverse(c); Collections.reverse(c);
for (Iterator iter = c.iterator(); iter.hasNext();) { for (Iterator<MessageDispatch> iter = c.iterator(); iter.hasNext();) {
MessageDispatch md = (MessageDispatch)iter.next(); MessageDispatch md = iter.next();
executor.executeFirst(md); executor.executeFirst(md);
} }
@ -1790,8 +1791,8 @@ public class ActiveMQSession implements Session, QueueSession, TopicSession, Sta
if (messageListener != null) { if (messageListener != null) {
throw new IllegalStateException("Cannot synchronously receive a message when a MessageListener is set"); throw new IllegalStateException("Cannot synchronously receive a message when a MessageListener is set");
} }
for (Iterator i = consumers.iterator(); i.hasNext();) { for (Iterator<ActiveMQMessageConsumer> i = consumers.iterator(); i.hasNext();) {
ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer)i.next(); ActiveMQMessageConsumer consumer = i.next();
if (consumer.getMessageListener() != null) { if (consumer.getMessageListener() != null) {
throw new IllegalStateException("Cannot synchronously receive a message when a MessageListener is set"); throw new IllegalStateException("Cannot synchronously receive a message when a MessageListener is set");
} }
@ -1799,15 +1800,15 @@ public class ActiveMQSession implements Session, QueueSession, TopicSession, Sta
} }
protected void setOptimizeAcknowledge(boolean value) { protected void setOptimizeAcknowledge(boolean value) {
for (Iterator iter = consumers.iterator(); iter.hasNext();) { for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
ActiveMQMessageConsumer c = (ActiveMQMessageConsumer)iter.next(); ActiveMQMessageConsumer c = iter.next();
c.setOptimizeAcknowledge(value); c.setOptimizeAcknowledge(value);
} }
} }
protected void setPrefetchSize(ConsumerId id, int prefetch) { protected void setPrefetchSize(ConsumerId id, int prefetch) {
for (Iterator iter = consumers.iterator(); iter.hasNext();) { for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
ActiveMQMessageConsumer c = (ActiveMQMessageConsumer)iter.next(); ActiveMQMessageConsumer c = iter.next();
if (c.getConsumerId().equals(id)) { if (c.getConsumerId().equals(id)) {
c.setPrefetchSize(prefetch); c.setPrefetchSize(prefetch);
break; break;
@ -1816,8 +1817,8 @@ public class ActiveMQSession implements Session, QueueSession, TopicSession, Sta
} }
protected void close(ConsumerId id) { protected void close(ConsumerId id) {
for (Iterator iter = consumers.iterator(); iter.hasNext();) { for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
ActiveMQMessageConsumer c = (ActiveMQMessageConsumer)iter.next(); ActiveMQMessageConsumer c = iter.next();
if (c.getConsumerId().equals(id)) { if (c.getConsumerId().equals(id)) {
try { try {
c.close(); c.close();
@ -1831,8 +1832,8 @@ public class ActiveMQSession implements Session, QueueSession, TopicSession, Sta
} }
public boolean isInUse(ActiveMQTempDestination destination) { public boolean isInUse(ActiveMQTempDestination destination) {
for (Iterator iter = consumers.iterator(); iter.hasNext();) { for (Iterator<ActiveMQMessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
ActiveMQMessageConsumer c = (ActiveMQMessageConsumer)iter.next(); ActiveMQMessageConsumer c = iter.next();
if (c.isInUse(destination)) { if (c.isInUse(destination)) {
return true; return true;
} }

View File

@ -42,8 +42,9 @@ public class ConnectionFailedException extends JMSException {
private static String extractMessage(IOException cause) { private static String extractMessage(IOException cause) {
String m = cause.getMessage(); String m = cause.getMessage();
if (m == null || m.length() == 0) if (m == null || m.length() == 0) {
m = cause.toString(); m = cause.toString();
}
return m; return m;
} }

View File

@ -19,11 +19,11 @@ package org.apache.activemq;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import javax.jms.JMSException; import javax.jms.JMSException;
import javax.jms.TransactionInProgressException; import javax.jms.TransactionInProgressException;
import javax.jms.TransactionRolledBackException;
import javax.transaction.xa.XAException; import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource; import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid; import javax.transaction.xa.Xid;
@ -65,12 +65,12 @@ public class TransactionContext implements XAResource {
private static final Log LOG = LogFactory.getLog(TransactionContext.class); private static final Log LOG = LogFactory.getLog(TransactionContext.class);
// XATransactionId -> ArrayList of TransactionContext objects // XATransactionId -> ArrayList of TransactionContext objects
private static final ConcurrentHashMap ENDED_XA_TRANSACTION_CONTEXTS = new ConcurrentHashMap(); private static final ConcurrentHashMap<TransactionId, List<TransactionContext>> ENDED_XA_TRANSACTION_CONTEXTS = new ConcurrentHashMap<TransactionId, List<TransactionContext>>();
private final ActiveMQConnection connection; private final ActiveMQConnection connection;
private final LongSequenceGenerator localTransactionIdGenerator; private final LongSequenceGenerator localTransactionIdGenerator;
private final ConnectionId connectionId; private final ConnectionId connectionId;
private ArrayList synchornizations; private List<Synchronization> synchornizations;
// To track XA transactions. // To track XA transactions.
private Xid associatedXid; private Xid associatedXid;
@ -116,19 +116,21 @@ public class TransactionContext implements XAResource {
// /////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////
public void addSynchronization(Synchronization s) { public void addSynchronization(Synchronization s) {
if (synchornizations == null) if (synchornizations == null) {
synchornizations = new ArrayList(10); synchornizations = new ArrayList<Synchronization>(10);
}
synchornizations.add(s); synchornizations.add(s);
} }
private void afterRollback() throws JMSException { private void afterRollback() throws JMSException {
if (synchornizations == null) if (synchornizations == null) {
return; return;
}
int size = synchornizations.size(); int size = synchornizations.size();
try { try {
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
((Synchronization)synchornizations.get(i)).afterRollback(); synchornizations.get(i).afterRollback();
} }
} catch (JMSException e) { } catch (JMSException e) {
throw e; throw e;
@ -138,13 +140,14 @@ public class TransactionContext implements XAResource {
} }
private void afterCommit() throws JMSException { private void afterCommit() throws JMSException {
if (synchornizations == null) if (synchornizations == null) {
return; return;
}
int size = synchornizations.size(); int size = synchornizations.size();
try { try {
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
((Synchronization)synchornizations.get(i)).afterCommit(); synchornizations.get(i).afterCommit();
} }
} catch (JMSException e) { } catch (JMSException e) {
throw e; throw e;
@ -154,13 +157,14 @@ public class TransactionContext implements XAResource {
} }
private void beforeEnd() throws JMSException { private void beforeEnd() throws JMSException {
if (synchornizations == null) if (synchornizations == null) {
return; return;
}
int size = synchornizations.size(); int size = synchornizations.size();
try { try {
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
((Synchronization)synchornizations.get(i)).beforeEnd(); synchornizations.get(i).beforeEnd();
} }
} catch (JMSException e) { } catch (JMSException e) {
throw e; throw e;
@ -184,9 +188,10 @@ public class TransactionContext implements XAResource {
*/ */
public void begin() throws JMSException { public void begin() throws JMSException {
if (isInXATransaction()) if (isInXATransaction()) {
throw new TransactionInProgressException("Cannot start local transaction. XA transaction is already in progress."); throw new TransactionInProgressException("Cannot start local transaction. XA transaction is already in progress.");
}
if (transactionId == null) { if (transactionId == null) {
synchornizations = null; synchornizations = null;
this.transactionId = new LocalTransactionId(connectionId, localTransactionIdGenerator.getNextSequenceId()); this.transactionId = new LocalTransactionId(connectionId, localTransactionIdGenerator.getNextSequenceId());
@ -211,9 +216,10 @@ public class TransactionContext implements XAResource {
* transacted session. * transacted session.
*/ */
public void rollback() throws JMSException { public void rollback() throws JMSException {
if (isInXATransaction()) if (isInXATransaction()) {
throw new TransactionInProgressException("Cannot rollback() if an XA transaction is already in progress "); throw new TransactionInProgressException("Cannot rollback() if an XA transaction is already in progress ");
}
if (transactionId != null) { if (transactionId != null) {
TransactionInfo info = new TransactionInfo(getConnectionId(), transactionId, TransactionInfo.ROLLBACK); TransactionInfo info = new TransactionInfo(getConnectionId(), transactionId, TransactionInfo.ROLLBACK);
this.transactionId = null; this.transactionId = null;
@ -239,9 +245,10 @@ public class TransactionContext implements XAResource {
* transacted session. * transacted session.
*/ */
public void commit() throws JMSException { public void commit() throws JMSException {
if (isInXATransaction()) if (isInXATransaction()) {
throw new TransactionInProgressException("Cannot commit() if an XA transaction is already in progress "); throw new TransactionInProgressException("Cannot commit() if an XA transaction is already in progress ");
}
beforeEnd(); beforeEnd();
// Only send commit if the transaction was started. // Only send commit if the transaction was started.
@ -299,12 +306,14 @@ public class TransactionContext implements XAResource {
public void end(Xid xid, int flags) throws XAException { public void end(Xid xid, int flags) throws XAException {
if (LOG.isDebugEnabled()) if (LOG.isDebugEnabled()) {
LOG.debug("End: " + xid); LOG.debug("End: " + xid);
}
if (isInLocalTransaction())
if (isInLocalTransaction()) {
throw new XAException(XAException.XAER_PROTO); throw new XAException(XAException.XAER_PROTO);
}
if ((flags & (TMSUSPEND | TMFAIL)) != 0) { if ((flags & (TMSUSPEND | TMFAIL)) != 0) {
// You can only suspend the associated xid. // You can only suspend the associated xid.
if (!equals(associatedXid, xid)) { if (!equals(associatedXid, xid)) {
@ -335,18 +344,21 @@ public class TransactionContext implements XAResource {
} }
private boolean equals(Xid xid1, Xid xid2) { private boolean equals(Xid xid1, Xid xid2) {
if (xid1 == xid2) if (xid1 == xid2) {
return true; return true;
if (xid1 == null ^ xid2 == null) }
if (xid1 == null ^ xid2 == null) {
return false; return false;
}
return xid1.getFormatId() == xid2.getFormatId() && Arrays.equals(xid1.getBranchQualifier(), xid2.getBranchQualifier()) return xid1.getFormatId() == xid2.getFormatId() && Arrays.equals(xid1.getBranchQualifier(), xid2.getBranchQualifier())
&& Arrays.equals(xid1.getGlobalTransactionId(), xid2.getGlobalTransactionId()); && Arrays.equals(xid1.getGlobalTransactionId(), xid2.getGlobalTransactionId());
} }
public int prepare(Xid xid) throws XAException { public int prepare(Xid xid) throws XAException {
if (LOG.isDebugEnabled()) if (LOG.isDebugEnabled()) {
LOG.debug("Prepare: " + xid); LOG.debug("Prepare: " + xid);
}
// We allow interleaving multiple transactions, so // We allow interleaving multiple transactions, so
// we don't limit prepare to the associated xid. // we don't limit prepare to the associated xid.
XATransactionId x; XATransactionId x;
@ -373,9 +385,10 @@ public class TransactionContext implements XAResource {
public void rollback(Xid xid) throws XAException { public void rollback(Xid xid) throws XAException {
if (LOG.isDebugEnabled()) if (LOG.isDebugEnabled()) {
LOG.debug("Rollback: " + xid); LOG.debug("Rollback: " + xid);
}
// We allow interleaving multiple transactions, so // We allow interleaving multiple transactions, so
// we don't limit rollback to the associated xid. // we don't limit rollback to the associated xid.
XATransactionId x; XATransactionId x;
@ -398,10 +411,10 @@ public class TransactionContext implements XAResource {
TransactionInfo info = new TransactionInfo(getConnectionId(), x, TransactionInfo.ROLLBACK); TransactionInfo info = new TransactionInfo(getConnectionId(), x, TransactionInfo.ROLLBACK);
this.connection.syncSendPacket(info); this.connection.syncSendPacket(info);
ArrayList l = (ArrayList)ENDED_XA_TRANSACTION_CONTEXTS.remove(x); List<TransactionContext> l = ENDED_XA_TRANSACTION_CONTEXTS.remove(x);
if (l != null && !l.isEmpty()) { if (l != null && !l.isEmpty()) {
for (Iterator iter = l.iterator(); iter.hasNext();) { for (Iterator<TransactionContext> iter = l.iterator(); iter.hasNext();) {
TransactionContext ctx = (TransactionContext)iter.next(); TransactionContext ctx = iter.next();
ctx.afterRollback(); ctx.afterRollback();
} }
} }
@ -414,9 +427,10 @@ public class TransactionContext implements XAResource {
// XAResource interface // XAResource interface
public void commit(Xid xid, boolean onePhase) throws XAException { public void commit(Xid xid, boolean onePhase) throws XAException {
if (LOG.isDebugEnabled()) if (LOG.isDebugEnabled()) {
LOG.debug("Commit: " + xid); LOG.debug("Commit: " + xid);
}
// We allow interleaving multiple transactions, so // We allow interleaving multiple transactions, so
// we don't limit commit to the associated xid. // we don't limit commit to the associated xid.
XATransactionId x; XATransactionId x;
@ -437,7 +451,7 @@ public class TransactionContext implements XAResource {
this.connection.syncSendPacket(info); this.connection.syncSendPacket(info);
ArrayList l = (ArrayList)ENDED_XA_TRANSACTION_CONTEXTS.remove(x); List<TransactionContext> l = ENDED_XA_TRANSACTION_CONTEXTS.remove(x);
if (l != null && !l.isEmpty()) { if (l != null && !l.isEmpty()) {
for (Iterator iter = l.iterator(); iter.hasNext();) { for (Iterator iter = l.iterator(); iter.hasNext();) {
TransactionContext ctx = (TransactionContext)iter.next(); TransactionContext ctx = (TransactionContext)iter.next();
@ -452,9 +466,10 @@ public class TransactionContext implements XAResource {
} }
public void forget(Xid xid) throws XAException { public void forget(Xid xid) throws XAException {
if (LOG.isDebugEnabled()) if (LOG.isDebugEnabled()) {
LOG.debug("Forget: " + xid); LOG.debug("Forget: " + xid);
}
// We allow interleaving multiple transactions, so // We allow interleaving multiple transactions, so
// we don't limit forget to the associated xid. // we don't limit forget to the associated xid.
XATransactionId x; XATransactionId x;
@ -494,9 +509,10 @@ public class TransactionContext implements XAResource {
} }
public Xid[] recover(int flag) throws XAException { public Xid[] recover(int flag) throws XAException {
if (LOG.isDebugEnabled()) if (LOG.isDebugEnabled()) {
LOG.debug("Recover: " + flag); LOG.debug("Recover: " + flag);
}
TransactionInfo info = new TransactionInfo(getConnectionId(), null, TransactionInfo.RECOVER); TransactionInfo info = new TransactionInfo(getConnectionId(), null, TransactionInfo.RECOVER);
try { try {
this.connection.checkClosedOrFailed(); this.connection.checkClosedOrFailed();
@ -551,8 +567,9 @@ public class TransactionContext implements XAResource {
TransactionInfo info = new TransactionInfo(connectionId, transactionId, TransactionInfo.BEGIN); TransactionInfo info = new TransactionInfo(connectionId, transactionId, TransactionInfo.BEGIN);
try { try {
this.connection.asyncSendPacket(info); this.connection.asyncSendPacket(info);
if (LOG.isDebugEnabled()) if (LOG.isDebugEnabled()) {
LOG.debug("Started XA transaction: " + transactionId); LOG.debug("Started XA transaction: " + transactionId);
}
} catch (JMSException e) { } catch (JMSException e) {
throw toXAException(e); throw toXAException(e);
} }
@ -563,17 +580,18 @@ public class TransactionContext implements XAResource {
TransactionInfo info = new TransactionInfo(connectionId, transactionId, TransactionInfo.END); TransactionInfo info = new TransactionInfo(connectionId, transactionId, TransactionInfo.END);
try { try {
this.connection.syncSendPacket(info); this.connection.syncSendPacket(info);
if (LOG.isDebugEnabled()) if (LOG.isDebugEnabled()) {
LOG.debug("Ended XA transaction: " + transactionId); LOG.debug("Ended XA transaction: " + transactionId);
}
} catch (JMSException e) { } catch (JMSException e) {
throw toXAException(e); throw toXAException(e);
} }
// Add our self to the list of contexts that are interested in // Add our self to the list of contexts that are interested in
// post commit/rollback events. // post commit/rollback events.
ArrayList l = (ArrayList)ENDED_XA_TRANSACTION_CONTEXTS.get(transactionId); List<TransactionContext> l = ENDED_XA_TRANSACTION_CONTEXTS.get(transactionId);
if (l == null) { if (l == null) {
l = new ArrayList(3); l = new ArrayList<TransactionContext>(3);
ENDED_XA_TRANSACTION_CONTEXTS.put(transactionId, l); ENDED_XA_TRANSACTION_CONTEXTS.put(transactionId, l);
l.add(this); l.add(this);
} else if (!l.contains(this)) { } else if (!l.contains(this)) {

View File

@ -221,7 +221,7 @@ public interface Broker extends Region, Service {
/** /**
* @return a Set of all durable destinations * @return a Set of all durable destinations
*/ */
Set getDurableDestinations(); Set<ActiveMQDestination> getDurableDestinations();
/** /**
* Add and process a DestinationInfo object * Add and process a DestinationInfo object

View File

@ -95,11 +95,12 @@ import org.apache.commons.logging.LogFactory;
*/ */
public class BrokerService implements Service { public class BrokerService implements Service {
public static final String DEFAULT_PORT = "61616";
public static final String LOCAL_HOST_NAME;
public static final String DEFAULT_BROKER_NAME = "localhost";
private static final Log LOG = LogFactory.getLog(BrokerService.class); private static final Log LOG = LogFactory.getLog(BrokerService.class);
private static final long serialVersionUID = 7353129142305630237L; private static final long serialVersionUID = 7353129142305630237L;
public static final String DEFAULT_PORT = "61616";
static final String DEFAULT_BROKER_NAME = "localhost";
public static final String LOCAL_HOST_NAME;
private boolean useJmx = true; private boolean useJmx = true;
private boolean enableStatistics = true; private boolean enableStatistics = true;
@ -124,11 +125,11 @@ public class BrokerService implements Service {
private PersistenceAdapterFactory persistenceFactory; private PersistenceAdapterFactory persistenceFactory;
private DestinationFactory destinationFactory; private DestinationFactory destinationFactory;
private MessageAuthorizationPolicy messageAuthorizationPolicy; private MessageAuthorizationPolicy messageAuthorizationPolicy;
private List transportConnectors = new CopyOnWriteArrayList(); private List<TransportConnector> transportConnectors = new CopyOnWriteArrayList<TransportConnector>();
private List networkConnectors = new CopyOnWriteArrayList(); private List<NetworkConnector> networkConnectors = new CopyOnWriteArrayList<NetworkConnector>();
private List proxyConnectors = new CopyOnWriteArrayList(); private List<ProxyConnector> proxyConnectors = new CopyOnWriteArrayList<ProxyConnector>();
private List registeredMBeanNames = new CopyOnWriteArrayList(); private List<ObjectName> registeredMBeanNames = new CopyOnWriteArrayList<ObjectName>();
private List jmsConnectors = new CopyOnWriteArrayList(); private List<JmsConnector> jmsConnectors = new CopyOnWriteArrayList<JmsConnector>();
private Service[] services; private Service[] services;
private MasterConnector masterConnector; private MasterConnector masterConnector;
private String masterConnectorURI; private String masterConnectorURI;
@ -282,7 +283,7 @@ public class BrokerService implements Service {
public NetworkConnector addNetworkConnector(NetworkConnector connector) throws Exception { public NetworkConnector addNetworkConnector(NetworkConnector connector) throws Exception {
connector.setBrokerService(this); connector.setBrokerService(this);
URI uri = getVmConnectorURI(); URI uri = getVmConnectorURI();
HashMap map = new HashMap(URISupport.parseParamters(uri)); Map<String, String> map = new HashMap<String, String>(URISupport.parseParamters(uri));
map.put("network", "true"); map.put("network", "true");
map.put("async", "false"); map.put("async", "false");
uri = URISupport.createURIWithQuery(uri, URISupport.createQueryString(map)); uri = URISupport.createURIWithQuery(uri, URISupport.createQueryString(map));
@ -292,10 +293,10 @@ public class BrokerService implements Service {
// back connections. // back connections.
connector.setConnectionFilter(new ConnectionFilter() { connector.setConnectionFilter(new ConnectionFilter() {
public boolean connectTo(URI location) { public boolean connectTo(URI location) {
List transportConnectors = getTransportConnectors(); List<TransportConnector> transportConnectors = getTransportConnectors();
for (Iterator iter = transportConnectors.iterator(); iter.hasNext();) { for (Iterator<TransportConnector> iter = transportConnectors.iterator(); iter.hasNext();) {
try { try {
TransportConnector tc = (TransportConnector)iter.next(); TransportConnector tc = iter.next();
if (location.equals(tc.getConnectUri())) { if (location.equals(tc.getConnectUri())) {
return false; return false;
} }
@ -470,8 +471,8 @@ public class BrokerService implements Service {
if (isUseJmx()) { if (isUseJmx()) {
MBeanServer mbeanServer = getManagementContext().getMBeanServer(); MBeanServer mbeanServer = getManagementContext().getMBeanServer();
if (mbeanServer != null) { if (mbeanServer != null) {
for (Iterator iter = registeredMBeanNames.iterator(); iter.hasNext();) { for (Iterator<ObjectName> iter = registeredMBeanNames.iterator(); iter.hasNext();) {
ObjectName name = (ObjectName)iter.next(); ObjectName name = iter.next();
try { try {
mbeanServer.unregisterMBean(name); mbeanServer.unregisterMBean(name);
} catch (Exception e) { } catch (Exception e) {
@ -872,8 +873,8 @@ public class BrokerService implements Service {
this.advisorySupport = advisorySupport; this.advisorySupport = advisorySupport;
} }
public List getTransportConnectors() { public List<TransportConnector> getTransportConnectors() {
return new ArrayList(transportConnectors); return new ArrayList<TransportConnector>(transportConnectors);
} }
/** /**
@ -882,19 +883,19 @@ public class BrokerService implements Service {
* *
* @org.apache.xbean.Property nestedType="org.apache.activemq.broker.TransportConnector" * @org.apache.xbean.Property nestedType="org.apache.activemq.broker.TransportConnector"
*/ */
public void setTransportConnectors(List transportConnectors) throws Exception { public void setTransportConnectors(List<TransportConnector> transportConnectors) throws Exception {
for (Iterator iter = transportConnectors.iterator(); iter.hasNext();) { for (Iterator<TransportConnector> iter = transportConnectors.iterator(); iter.hasNext();) {
TransportConnector connector = (TransportConnector)iter.next(); TransportConnector connector = iter.next();
addConnector(connector); addConnector(connector);
} }
} }
public List getNetworkConnectors() { public List<NetworkConnector> getNetworkConnectors() {
return new ArrayList(networkConnectors); return new ArrayList<NetworkConnector>(networkConnectors);
} }
public List getProxyConnectors() { public List<ProxyConnector> getProxyConnectors() {
return new ArrayList(proxyConnectors); return new ArrayList<ProxyConnector>(proxyConnectors);
} }
/** /**
@ -1182,24 +1183,24 @@ public class BrokerService implements Service {
protected void stopAllConnectors(ServiceStopper stopper) { protected void stopAllConnectors(ServiceStopper stopper) {
for (Iterator iter = getNetworkConnectors().iterator(); iter.hasNext();) { for (Iterator<NetworkConnector> iter = getNetworkConnectors().iterator(); iter.hasNext();) {
NetworkConnector connector = (NetworkConnector)iter.next(); NetworkConnector connector = iter.next();
unregisterNetworkConnectorMBean(connector); unregisterNetworkConnectorMBean(connector);
stopper.stop(connector); stopper.stop(connector);
} }
for (Iterator iter = getProxyConnectors().iterator(); iter.hasNext();) { for (Iterator<ProxyConnector> iter = getProxyConnectors().iterator(); iter.hasNext();) {
ProxyConnector connector = (ProxyConnector)iter.next(); ProxyConnector connector = iter.next();
stopper.stop(connector); stopper.stop(connector);
} }
for (Iterator iter = jmsConnectors.iterator(); iter.hasNext();) { for (Iterator<JmsConnector> iter = jmsConnectors.iterator(); iter.hasNext();) {
JmsConnector connector = (JmsConnector)iter.next(); JmsConnector connector = iter.next();
stopper.stop(connector); stopper.stop(connector);
} }
for (Iterator iter = getTransportConnectors().iterator(); iter.hasNext();) { for (Iterator<TransportConnector> iter = getTransportConnectors().iterator(); iter.hasNext();) {
TransportConnector connector = (TransportConnector)iter.next(); TransportConnector connector = iter.next();
stopper.stop(connector); stopper.stop(connector);
} }
} }
@ -1584,10 +1585,10 @@ public class BrokerService implements Service {
protected void startAllConnectors() throws Exception { protected void startAllConnectors() throws Exception {
if (!isSlave()) { if (!isSlave()) {
ArrayList al = new ArrayList(); List<TransportConnector> al = new ArrayList<TransportConnector>();
for (Iterator iter = getTransportConnectors().iterator(); iter.hasNext();) { for (Iterator<TransportConnector> iter = getTransportConnectors().iterator(); iter.hasNext();) {
TransportConnector connector = (TransportConnector)iter.next(); TransportConnector connector = iter.next();
al.add(startTransportConnector(connector)); al.add(startTransportConnector(connector));
} }
@ -1598,26 +1599,26 @@ public class BrokerService implements Service {
setTransportConnectors(al); setTransportConnectors(al);
} }
URI uri = getVmConnectorURI(); URI uri = getVmConnectorURI();
HashMap map = new HashMap(URISupport.parseParamters(uri)); Map<String, String> map = new HashMap<String, String>(URISupport.parseParamters(uri));
map.put("network", "true"); map.put("network", "true");
map.put("async", "false"); map.put("async", "false");
uri = URISupport.createURIWithQuery(uri, URISupport.createQueryString(map)); uri = URISupport.createURIWithQuery(uri, URISupport.createQueryString(map));
for (Iterator iter = getNetworkConnectors().iterator(); iter.hasNext();) { for (Iterator<NetworkConnector> iter = getNetworkConnectors().iterator(); iter.hasNext();) {
NetworkConnector connector = (NetworkConnector)iter.next(); NetworkConnector connector = iter.next();
connector.setLocalUri(uri); connector.setLocalUri(uri);
connector.setBrokerName(getBrokerName()); connector.setBrokerName(getBrokerName());
connector.setDurableDestinations(getBroker().getDurableDestinations()); connector.setDurableDestinations(getBroker().getDurableDestinations());
connector.start(); connector.start();
} }
for (Iterator iter = getProxyConnectors().iterator(); iter.hasNext();) { for (Iterator<ProxyConnector> iter = getProxyConnectors().iterator(); iter.hasNext();) {
ProxyConnector connector = (ProxyConnector)iter.next(); ProxyConnector connector = iter.next();
connector.start(); connector.start();
} }
for (Iterator iter = jmsConnectors.iterator(); iter.hasNext();) { for (Iterator<JmsConnector> iter = jmsConnectors.iterator(); iter.hasNext();) {
JmsConnector connector = (JmsConnector)iter.next(); JmsConnector connector = iter.next();
connector.start(); connector.start();
} }

View File

@ -23,6 +23,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.activemq.broker.region.MessageReference; import org.apache.activemq.broker.region.MessageReference;
import org.apache.activemq.command.ConnectionId; import org.apache.activemq.command.ConnectionId;
import org.apache.activemq.command.ConnectionInfo; import org.apache.activemq.command.ConnectionInfo;
import org.apache.activemq.command.TransactionId;
import org.apache.activemq.command.WireFormatInfo; import org.apache.activemq.command.WireFormatInfo;
import org.apache.activemq.filter.MessageEvaluationContext; import org.apache.activemq.filter.MessageEvaluationContext;
import org.apache.activemq.security.MessageAuthorizationPolicy; import org.apache.activemq.security.MessageAuthorizationPolicy;
@ -41,7 +42,7 @@ public class ConnectionContext {
private Broker broker; private Broker broker;
private boolean inRecoveryMode; private boolean inRecoveryMode;
private Transaction transaction; private Transaction transaction;
private ConcurrentHashMap transactions; private ConcurrentHashMap<TransactionId, Transaction> transactions;
private SecurityContext securityContext; private SecurityContext securityContext;
private ConnectionId connectionId; private ConnectionId connectionId;
private String clientId; private String clientId;
@ -158,11 +159,11 @@ public class ConnectionContext {
this.inRecoveryMode = inRecoveryMode; this.inRecoveryMode = inRecoveryMode;
} }
public ConcurrentHashMap getTransactions() { public ConcurrentHashMap<TransactionId, Transaction> getTransactions() {
return transactions; return transactions;
} }
public void setTransactions(ConcurrentHashMap transactions) { public void setTransactions(ConcurrentHashMap<TransactionId, Transaction> transactions) {
this.transactions = transactions; this.transactions = transactions;
} }

View File

@ -36,12 +36,13 @@ public class DefaultBrokerFactory implements BrokerFactoryHandler {
public BrokerService createBroker(URI brokerURI) throws Exception { public BrokerService createBroker(URI brokerURI) throws Exception {
CompositeData compositeData = URISupport.parseComposite(brokerURI); CompositeData compositeData = URISupport.parseComposite(brokerURI);
Map params = new HashMap(compositeData.getParameters()); Map<String, String> params = new HashMap<String, String>(compositeData.getParameters());
BrokerService brokerService = new BrokerService(); BrokerService brokerService = new BrokerService();
IntrospectionSupport.setProperties(brokerService, params); IntrospectionSupport.setProperties(brokerService, params);
if (compositeData.getPath() != null) if (compositeData.getPath() != null) {
brokerService.setBrokerName(compositeData.getPath()); brokerService.setBrokerName(compositeData.getPath());
}
URI[] components = compositeData.getComponents(); URI[] components = compositeData.getComponents();
for (int i = 0; i < components.length; i++) { for (int i = 0; i < components.length; i++) {

View File

@ -19,6 +19,7 @@ package org.apache.activemq.broker;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -55,8 +56,8 @@ public class TransactionBroker extends BrokerFilter {
// The prepared XA transactions. // The prepared XA transactions.
private TransactionStore transactionStore; private TransactionStore transactionStore;
private Map xaTransactions = new LinkedHashMap(); private Map<TransactionId, Transaction> xaTransactions = new LinkedHashMap<TransactionId, Transaction>();
ActiveMQMessageAudit audit; private ActiveMQMessageAudit audit;
public TransactionBroker(Broker next, TransactionStore transactionStore) { public TransactionBroker(Broker next, TransactionStore transactionStore) {
super(next); super(next);
@ -78,7 +79,7 @@ public class TransactionBroker extends BrokerFilter {
final ConnectionContext context = new ConnectionContext(); final ConnectionContext context = new ConnectionContext();
context.setBroker(this); context.setBroker(this);
context.setInRecoveryMode(true); context.setInRecoveryMode(true);
context.setTransactions(new ConcurrentHashMap()); context.setTransactions(new ConcurrentHashMap<TransactionId, Transaction>());
context.setProducerFlowControl(false); context.setProducerFlowControl(false);
final ProducerBrokerExchange producerExchange = new ProducerBrokerExchange(); final ProducerBrokerExchange producerExchange = new ProducerBrokerExchange();
producerExchange.setMutable(true); producerExchange.setMutable(true);
@ -119,12 +120,13 @@ public class TransactionBroker extends BrokerFilter {
// //
// //////////////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////////////
public TransactionId[] getPreparedTransactions(ConnectionContext context) throws Exception { public TransactionId[] getPreparedTransactions(ConnectionContext context) throws Exception {
ArrayList txs = new ArrayList(); List<TransactionId> txs = new ArrayList<TransactionId>();
synchronized (xaTransactions) { synchronized (xaTransactions) {
for (Iterator iter = xaTransactions.values().iterator(); iter.hasNext();) { for (Iterator<Transaction> iter = xaTransactions.values().iterator(); iter.hasNext();) {
Transaction tx = (Transaction)iter.next(); Transaction tx = iter.next();
if (tx.isPrepared()) if (tx.isPrepared()) {
txs.add(tx.getTransactionId()); txs.add(tx.getTransactionId());
}
} }
} }
XATransactionId rc[] = new XATransactionId[txs.size()]; XATransactionId rc[] = new XATransactionId[txs.size()];
@ -137,17 +139,19 @@ public class TransactionBroker extends BrokerFilter {
if (xid.isXATransaction()) { if (xid.isXATransaction()) {
Transaction transaction = null; Transaction transaction = null;
synchronized (xaTransactions) { synchronized (xaTransactions) {
transaction = (Transaction)xaTransactions.get(xid); transaction = xaTransactions.get(xid);
if (transaction != null) if (transaction != null) {
return; return;
}
transaction = new XATransaction(transactionStore, (XATransactionId)xid, this); transaction = new XATransaction(transactionStore, (XATransactionId)xid, this);
xaTransactions.put(xid, transaction); xaTransactions.put(xid, transaction);
} }
} else { } else {
Map transactionMap = context.getTransactions(); Map<TransactionId, Transaction> transactionMap = context.getTransactions();
Transaction transaction = (Transaction)transactionMap.get(xid); Transaction transaction = transactionMap.get(xid);
if (transaction != null) if (transaction != null) {
throw new JMSException("Transaction '" + xid + "' has already been started."); throw new JMSException("Transaction '" + xid + "' has already been started.");
}
transaction = new LocalTransaction(transactionStore, (LocalTransactionId)xid, context); transaction = new LocalTransaction(transactionStore, (LocalTransactionId)xid, context);
transactionMap.put(xid, transaction); transactionMap.put(xid, transaction);
} }
@ -229,9 +233,9 @@ public class TransactionBroker extends BrokerFilter {
} }
public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) throws Exception { public void removeConnection(ConnectionContext context, ConnectionInfo info, Throwable error) throws Exception {
for (Iterator iter = context.getTransactions().values().iterator(); iter.hasNext();) { for (Iterator<Transaction> iter = context.getTransactions().values().iterator(); iter.hasNext();) {
try { try {
Transaction transaction = (Transaction)iter.next(); Transaction transaction = iter.next();
transaction.rollback(); transaction.rollback();
} catch (Exception e) { } catch (Exception e) {
LOG.warn("ERROR Rolling back disconnected client's transactions: ", e); LOG.warn("ERROR Rolling back disconnected client's transactions: ", e);
@ -252,8 +256,9 @@ public class TransactionBroker extends BrokerFilter {
transactionMap = xid.isXATransaction() ? xaTransactions : context.getTransactions(); transactionMap = xid.isXATransaction() ? xaTransactions : context.getTransactions();
} }
Transaction transaction = (Transaction)transactionMap.get(xid); Transaction transaction = (Transaction)transactionMap.get(xid);
if (transaction != null) if (transaction != null) {
return transaction; return transaction;
}
if (xid.isXATransaction()) { if (xid.isXATransaction()) {
XAException e = new XAException("Transaction '" + xid + "' has not been started."); XAException e = new XAException("Transaction '" + xid + "' has not been started.");
e.errorCode = XAException.XAER_NOTA; e.errorCode = XAException.XAER_NOTA;

View File

@ -233,8 +233,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
public void serviceTransportException(IOException e) { public void serviceTransportException(IOException e) {
if (!disposed.get()) { if (!disposed.get()) {
transportException.set(e); transportException.set(e);
if (TRANSPORTLOG.isDebugEnabled()) if (TRANSPORTLOG.isDebugEnabled()) {
TRANSPORTLOG.debug("Transport failed: " + e, e); TRANSPORTLOG.debug("Transport failed: " + e, e);
}
ServiceSupport.dispose(this); ServiceSupport.dispose(this);
} }
} }
@ -263,17 +264,20 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
* error transmitted to the client before stopping it's transport. * error transmitted to the client before stopping it's transport.
*/ */
public void serviceException(Throwable e) { public void serviceException(Throwable e) {
// are we a transport exception such as not being able to dispatch // are we a transport exception such as not being able to dispatch
// synchronously to a transport // synchronously to a transport
if (e instanceof IOException) { if (e instanceof IOException) {
serviceTransportException((IOException)e); serviceTransportException((IOException)e);
} } else if (e.getClass() == BrokerStoppedException.class) {
// Handle the case where the broker is stopped // Handle the case where the broker is stopped
// But the client is still connected. // But the client is still connected.
else if (e.getClass() == BrokerStoppedException.class) {
if (!disposed.get()) { if (!disposed.get()) {
if (SERVICELOG.isDebugEnabled()) if (SERVICELOG.isDebugEnabled()) {
SERVICELOG.debug("Broker has been stopped. Notifying client and closing his connection."); SERVICELOG.debug("Broker has been stopped. Notifying client and closing his connection.");
}
ConnectionError ce = new ConnectionError(); ConnectionError ce = new ConnectionError();
ce.setException(e); ce.setException(e);
dispatchSync(ce); dispatchSync(ce);
@ -310,8 +314,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
response = command.visit(this); response = command.visit(this);
} catch (Throwable e) { } catch (Throwable e) {
if (responseRequired) { if (responseRequired) {
if (SERVICELOG.isDebugEnabled() && e.getClass() != BrokerStoppedException.class) if (SERVICELOG.isDebugEnabled() && e.getClass() != BrokerStoppedException.class) {
SERVICELOG.debug("Error occured while processing sync command: " + e, e); SERVICELOG.debug("Error occured while processing sync command: " + e, e);
}
response = new ExceptionResponse(e); response = new ExceptionResponse(e);
} else { } else {
serviceException(e); serviceException(e);
@ -402,8 +407,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
throw new NullPointerException("Context is null"); throw new NullPointerException("Context is null");
} }
TransactionState transactionState = cs.getTransactionState(info.getTransactionId()); TransactionState transactionState = cs.getTransactionState(info.getTransactionId());
if (transactionState == null) if (transactionState == null) {
throw new IllegalStateException("Cannot prepare a transaction that had not been started: " + info.getTransactionId()); throw new IllegalStateException("Cannot prepare a transaction that had not been started: " + info.getTransactionId());
}
// Avoid dups. // Avoid dups.
if (!transactionState.isPrepared()) { if (!transactionState.isPrepared()) {
transactionState.setPrepared(true); transactionState.setPrepared(true);
@ -500,8 +506,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
ConnectionId connectionId = sessionId.getParentId(); ConnectionId connectionId = sessionId.getParentId();
TransportConnectionState cs = lookupConnectionState(connectionId); TransportConnectionState cs = lookupConnectionState(connectionId);
SessionState ss = cs.getSessionState(sessionId); SessionState ss = cs.getSessionState(sessionId);
if (ss == null) if (ss == null) {
throw new IllegalStateException("Cannot add a producer to a session that had not been registered: " + sessionId); throw new IllegalStateException("Cannot add a producer to a session that had not been registered: " + sessionId);
}
// Avoid replaying dup commands // Avoid replaying dup commands
if (!ss.getProducerIds().contains(info.getProducerId())) { if (!ss.getProducerIds().contains(info.getProducerId())) {
broker.addProducer(cs.getContext(), info); broker.addProducer(cs.getContext(), info);
@ -519,11 +526,13 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
ConnectionId connectionId = sessionId.getParentId(); ConnectionId connectionId = sessionId.getParentId();
TransportConnectionState cs = lookupConnectionState(connectionId); TransportConnectionState cs = lookupConnectionState(connectionId);
SessionState ss = cs.getSessionState(sessionId); SessionState ss = cs.getSessionState(sessionId);
if (ss == null) if (ss == null) {
throw new IllegalStateException("Cannot remove a producer from a session that had not been registered: " + sessionId); throw new IllegalStateException("Cannot remove a producer from a session that had not been registered: " + sessionId);
}
ProducerState ps = ss.removeProducer(id); ProducerState ps = ss.removeProducer(id);
if (ps == null) if (ps == null) {
throw new IllegalStateException("Cannot remove a producer that had not been registered: " + id); throw new IllegalStateException("Cannot remove a producer that had not been registered: " + id);
}
removeProducerBrokerExchange(id); removeProducerBrokerExchange(id);
broker.removeProducer(cs.getContext(), ps.getInfo()); broker.removeProducer(cs.getContext(), ps.getInfo());
return null; return null;
@ -534,8 +543,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
ConnectionId connectionId = sessionId.getParentId(); ConnectionId connectionId = sessionId.getParentId();
TransportConnectionState cs = lookupConnectionState(connectionId); TransportConnectionState cs = lookupConnectionState(connectionId);
SessionState ss = cs.getSessionState(sessionId); SessionState ss = cs.getSessionState(sessionId);
if (ss == null) if (ss == null) {
throw new IllegalStateException("Cannot add a consumer to a session that had not been registered: " + sessionId); throw new IllegalStateException("Cannot add a consumer to a session that had not been registered: " + sessionId);
}
// Avoid replaying dup commands // Avoid replaying dup commands
if (!ss.getConsumerIds().contains(info.getConsumerId())) { if (!ss.getConsumerIds().contains(info.getConsumerId())) {
broker.addConsumer(cs.getContext(), info); broker.addConsumer(cs.getContext(), info);
@ -553,11 +563,13 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
ConnectionId connectionId = sessionId.getParentId(); ConnectionId connectionId = sessionId.getParentId();
TransportConnectionState cs = lookupConnectionState(connectionId); TransportConnectionState cs = lookupConnectionState(connectionId);
SessionState ss = cs.getSessionState(sessionId); SessionState ss = cs.getSessionState(sessionId);
if (ss == null) if (ss == null) {
throw new IllegalStateException("Cannot remove a consumer from a session that had not been registered: " + sessionId); throw new IllegalStateException("Cannot remove a consumer from a session that had not been registered: " + sessionId);
}
ConsumerState consumerState = ss.removeConsumer(id); ConsumerState consumerState = ss.removeConsumer(id);
if (consumerState == null) if (consumerState == null) {
throw new IllegalStateException("Cannot remove a consumer that had not been registered: " + id); throw new IllegalStateException("Cannot remove a consumer that had not been registered: " + id);
}
broker.removeConsumer(cs.getContext(), consumerState.getInfo()); broker.removeConsumer(cs.getContext(), consumerState.getInfo());
removeConsumerBrokerExchange(id); removeConsumerBrokerExchange(id);
return null; return null;
@ -582,8 +594,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
ConnectionId connectionId = id.getParentId(); ConnectionId connectionId = id.getParentId();
TransportConnectionState cs = lookupConnectionState(connectionId); TransportConnectionState cs = lookupConnectionState(connectionId);
SessionState session = cs.getSessionState(id); SessionState session = cs.getSessionState(id);
if (session == null) if (session == null) {
throw new IllegalStateException("Cannot remove session that had not been registered: " + id); throw new IllegalStateException("Cannot remove session that had not been registered: " + id);
}
// Don't let new consumers or producers get added while we are closing // Don't let new consumers or producers get added while we are closing
// this down. // this down.
session.shutdown(); session.shutdown();
@ -912,8 +925,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
disposeTransport(); disposeTransport();
} }
if (taskRunner != null) if (taskRunner != null) {
taskRunner.shutdown(); taskRunner.shutdown();
}
// Run the MessageDispatch callbacks so that message references get // Run the MessageDispatch callbacks so that message references get
// cleaned up. // cleaned up.
@ -1090,12 +1104,13 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
// so this TransportConnection is the rear end of a network bridge // so this TransportConnection is the rear end of a network bridge
// We have been requested to create a two way pipe ... // We have been requested to create a two way pipe ...
try { try {
Properties props = MarshallingSupport.stringToProperties(info.getNetworkProperties()); Properties properties = MarshallingSupport.stringToProperties(info.getNetworkProperties());
Map<String, String> props = new HashMap(properties);
NetworkBridgeConfiguration config = new NetworkBridgeConfiguration(); NetworkBridgeConfiguration config = new NetworkBridgeConfiguration();
IntrospectionSupport.setProperties(config, props, ""); IntrospectionSupport.setProperties(config, props, "");
config.setBrokerName(broker.getBrokerName()); config.setBrokerName(broker.getBrokerName());
URI uri = broker.getVmConnectorURI(); URI uri = broker.getVmConnectorURI();
HashMap map = new HashMap(URISupport.parseParamters(uri)); HashMap<String,String> map = new HashMap<String,String>(URISupport.parseParamters(uri));
map.put("network", "true"); map.put("network", "true");
map.put("async", "false"); map.put("async", "false");
uri = URISupport.createURIWithQuery(uri, URISupport.createQueryString(map)); uri = URISupport.createURIWithQuery(uri, URISupport.createQueryString(map));
@ -1145,8 +1160,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
public String getConnectionId() { public String getConnectionId() {
List<TransportConnectionState> connectionStates = listConnectionStates(); List<TransportConnectionState> connectionStates = listConnectionStates();
for (TransportConnectionState cs : connectionStates) { for (TransportConnectionState cs : connectionStates) {
if (cs.getInfo().getClientId() != null) if (cs.getInfo().getClientId() != null) {
return cs.getInfo().getClientId(); return cs.getInfo().getClientId();
}
return cs.getInfo().getConnectionId().toString(); return cs.getInfo().getConnectionId().toString();
} }
return null; return null;
@ -1197,7 +1213,7 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
if (cs != null) { if (cs != null) {
ConsumerInfo info = cs.getInfo(); ConsumerInfo info = cs.getInfo();
if (info != null) { if (info != null) {
if (info.getDestination() != null && info.getDestination().isPattern()) { if (info.getDestination() != null && info.getDestination().isPattern()) {
result.setWildcard(true); result.setWildcard(true);
} }
} }
@ -1233,8 +1249,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
public Response processControlCommand(ControlCommand command) throws Exception { public Response processControlCommand(ControlCommand command) throws Exception {
String control = command.getCommand(); String control = command.getCommand();
if (control != null && control.equals("shutdown")) if (control != null && control.equals("shutdown")) {
System.exit(0); System.exit(0);
}
return null; return null;
} }
@ -1283,7 +1300,7 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
} }
protected List<TransportConnectionState> listConnectionStates() { protected List<TransportConnectionState> listConnectionStates() {
ArrayList<TransportConnectionState> rc = new ArrayList<TransportConnectionState>(); List<TransportConnectionState> rc = new ArrayList<TransportConnectionState>();
if (connectionState != null) { if (connectionState != null) {
rc.add(connectionState); rc.add(connectionState);
} }
@ -1292,36 +1309,41 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
protected TransportConnectionState lookupConnectionState(String connectionId) { protected TransportConnectionState lookupConnectionState(String connectionId) {
TransportConnectionState cs = connectionState; TransportConnectionState cs = connectionState;
if (cs == null) if (cs == null) {
throw new IllegalStateException("Cannot lookup a connectionId for a connection that had not been registered: " + connectionId); throw new IllegalStateException("Cannot lookup a connectionId for a connection that had not been registered: " + connectionId);
}
return cs; return cs;
} }
protected TransportConnectionState lookupConnectionState(ConsumerId id) { protected TransportConnectionState lookupConnectionState(ConsumerId id) {
TransportConnectionState cs = connectionState; TransportConnectionState cs = connectionState;
if (cs == null) if (cs == null) {
throw new IllegalStateException("Cannot lookup a consumer from a connection that had not been registered: " + id.getParentId().getParentId()); throw new IllegalStateException("Cannot lookup a consumer from a connection that had not been registered: " + id.getParentId().getParentId());
}
return cs; return cs;
} }
protected TransportConnectionState lookupConnectionState(ProducerId id) { protected TransportConnectionState lookupConnectionState(ProducerId id) {
TransportConnectionState cs = connectionState; TransportConnectionState cs = connectionState;
if (cs == null) if (cs == null) {
throw new IllegalStateException("Cannot lookup a producer from a connection that had not been registered: " + id.getParentId().getParentId()); throw new IllegalStateException("Cannot lookup a producer from a connection that had not been registered: " + id.getParentId().getParentId());
}
return cs; return cs;
} }
protected TransportConnectionState lookupConnectionState(SessionId id) { protected TransportConnectionState lookupConnectionState(SessionId id) {
TransportConnectionState cs = connectionState; TransportConnectionState cs = connectionState;
if (cs == null) if (cs == null) {
throw new IllegalStateException("Cannot lookup a session from a connection that had not been registered: " + id.getParentId()); throw new IllegalStateException("Cannot lookup a session from a connection that had not been registered: " + id.getParentId());
}
return cs; return cs;
} }
protected TransportConnectionState lookupConnectionState(ConnectionId connectionId) { protected TransportConnectionState lookupConnectionState(ConnectionId connectionId) {
TransportConnectionState cs = connectionState; TransportConnectionState cs = connectionState;
if (cs == null) if (cs == null) {
throw new IllegalStateException("Cannot lookup a connection that had not been registered: " + connectionId); throw new IllegalStateException("Cannot lookup a connection that had not been registered: " + connectionId);
}
return cs; return cs;
} }

View File

@ -49,6 +49,9 @@ public class TransportConnector implements Connector {
private static final Log LOG = LogFactory.getLog(TransportConnector.class); private static final Log LOG = LogFactory.getLog(TransportConnector.class);
protected CopyOnWriteArrayList<TransportConnection> connections = new CopyOnWriteArrayList<TransportConnection>();
protected TransportStatusDetector statusDector;
private Broker broker; private Broker broker;
private TransportServer server; private TransportServer server;
private URI uri; private URI uri;
@ -56,8 +59,6 @@ public class TransportConnector implements Connector {
private TaskRunnerFactory taskRunnerFactory; private TaskRunnerFactory taskRunnerFactory;
private MessageAuthorizationPolicy messageAuthorizationPolicy; private MessageAuthorizationPolicy messageAuthorizationPolicy;
private DiscoveryAgent discoveryAgent; private DiscoveryAgent discoveryAgent;
protected CopyOnWriteArrayList connections = new CopyOnWriteArrayList();
protected TransportStatusDetector statusDector;
private ConnectorStatistics statistics = new ConnectorStatistics(); private ConnectorStatistics statistics = new ConnectorStatistics();
private URI discoveryUri; private URI discoveryUri;
private URI connectUri; private URI connectUri;
@ -65,13 +66,6 @@ public class TransportConnector implements Connector {
private boolean disableAsyncDispatch; private boolean disableAsyncDispatch;
private boolean enableStatusMonitor = true; private boolean enableStatusMonitor = true;
/**
* @return Returns the connections.
*/
public CopyOnWriteArrayList getConnections() {
return connections;
}
public TransportConnector() { public TransportConnector() {
} }
@ -88,6 +82,14 @@ public class TransportConnector implements Connector {
} }
/**
* @return Returns the connections.
*/
public CopyOnWriteArrayList<TransportConnection> getConnections() {
return connections;
}
/** /**
* Factory method to create a JMX managed version of this transport * Factory method to create a JMX managed version of this transport
* connector * connector
@ -251,8 +253,8 @@ public class TransportConnector implements Connector {
this.statusDector.stop(); this.statusDector.stop();
} }
for (Iterator iter = connections.iterator(); iter.hasNext();) { for (Iterator<TransportConnection> iter = connections.iterator(); iter.hasNext();) {
TransportConnection c = (TransportConnection)iter.next(); TransportConnection c = iter.next();
ss.stop(c); ss.stop(c);
} }
ss.throwFirstException(); ss.throwFirstException();
@ -342,8 +344,9 @@ public class TransportConnector implements Connector {
public String toString() { public String toString() {
String rc = getName(); String rc = getName();
if (rc == null) if (rc == null) {
rc = super.toString(); rc = super.toString();
}
return rc; return rc;
} }

View File

@ -76,19 +76,19 @@ public class ManagedRegionBroker extends RegionBroker {
private static final Log LOG = LogFactory.getLog(ManagedRegionBroker.class); private static final Log LOG = LogFactory.getLog(ManagedRegionBroker.class);
private final MBeanServer mbeanServer; private final MBeanServer mbeanServer;
private final ObjectName brokerObjectName; private final ObjectName brokerObjectName;
private final Map topics = new ConcurrentHashMap(); private final Map<ObjectName, DestinationView> topics = new ConcurrentHashMap<ObjectName, DestinationView>();
private final Map queues = new ConcurrentHashMap(); private final Map<ObjectName, DestinationView> queues = new ConcurrentHashMap<ObjectName, DestinationView>();
private final Map temporaryQueues = new ConcurrentHashMap(); private final Map<ObjectName, DestinationView> temporaryQueues = new ConcurrentHashMap<ObjectName, DestinationView>();
private final Map temporaryTopics = new ConcurrentHashMap(); private final Map<ObjectName, DestinationView> temporaryTopics = new ConcurrentHashMap<ObjectName, DestinationView>();
private final Map queueSubscribers = new ConcurrentHashMap(); private final Map<ObjectName, SubscriptionView> queueSubscribers = new ConcurrentHashMap<ObjectName, SubscriptionView>();
private final Map topicSubscribers = new ConcurrentHashMap(); private final Map<ObjectName, SubscriptionView> topicSubscribers = new ConcurrentHashMap<ObjectName, SubscriptionView>();
private final Map durableTopicSubscribers = new ConcurrentHashMap(); private final Map<ObjectName, SubscriptionView> durableTopicSubscribers = new ConcurrentHashMap<ObjectName, SubscriptionView>();
private final Map inactiveDurableTopicSubscribers = new ConcurrentHashMap(); private final Map<ObjectName, SubscriptionView> inactiveDurableTopicSubscribers = new ConcurrentHashMap<ObjectName, SubscriptionView>();
private final Map temporaryQueueSubscribers = new ConcurrentHashMap(); private final Map<ObjectName, SubscriptionView> temporaryQueueSubscribers = new ConcurrentHashMap<ObjectName, SubscriptionView>();
private final Map temporaryTopicSubscribers = new ConcurrentHashMap(); private final Map<ObjectName, SubscriptionView> temporaryTopicSubscribers = new ConcurrentHashMap<ObjectName, SubscriptionView>();
private final Map subscriptionKeys = new ConcurrentHashMap(); private final Map<SubscriptionKey, ObjectName> subscriptionKeys = new ConcurrentHashMap<SubscriptionKey, ObjectName>();
private final Map subscriptionMap = new ConcurrentHashMap(); private final Map<Subscription, ObjectName> subscriptionMap = new ConcurrentHashMap<Subscription, ObjectName>();
private final Set registeredMBeans = new CopyOnWriteArraySet(); private final Set<ObjectName> registeredMBeans = new CopyOnWriteArraySet<ObjectName>();
/* This is the first broker in the broker interceptor chain. */ /* This is the first broker in the broker interceptor chain. */
private Broker contextBroker; private Broker contextBroker;
@ -108,8 +108,8 @@ public class ManagedRegionBroker extends RegionBroker {
protected void doStop(ServiceStopper stopper) { protected void doStop(ServiceStopper stopper) {
super.doStop(stopper); super.doStop(stopper);
// lets remove any mbeans not yet removed // lets remove any mbeans not yet removed
for (Iterator iter = registeredMBeans.iterator(); iter.hasNext();) { for (Iterator<ObjectName> iter = registeredMBeans.iterator(); iter.hasNext();) {
ObjectName name = (ObjectName)iter.next(); ObjectName name = iter.next();
try { try {
mbeanServer.unregisterMBean(name); mbeanServer.unregisterMBean(name);
} catch (InstanceNotFoundException e) { } catch (InstanceNotFoundException e) {
@ -211,7 +211,7 @@ public class ManagedRegionBroker extends RegionBroker {
} }
public void unregisterSubscription(Subscription sub) { public void unregisterSubscription(Subscription sub) {
ObjectName name = (ObjectName)subscriptionMap.remove(sub); ObjectName name = subscriptionMap.remove(sub);
if (name != null) { if (name != null) {
try { try {
unregisterSubscription(name); unregisterSubscription(name);
@ -275,7 +275,7 @@ public class ManagedRegionBroker extends RegionBroker {
durableTopicSubscribers.put(key, view); durableTopicSubscribers.put(key, view);
// unregister any inactive durable subs // unregister any inactive durable subs
try { try {
ObjectName inactiveName = (ObjectName)subscriptionKeys.get(subscriptionKey); ObjectName inactiveName = subscriptionKeys.get(subscriptionKey);
if (inactiveName != null) { if (inactiveName != null) {
inactiveDurableTopicSubscribers.remove(inactiveName); inactiveDurableTopicSubscribers.remove(inactiveName);
registeredMBeans.remove(inactiveName); registeredMBeans.remove(inactiveName);
@ -327,7 +327,7 @@ public class ManagedRegionBroker extends RegionBroker {
} }
protected void buildExistingSubscriptions() throws Exception { protected void buildExistingSubscriptions() throws Exception {
Map subscriptions = new HashMap(); Map<SubscriptionKey, SubscriptionInfo> subscriptions = new HashMap<SubscriptionKey, SubscriptionInfo>();
Set destinations = destinationFactory.getDestinations(); Set destinations = destinationFactory.getDestinations();
if (destinations != null) { if (destinations != null) {
for (Iterator iter = destinations.iterator(); iter.hasNext();) { for (Iterator iter = destinations.iterator(); iter.hasNext();) {
@ -376,11 +376,11 @@ public class ManagedRegionBroker extends RegionBroker {
} }
public CompositeData[] browse(SubscriptionView view) throws OpenDataException { public CompositeData[] browse(SubscriptionView view) throws OpenDataException {
List messages = getSubscriberMessages(view); List<Message> messages = getSubscriberMessages(view);
CompositeData c[] = new CompositeData[messages.size()]; CompositeData c[] = new CompositeData[messages.size()];
for (int i = 0; i < c.length; i++) { for (int i = 0; i < c.length; i++) {
try { try {
c[i] = OpenTypeSupport.convert((Message)messages.get(i)); c[i] = OpenTypeSupport.convert(messages.get(i));
} catch (Throwable e) { } catch (Throwable e) {
LOG.error("failed to browse : " + view, e); LOG.error("failed to browse : " + view, e);
} }
@ -390,7 +390,7 @@ public class ManagedRegionBroker extends RegionBroker {
public TabularData browseAsTable(SubscriptionView view) throws OpenDataException { public TabularData browseAsTable(SubscriptionView view) throws OpenDataException {
OpenTypeFactory factory = OpenTypeSupport.getFactory(ActiveMQMessage.class); OpenTypeFactory factory = OpenTypeSupport.getFactory(ActiveMQMessage.class);
List messages = getSubscriberMessages(view); List<Message> messages = getSubscriberMessages(view);
CompositeType ct = factory.getCompositeType(); CompositeType ct = factory.getCompositeType();
TabularType tt = new TabularType("MessageList", "MessageList", ct, new String[] {"JMSMessageID"}); TabularType tt = new TabularType("MessageList", "MessageList", ct, new String[] {"JMSMessageID"});
TabularDataSupport rc = new TabularDataSupport(tt); TabularDataSupport rc = new TabularDataSupport(tt);
@ -400,13 +400,13 @@ public class ManagedRegionBroker extends RegionBroker {
return rc; return rc;
} }
protected List getSubscriberMessages(SubscriptionView view) { protected List<Message> getSubscriberMessages(SubscriptionView view) {
// TODO It is very dangerous operation for big backlogs // TODO It is very dangerous operation for big backlogs
if (!(destinationFactory instanceof DestinationFactoryImpl)) { if (!(destinationFactory instanceof DestinationFactoryImpl)) {
throw new RuntimeException("unsupported by " + destinationFactory); throw new RuntimeException("unsupported by " + destinationFactory);
} }
PersistenceAdapter adapter = ((DestinationFactoryImpl)destinationFactory).getPersistenceAdapter(); PersistenceAdapter adapter = ((DestinationFactoryImpl)destinationFactory).getPersistenceAdapter();
final List result = new ArrayList(); final List<Message> result = new ArrayList<Message>();
try { try {
ActiveMQTopic topic = new ActiveMQTopic(view.getDestinationName()); ActiveMQTopic topic = new ActiveMQTopic(view.getDestinationName());
TopicMessageStore store = adapter.createTopicMessageStore(topic); TopicMessageStore store = adapter.createTopicMessageStore(topic);
@ -435,53 +435,53 @@ public class ManagedRegionBroker extends RegionBroker {
} }
protected ObjectName[] getTopics() { protected ObjectName[] getTopics() {
Set set = topics.keySet(); Set<ObjectName> set = topics.keySet();
return (ObjectName[])set.toArray(new ObjectName[set.size()]); return set.toArray(new ObjectName[set.size()]);
} }
protected ObjectName[] getQueues() { protected ObjectName[] getQueues() {
Set set = queues.keySet(); Set<ObjectName> set = queues.keySet();
return (ObjectName[])set.toArray(new ObjectName[set.size()]); return set.toArray(new ObjectName[set.size()]);
} }
protected ObjectName[] getTemporaryTopics() { protected ObjectName[] getTemporaryTopics() {
Set set = temporaryTopics.keySet(); Set<ObjectName> set = temporaryTopics.keySet();
return (ObjectName[])set.toArray(new ObjectName[set.size()]); return set.toArray(new ObjectName[set.size()]);
} }
protected ObjectName[] getTemporaryQueues() { protected ObjectName[] getTemporaryQueues() {
Set set = temporaryQueues.keySet(); Set<ObjectName> set = temporaryQueues.keySet();
return (ObjectName[])set.toArray(new ObjectName[set.size()]); return set.toArray(new ObjectName[set.size()]);
} }
protected ObjectName[] getTopicSubscribers() { protected ObjectName[] getTopicSubscribers() {
Set set = topicSubscribers.keySet(); Set<ObjectName> set = topicSubscribers.keySet();
return (ObjectName[])set.toArray(new ObjectName[set.size()]); return set.toArray(new ObjectName[set.size()]);
} }
protected ObjectName[] getDurableTopicSubscribers() { protected ObjectName[] getDurableTopicSubscribers() {
Set set = durableTopicSubscribers.keySet(); Set<ObjectName> set = durableTopicSubscribers.keySet();
return (ObjectName[])set.toArray(new ObjectName[set.size()]); return set.toArray(new ObjectName[set.size()]);
} }
protected ObjectName[] getQueueSubscribers() { protected ObjectName[] getQueueSubscribers() {
Set set = queueSubscribers.keySet(); Set<ObjectName> set = queueSubscribers.keySet();
return (ObjectName[])set.toArray(new ObjectName[set.size()]); return set.toArray(new ObjectName[set.size()]);
} }
protected ObjectName[] getTemporaryTopicSubscribers() { protected ObjectName[] getTemporaryTopicSubscribers() {
Set set = temporaryTopicSubscribers.keySet(); Set<ObjectName> set = temporaryTopicSubscribers.keySet();
return (ObjectName[])set.toArray(new ObjectName[set.size()]); return set.toArray(new ObjectName[set.size()]);
} }
protected ObjectName[] getTemporaryQueueSubscribers() { protected ObjectName[] getTemporaryQueueSubscribers() {
Set set = temporaryQueueSubscribers.keySet(); Set<ObjectName> set = temporaryQueueSubscribers.keySet();
return (ObjectName[])set.toArray(new ObjectName[set.size()]); return set.toArray(new ObjectName[set.size()]);
} }
protected ObjectName[] getInactiveDurableTopicSubscribers() { protected ObjectName[] getInactiveDurableTopicSubscribers() {
Set set = inactiveDurableTopicSubscribers.keySet(); Set<ObjectName> set = inactiveDurableTopicSubscribers.keySet();
return (ObjectName[])set.toArray(new ObjectName[set.size()]); return set.toArray(new ObjectName[set.size()]);
} }
public Broker getContextBroker() { public Broker getContextBroker() {

View File

@ -105,8 +105,9 @@ public class NetworkConnectorView implements NetworkConnectorViewMBean {
public String getPassword() { public String getPassword() {
String pw = connector.getPassword(); String pw = connector.getPassword();
// Hide the password for security reasons. // Hide the password for security reasons.
if (pw != null) if (pw != null) {
pw = pw.replaceAll(".", "*"); pw = pw.replaceAll(".", "*");
}
return pw; return pw;
} }

View File

@ -20,6 +20,7 @@ import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import javax.jms.DeliveryMode; import javax.jms.DeliveryMode;
@ -40,22 +41,22 @@ import org.apache.activemq.command.ActiveMQStreamMessage;
import org.apache.activemq.command.ActiveMQTextMessage; import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.activemq.command.Message; import org.apache.activemq.command.Message;
public class OpenTypeSupport { public final class OpenTypeSupport {
interface OpenTypeFactory { interface OpenTypeFactory {
CompositeType getCompositeType() throws OpenDataException; CompositeType getCompositeType() throws OpenDataException;
Map getFields(Object o) throws OpenDataException; Map<String, Object> getFields(Object o) throws OpenDataException;
} }
private static final HashMap OPEN_TYPE_FACTORIES = new HashMap(); private static final Map<Class, MessageOpenTypeFactory> OPEN_TYPE_FACTORIES = new HashMap<Class, MessageOpenTypeFactory>();
abstract static class AbstractOpenTypeFactory implements OpenTypeFactory { abstract static class AbstractOpenTypeFactory implements OpenTypeFactory {
private CompositeType compositeType; private CompositeType compositeType;
ArrayList itemNamesList = new ArrayList(); private List<String> itemNamesList = new ArrayList<String>();
ArrayList itemDescriptionsList = new ArrayList(); private List<String> itemDescriptionsList = new ArrayList<String>();
ArrayList itemTypesList = new ArrayList(); private List<OpenType> itemTypesList = new ArrayList<OpenType>();
public CompositeType getCompositeType() throws OpenDataException { public CompositeType getCompositeType() throws OpenDataException {
if (compositeType == null) { if (compositeType == null) {
@ -69,9 +70,9 @@ public class OpenTypeSupport {
} }
protected CompositeType createCompositeType() throws OpenDataException { protected CompositeType createCompositeType() throws OpenDataException {
String[] itemNames = (String[])itemNamesList.toArray(new String[itemNamesList.size()]); String[] itemNames = itemNamesList.toArray(new String[itemNamesList.size()]);
String[] itemDescriptions = (String[])itemDescriptionsList.toArray(new String[itemDescriptionsList.size()]); String[] itemDescriptions = itemDescriptionsList.toArray(new String[itemDescriptionsList.size()]);
OpenType[] itemTypes = (OpenType[])itemTypesList.toArray(new OpenType[itemTypesList.size()]); OpenType[] itemTypes = itemTypesList.toArray(new OpenType[itemTypesList.size()]);
return new CompositeType(getTypeName(), getDescription(), itemNames, itemDescriptions, itemTypes); return new CompositeType(getTypeName(), getDescription(), itemNames, itemDescriptions, itemTypes);
} }
@ -87,8 +88,8 @@ public class OpenTypeSupport {
return getTypeName(); return getTypeName();
} }
public Map getFields(Object o) throws OpenDataException { public Map<String, Object> getFields(Object o) throws OpenDataException {
HashMap rc = new HashMap(); Map<String, Object> rc = new HashMap<String, Object>();
return rc; return rc;
} }
} }
@ -114,9 +115,9 @@ public class OpenTypeSupport {
addItem("Properties", "Properties", SimpleType.STRING); addItem("Properties", "Properties", SimpleType.STRING);
} }
public Map getFields(Object o) throws OpenDataException { public Map<String, Object> getFields(Object o) throws OpenDataException {
ActiveMQMessage m = (ActiveMQMessage)o; ActiveMQMessage m = (ActiveMQMessage)o;
Map rc = super.getFields(o); Map<String, Object> rc = super.getFields(o);
rc.put("JMSCorrelationID", m.getJMSCorrelationID()); rc.put("JMSCorrelationID", m.getJMSCorrelationID());
rc.put("JMSDestination", "" + m.getJMSDestination()); rc.put("JMSDestination", "" + m.getJMSDestination());
rc.put("JMSMessageID", m.getJMSMessageID()); rc.put("JMSMessageID", m.getJMSMessageID());
@ -148,9 +149,9 @@ public class OpenTypeSupport {
addItem("BodyPreview", "Body preview", new ArrayType(1, SimpleType.BYTE)); addItem("BodyPreview", "Body preview", new ArrayType(1, SimpleType.BYTE));
} }
public Map getFields(Object o) throws OpenDataException { public Map<String, Object> getFields(Object o) throws OpenDataException {
ActiveMQBytesMessage m = (ActiveMQBytesMessage)o; ActiveMQBytesMessage m = (ActiveMQBytesMessage)o;
Map rc = super.getFields(o); Map<String, Object> rc = super.getFields(o);
long length = 0; long length = 0;
try { try {
length = m.getBodyLength(); length = m.getBodyLength();
@ -189,10 +190,9 @@ public class OpenTypeSupport {
addItem("ContentMap", "Content map", SimpleType.STRING); addItem("ContentMap", "Content map", SimpleType.STRING);
} }
public Map getFields(Object o) throws OpenDataException { public Map<String, Object> getFields(Object o) throws OpenDataException {
ActiveMQMapMessage m = (ActiveMQMapMessage)o; ActiveMQMapMessage m = (ActiveMQMapMessage)o;
Map rc = super.getFields(o); Map<String, Object> rc = super.getFields(o);
long length = 0;
try { try {
rc.put("ContentMap", "" + m.getContentMap()); rc.put("ContentMap", "" + m.getContentMap());
} catch (JMSException e) { } catch (JMSException e) {
@ -211,9 +211,8 @@ public class OpenTypeSupport {
super.init(); super.init();
} }
public Map getFields(Object o) throws OpenDataException { public Map<String, Object> getFields(Object o) throws OpenDataException {
ActiveMQObjectMessage m = (ActiveMQObjectMessage)o; Map<String, Object> rc = super.getFields(o);
Map rc = super.getFields(o);
return rc; return rc;
} }
} }
@ -227,9 +226,8 @@ public class OpenTypeSupport {
super.init(); super.init();
} }
public Map getFields(Object o) throws OpenDataException { public Map<String, Object> getFields(Object o) throws OpenDataException {
ActiveMQStreamMessage m = (ActiveMQStreamMessage)o; Map<String, Object> rc = super.getFields(o);
Map rc = super.getFields(o);
return rc; return rc;
} }
} }
@ -244,9 +242,9 @@ public class OpenTypeSupport {
addItem("Text", "Text", SimpleType.STRING); addItem("Text", "Text", SimpleType.STRING);
} }
public Map getFields(Object o) throws OpenDataException { public Map<String, Object> getFields(Object o) throws OpenDataException {
ActiveMQTextMessage m = (ActiveMQTextMessage)o; ActiveMQTextMessage m = (ActiveMQTextMessage)o;
Map rc = super.getFields(o); Map<String, Object> rc = super.getFields(o);
try { try {
rc.put("Text", "" + m.getText()); rc.put("Text", "" + m.getText());
} catch (JMSException e) { } catch (JMSException e) {
@ -265,16 +263,20 @@ public class OpenTypeSupport {
OPEN_TYPE_FACTORIES.put(ActiveMQTextMessage.class, new TextMessageOpenTypeFactory()); OPEN_TYPE_FACTORIES.put(ActiveMQTextMessage.class, new TextMessageOpenTypeFactory());
} }
public static OpenTypeFactory getFactory(Class clazz) throws OpenDataException { private OpenTypeSupport() {
return (OpenTypeFactory)OPEN_TYPE_FACTORIES.get(clazz); }
public static OpenTypeFactory getFactory(Class<? extends Message> clazz) throws OpenDataException {
return OPEN_TYPE_FACTORIES.get(clazz);
} }
public static CompositeData convert(Message message) throws OpenDataException { public static CompositeData convert(Message message) throws OpenDataException {
OpenTypeFactory f = getFactory(message.getClass()); OpenTypeFactory f = getFactory(message.getClass());
if (f == null) if (f == null) {
throw new OpenDataException("Cannot create a CompositeData for type: " + message.getClass().getName()); throw new OpenDataException("Cannot create a CompositeData for type: " + message.getClass().getName());
}
CompositeType ct = f.getCompositeType(); CompositeType ct = f.getCompositeType();
Map fields = f.getFields(message); Map<String, Object> fields = f.getFields(message);
return new CompositeDataSupport(ct, fields); return new CompositeDataSupport(ct, fields);
} }

View File

@ -34,8 +34,9 @@ public class QueueView extends DestinationView implements QueueViewMBean {
public CompositeData getMessage(String messageId) throws OpenDataException { public CompositeData getMessage(String messageId) throws OpenDataException {
Message rc = ((Queue)destination).getMessage(messageId); Message rc = ((Queue)destination).getMessage(messageId);
if (rc == null) if (rc == null) {
return null; return null;
}
return OpenTypeSupport.convert(rc); return OpenTypeSupport.convert(rc);
} }

View File

@ -31,6 +31,7 @@ import org.apache.activemq.broker.ConsumerBrokerExchange;
import org.apache.activemq.broker.DestinationAlreadyExistsException; import org.apache.activemq.broker.DestinationAlreadyExistsException;
import org.apache.activemq.broker.ProducerBrokerExchange; import org.apache.activemq.broker.ProducerBrokerExchange;
import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ConsumerId;
import org.apache.activemq.command.ConsumerInfo; import org.apache.activemq.command.ConsumerInfo;
import org.apache.activemq.command.Message; import org.apache.activemq.command.Message;
import org.apache.activemq.command.MessageAck; import org.apache.activemq.command.MessageAck;
@ -52,9 +53,9 @@ public abstract class AbstractRegion implements Region {
private static final Log LOG = LogFactory.getLog(AbstractRegion.class); private static final Log LOG = LogFactory.getLog(AbstractRegion.class);
protected final ConcurrentHashMap destinations = new ConcurrentHashMap(); protected final Map<ActiveMQDestination, Destination> destinations = new ConcurrentHashMap<ActiveMQDestination, Destination>();
protected final DestinationMap destinationMap = new DestinationMap(); protected final DestinationMap destinationMap = new DestinationMap();
protected final ConcurrentHashMap subscriptions = new ConcurrentHashMap(); protected final Map<ConsumerId, Subscription> subscriptions = new ConcurrentHashMap<ConsumerId, Subscription>();
protected final UsageManager memoryManager; protected final UsageManager memoryManager;
protected final DestinationFactory destinationFactory; protected final DestinationFactory destinationFactory;
protected final DestinationStatistics destinationStatistics; protected final DestinationStatistics destinationStatistics;
@ -62,7 +63,7 @@ public abstract class AbstractRegion implements Region {
protected boolean autoCreateDestinations = true; protected boolean autoCreateDestinations = true;
protected final TaskRunnerFactory taskRunnerFactory; protected final TaskRunnerFactory taskRunnerFactory;
protected final Object destinationsMutex = new Object(); protected final Object destinationsMutex = new Object();
protected final Map consumerChangeMutexMap = new HashMap(); protected final Map<ConsumerId, Object> consumerChangeMutexMap = new HashMap<ConsumerId, Object>();
protected boolean started; protected boolean started;
public AbstractRegion(RegionBroker broker, DestinationStatistics destinationStatistics, UsageManager memoryManager, TaskRunnerFactory taskRunnerFactory, public AbstractRegion(RegionBroker broker, DestinationStatistics destinationStatistics, UsageManager memoryManager, TaskRunnerFactory taskRunnerFactory,
@ -83,25 +84,25 @@ public abstract class AbstractRegion implements Region {
public void start() throws Exception { public void start() throws Exception {
started = true; started = true;
Set inactiveDests = getInactiveDestinations(); Set<ActiveMQDestination> inactiveDests = getInactiveDestinations();
for (Iterator iter = inactiveDests.iterator(); iter.hasNext();) { for (Iterator<ActiveMQDestination> iter = inactiveDests.iterator(); iter.hasNext();) {
ActiveMQDestination dest = (ActiveMQDestination)iter.next(); ActiveMQDestination dest = iter.next();
ConnectionContext context = new ConnectionContext(); ConnectionContext context = new ConnectionContext();
context.setBroker(broker.getBrokerService().getBroker()); context.setBroker(broker.getBrokerService().getBroker());
context.getBroker().addDestination(context, dest); context.getBroker().addDestination(context, dest);
} }
for (Iterator i = destinations.values().iterator(); i.hasNext();) { for (Iterator<Destination> i = destinations.values().iterator(); i.hasNext();) {
Destination dest = (Destination)i.next(); Destination dest = i.next();
dest.start(); dest.start();
} }
} }
public void stop() throws Exception { public void stop() throws Exception {
started = false; started = false;
for (Iterator i = destinations.values().iterator(); i.hasNext();) { for (Iterator<Destination> i = destinations.values().iterator(); i.hasNext();) {
Destination dest = (Destination)i.next(); Destination dest = i.next();
dest.stop(); dest.stop();
} }
destinations.clear(); destinations.clear();
@ -110,7 +111,7 @@ public abstract class AbstractRegion implements Region {
public Destination addDestination(ConnectionContext context, ActiveMQDestination destination) throws Exception { public Destination addDestination(ConnectionContext context, ActiveMQDestination destination) throws Exception {
LOG.debug("Adding destination: " + destination); LOG.debug("Adding destination: " + destination);
synchronized (destinationsMutex) { synchronized (destinationsMutex) {
Destination dest = (Destination)destinations.get(destination); Destination dest = destinations.get(destination);
if (dest == null) { if (dest == null) {
dest = createDestination(context, destination); dest = createDestination(context, destination);
// intercept if there is a valid interceptor defined // intercept if there is a valid interceptor defined
@ -129,10 +130,10 @@ public abstract class AbstractRegion implements Region {
protected List<Subscription> addSubscriptionsForDestination(ConnectionContext context, Destination dest) throws Exception { protected List<Subscription> addSubscriptionsForDestination(ConnectionContext context, Destination dest) throws Exception {
ArrayList<Subscription> rc = new ArrayList<Subscription>(); List<Subscription> rc = new ArrayList<Subscription>();
// Add all consumers that are interested in the destination. // Add all consumers that are interested in the destination.
for (Iterator iter = subscriptions.values().iterator(); iter.hasNext();) { for (Iterator<Subscription> iter = subscriptions.values().iterator(); iter.hasNext();) {
Subscription sub = (Subscription)iter.next(); Subscription sub = iter.next();
if (sub.matches(dest.getActiveMQDestination())) { if (sub.matches(dest.getActiveMQDestination())) {
dest.addSubscription(context, sub); dest.addSubscription(context, sub);
rc.add(sub); rc.add(sub);
@ -147,8 +148,8 @@ public abstract class AbstractRegion implements Region {
// No timeout.. then try to shut down right way, fails if there are // No timeout.. then try to shut down right way, fails if there are
// current subscribers. // current subscribers.
if (timeout == 0) { if (timeout == 0) {
for (Iterator iter = subscriptions.values().iterator(); iter.hasNext();) { for (Iterator<Subscription> iter = subscriptions.values().iterator(); iter.hasNext();) {
Subscription sub = (Subscription)iter.next(); Subscription sub = iter.next();
if (sub.matches(destination)) { if (sub.matches(destination)) {
throw new JMSException("Destination still has an active subscription: " + destination); throw new JMSException("Destination still has an active subscription: " + destination);
} }
@ -166,13 +167,13 @@ public abstract class AbstractRegion implements Region {
LOG.debug("Removing destination: " + destination); LOG.debug("Removing destination: " + destination);
synchronized (destinationsMutex) { synchronized (destinationsMutex) {
Destination dest = (Destination)destinations.remove(destination); Destination dest = destinations.remove(destination);
if (dest != null) { if (dest != null) {
// timeout<0 or we timed out, we now force any remaining // timeout<0 or we timed out, we now force any remaining
// subscriptions to un-subscribe. // subscriptions to un-subscribe.
for (Iterator iter = subscriptions.values().iterator(); iter.hasNext();) { for (Iterator<Subscription> iter = subscriptions.values().iterator(); iter.hasNext();) {
Subscription sub = (Subscription)iter.next(); Subscription sub = iter.next();
if (sub.matches(destination)) { if (sub.matches(destination)) {
dest.removeSubscription(context, sub); dest.removeSubscription(context, sub);
} }
@ -199,9 +200,9 @@ public abstract class AbstractRegion implements Region {
} }
} }
public Map getDestinationMap() { public Map<ActiveMQDestination, Destination> getDestinationMap() {
synchronized (destinationsMutex) { synchronized (destinationsMutex) {
return new HashMap(destinations); return new HashMap<ActiveMQDestination, Destination>(destinations);
} }
} }
@ -222,10 +223,10 @@ public abstract class AbstractRegion implements Region {
} }
} }
synchronized (addGuard) { synchronized (addGuard) {
Object o = subscriptions.get(info.getConsumerId()); Subscription o = subscriptions.get(info.getConsumerId());
if (o != null) { if (o != null) {
LOG.warn("A duplicate subscription was detected. Clients may be misbehaving. Later warnings you may see about subscription removal are a consequence of this."); LOG.warn("A duplicate subscription was detected. Clients may be misbehaving. Later warnings you may see about subscription removal are a consequence of this.");
return (Subscription)o; return o;
} }
// We may need to add some destinations that are in persistent store // We may need to add some destinations that are in persistent store
@ -281,8 +282,8 @@ public abstract class AbstractRegion implements Region {
/** /**
* @return all Destinations that don't have active consumers * @return all Destinations that don't have active consumers
*/ */
protected Set getInactiveDestinations() { protected Set<ActiveMQDestination> getInactiveDestinations() {
Set inactiveDests = destinationFactory.getDestinations(); Set<ActiveMQDestination> inactiveDests = destinationFactory.getDestinations();
inactiveDests.removeAll(destinations.keySet()); inactiveDests.removeAll(destinations.keySet());
return inactiveDests; return inactiveDests;
} }
@ -290,9 +291,10 @@ public abstract class AbstractRegion implements Region {
public void removeConsumer(ConnectionContext context, ConsumerInfo info) throws Exception { public void removeConsumer(ConnectionContext context, ConsumerInfo info) throws Exception {
LOG.debug("Removing consumer: " + info.getConsumerId()); LOG.debug("Removing consumer: " + info.getConsumerId());
Subscription sub = (Subscription)subscriptions.remove(info.getConsumerId()); Subscription sub = subscriptions.remove(info.getConsumerId());
if (sub == null) if (sub == null) {
throw new IllegalArgumentException("The subscription does not exist: " + info.getConsumerId()); throw new IllegalArgumentException("The subscription does not exist: " + info.getConsumerId());
}
// remove the subscription from all the matching queues. // remove the subscription from all the matching queues.
for (Iterator iter = destinationMap.get(info.getDestination()).iterator(); iter.hasNext();) { for (Iterator iter = destinationMap.get(info.getDestination()).iterator(); iter.hasNext();) {
@ -329,7 +331,7 @@ public abstract class AbstractRegion implements Region {
public void acknowledge(ConsumerBrokerExchange consumerExchange, MessageAck ack) throws Exception { public void acknowledge(ConsumerBrokerExchange consumerExchange, MessageAck ack) throws Exception {
Subscription sub = consumerExchange.getSubscription(); Subscription sub = consumerExchange.getSubscription();
if (sub == null) { if (sub == null) {
sub = (Subscription)subscriptions.get(ack.getConsumerId()); sub = subscriptions.get(ack.getConsumerId());
if (sub == null) { if (sub == null) {
throw new IllegalArgumentException("The subscription does not exist: " + ack.getConsumerId()); throw new IllegalArgumentException("The subscription does not exist: " + ack.getConsumerId());
} }
@ -339,15 +341,16 @@ public abstract class AbstractRegion implements Region {
} }
public Response messagePull(ConnectionContext context, MessagePull pull) throws Exception { public Response messagePull(ConnectionContext context, MessagePull pull) throws Exception {
Subscription sub = (Subscription)subscriptions.get(pull.getConsumerId()); Subscription sub = subscriptions.get(pull.getConsumerId());
if (sub == null) if (sub == null) {
throw new IllegalArgumentException("The subscription does not exist: " + pull.getConsumerId()); throw new IllegalArgumentException("The subscription does not exist: " + pull.getConsumerId());
}
return sub.pullMessage(context, pull); return sub.pullMessage(context, pull);
} }
protected Destination lookup(ConnectionContext context, ActiveMQDestination destination) throws Exception { protected Destination lookup(ConnectionContext context, ActiveMQDestination destination) throws Exception {
synchronized (destinationsMutex) { synchronized (destinationsMutex) {
Destination dest = (Destination)destinations.get(destination); Destination dest = destinations.get(destination);
if (dest == null) { if (dest == null) {
if (autoCreateDestinations) { if (autoCreateDestinations) {
// Try to auto create the destination... re-invoke broker // Try to auto create the destination... re-invoke broker
@ -362,7 +365,7 @@ public abstract class AbstractRegion implements Region {
// this error // this error
} }
// We should now have the dest created. // We should now have the dest created.
dest = (Destination)destinations.get(destination); dest = destinations.get(destination);
} }
if (dest == null) { if (dest == null) {
throw new JMSException("The destination " + destination + " does not exist."); throw new JMSException("The destination " + destination + " does not exist.");
@ -373,19 +376,19 @@ public abstract class AbstractRegion implements Region {
} }
public void processDispatchNotification(MessageDispatchNotification messageDispatchNotification) throws Exception { public void processDispatchNotification(MessageDispatchNotification messageDispatchNotification) throws Exception {
Subscription sub = (Subscription)subscriptions.get(messageDispatchNotification.getConsumerId()); Subscription sub = subscriptions.get(messageDispatchNotification.getConsumerId());
if (sub != null) { if (sub != null) {
sub.processMessageDispatchNotification(messageDispatchNotification); sub.processMessageDispatchNotification(messageDispatchNotification);
} }
} }
public void gc() { public void gc() {
for (Iterator iter = subscriptions.values().iterator(); iter.hasNext();) { for (Iterator<Subscription> iter = subscriptions.values().iterator(); iter.hasNext();) {
Subscription sub = (Subscription)iter.next(); Subscription sub = iter.next();
sub.gc(); sub.gc();
} }
for (Iterator iter = destinations.values().iterator(); iter.hasNext();) { for (Iterator<Destination> iter = destinations.values().iterator(); iter.hasNext();) {
Destination dest = (Destination)iter.next(); Destination dest = iter.next();
dest.gc(); dest.gc();
} }
} }

View File

@ -45,7 +45,7 @@ public abstract class AbstractSubscription implements Subscription {
protected ConnectionContext context; protected ConnectionContext context;
protected ConsumerInfo info; protected ConsumerInfo info;
protected final DestinationFilter destinationFilter; protected final DestinationFilter destinationFilter;
protected final CopyOnWriteArrayList destinations = new CopyOnWriteArrayList(); protected final CopyOnWriteArrayList<Destination> destinations = new CopyOnWriteArrayList<Destination>();
private BooleanExpression selectorExpression; private BooleanExpression selectorExpression;
private ObjectName objectName; private ObjectName objectName;
@ -83,8 +83,9 @@ public abstract class AbstractSubscription implements Subscription {
public boolean matches(MessageReference node, MessageEvaluationContext context) throws IOException { public boolean matches(MessageReference node, MessageEvaluationContext context) throws IOException {
ConsumerId targetConsumerId = node.getTargetConsumerId(); ConsumerId targetConsumerId = node.getTargetConsumerId();
if (targetConsumerId != null) { if (targetConsumerId != null) {
if (!targetConsumerId.equals(info.getConsumerId())) if (!targetConsumerId.equals(info.getConsumerId())) {
return false; return false;
}
} }
try { try {
return (selectorExpression == null || selectorExpression.matches(context)) && this.context.isAllowedToConsume(node); return (selectorExpression == null || selectorExpression.matches(context)) && this.context.isAllowedToConsume(node);

View File

@ -41,7 +41,7 @@ public abstract class DestinationFactory {
* Returns a set of all the {@link org.apache.activemq.command.ActiveMQDestination} * Returns a set of all the {@link org.apache.activemq.command.ActiveMQDestination}
* objects that the persistence store is aware exist. * objects that the persistence store is aware exist.
*/ */
public abstract Set getDestinations(); public abstract Set<ActiveMQDestination> getDestinations();
/** /**
* Lists all the durable subscirptions for a given destination. * Lists all the durable subscirptions for a given destination.

View File

@ -140,11 +140,13 @@ public class IndirectMessageReference implements QueueMessageReference {
} }
public boolean lock(LockOwner subscription) { public boolean lock(LockOwner subscription) {
if (!regionDestination.lock(this, subscription)) if (!regionDestination.lock(this, subscription)) {
return false; return false;
}
synchronized (this) { synchronized (this) {
if (dropped || (lockOwner != null && lockOwner != subscription)) if (dropped || (lockOwner != null && lockOwner != subscription)) {
return false; return false;
}
lockOwner = subscription; lockOwner = subscription;
return true; return true;
} }

View File

@ -50,7 +50,7 @@ public abstract class PrefetchSubscription extends AbstractSubscription {
private static final Log LOG = LogFactory.getLog(PrefetchSubscription.class); private static final Log LOG = LogFactory.getLog(PrefetchSubscription.class);
protected PendingMessageCursor pending; protected PendingMessageCursor pending;
protected final LinkedList dispatched = new LinkedList(); protected final LinkedList<MessageReference> dispatched = new LinkedList<MessageReference>();
protected int prefetchExtension; protected int prefetchExtension;
protected long enqueueCounter; protected long enqueueCounter;
protected long dispatchCounter; protected long dispatchCounter;
@ -158,8 +158,8 @@ public abstract class PrefetchSubscription extends AbstractSubscription {
// acknowledgment. // acknowledgment.
int index = 0; int index = 0;
boolean inAckRange = false; boolean inAckRange = false;
for (Iterator iter = dispatched.iterator(); iter.hasNext();) { for (Iterator<MessageReference> iter = dispatched.iterator(); iter.hasNext();) {
final MessageReference node = (MessageReference)iter.next(); final MessageReference node = iter.next();
MessageId messageId = node.getMessageId(); MessageId messageId = node.getMessageId();
if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) {
inAckRange = true; inAckRange = true;
@ -219,8 +219,8 @@ public abstract class PrefetchSubscription extends AbstractSubscription {
// Acknowledge all dispatched messages up till the message id of the // Acknowledge all dispatched messages up till the message id of the
// acknowledgment. // acknowledgment.
int index = 0; int index = 0;
for (Iterator iter = dispatched.iterator(); iter.hasNext(); index++) { for (Iterator<MessageReference> iter = dispatched.iterator(); iter.hasNext(); index++) {
final MessageReference node = (MessageReference)iter.next(); final MessageReference node = iter.next();
if (ack.getLastMessageId().equals(node.getMessageId())) { if (ack.getLastMessageId().equals(node.getMessageId())) {
prefetchExtension = Math.max(prefetchExtension, index + 1); prefetchExtension = Math.max(prefetchExtension, index + 1);
callDispatchMatched = true; callDispatchMatched = true;
@ -233,14 +233,15 @@ public abstract class PrefetchSubscription extends AbstractSubscription {
} else if (ack.isPoisonAck()) { } else if (ack.isPoisonAck()) {
// TODO: what if the message is already in a DLQ??? // TODO: what if the message is already in a DLQ???
// Handle the poison ACK case: we need to send the message to a DLQ // Handle the poison ACK case: we need to send the message to a DLQ
if (ack.isInTransaction()) if (ack.isInTransaction()) {
throw new JMSException("Poison ack cannot be transacted: " + ack); throw new JMSException("Poison ack cannot be transacted: " + ack);
}
// Acknowledge all dispatched messages up till the message id of the // Acknowledge all dispatched messages up till the message id of the
// acknowledgment. // acknowledgment.
int index = 0; int index = 0;
boolean inAckRange = false; boolean inAckRange = false;
for (Iterator iter = dispatched.iterator(); iter.hasNext();) { for (Iterator<MessageReference> iter = dispatched.iterator(); iter.hasNext();) {
final MessageReference node = (MessageReference)iter.next(); final MessageReference node = iter.next();
MessageId messageId = node.getMessageId(); MessageId messageId = node.getMessageId();
if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) { if (ack.getFirstMessageId() == null || ack.getFirstMessageId().equals(messageId)) {
inAckRange = true; inAckRange = true;
@ -380,8 +381,9 @@ public abstract class PrefetchSubscription extends AbstractSubscription {
pending.reset(); pending.reset();
while (pending.hasNext() && !isFull() && count < numberToDispatch) { while (pending.hasNext() && !isFull() && count < numberToDispatch) {
MessageReference node = pending.next(); MessageReference node = pending.next();
if (node == null) if (node == null) {
break; break;
}
if (canDispatch(node)) { if (canDispatch(node)) {
pending.remove(); pending.remove();
// Message may have been sitting in the pending list // Message may have been sitting in the pending list

View File

@ -76,12 +76,12 @@ public class Queue implements Destination, Task {
private final Log log; private final Log log;
private final ActiveMQDestination destination; private final ActiveMQDestination destination;
private final List consumers = new CopyOnWriteArrayList(); private final List<Subscription> consumers = new CopyOnWriteArrayList<Subscription>();
private final Valve dispatchValve = new Valve(true); private final Valve dispatchValve = new Valve(true);
private final UsageManager usageManager; private final UsageManager usageManager;
private final DestinationStatistics destinationStatistics = new DestinationStatistics(); private final DestinationStatistics destinationStatistics = new DestinationStatistics();
private PendingMessageCursor messages; private PendingMessageCursor messages;
private final LinkedList pagedInMessages = new LinkedList(); private final LinkedList<MessageReference> pagedInMessages = new LinkedList<MessageReference>();
private LockOwner exclusiveOwner; private LockOwner exclusiveOwner;
private MessageGroupMap messageGroupOwners; private MessageGroupMap messageGroupOwners;
@ -96,7 +96,16 @@ public class Queue implements Destination, Task {
private final Object exclusiveLockMutex = new Object(); private final Object exclusiveLockMutex = new Object();
private final Object doDispatchMutex = new Object(); private final Object doDispatchMutex = new Object();
private TaskRunner taskRunner; private TaskRunner taskRunner;
private boolean started;
private final LinkedList<Runnable> messagesWaitingForSpace = new LinkedList<Runnable>();
private final Runnable sendMessagesWaitingForSpaceTask = new Runnable() {
public void run() {
try {
taskRunner.wakeup();
} catch (InterruptedException e) {
}
};
};
public Queue(Broker broker, ActiveMQDestination destination, final UsageManager memoryManager, MessageStore store, DestinationStatistics parentStats, public Queue(Broker broker, ActiveMQDestination destination, final UsageManager memoryManager, MessageStore store, DestinationStatistics parentStats,
TaskRunnerFactory taskFactory, Store tmpStore) throws Exception { TaskRunnerFactory taskFactory, Store tmpStore) throws Exception {
@ -161,9 +170,6 @@ public class Queue implements Destination, Task {
throw new RuntimeException("Should not be called."); throw new RuntimeException("Should not be called.");
} }
public void finished() {
}
public boolean hasSpace() { public boolean hasSpace() {
return true; return true;
} }
@ -183,10 +189,12 @@ public class Queue implements Destination, Task {
*/ */
public boolean lock(MessageReference node, LockOwner lockOwner) { public boolean lock(MessageReference node, LockOwner lockOwner) {
synchronized (exclusiveLockMutex) { synchronized (exclusiveLockMutex) {
if (exclusiveOwner == lockOwner) if (exclusiveOwner == lockOwner) {
return true; return true;
if (exclusiveOwner != null) }
if (exclusiveOwner != null) {
return false; return false;
}
} }
return true; return true;
} }
@ -225,7 +233,7 @@ public class Queue implements Destination, Task {
synchronized (pagedInMessages) { synchronized (pagedInMessages) {
// Add all the matching messages in the queue to the // Add all the matching messages in the queue to the
// subscription. // subscription.
for (Iterator i = pagedInMessages.iterator(); i.hasNext();) { for (Iterator<MessageReference> i = pagedInMessages.iterator(); i.hasNext();) {
QueueMessageReference node = (QueueMessageReference)i.next(); QueueMessageReference node = (QueueMessageReference)i.next();
if (node.isDropped()) { if (node.isDropped()) {
continue; continue;
@ -269,11 +277,12 @@ public class Queue implements Destination, Task {
// Find the exclusive consumer with the higest Lock // Find the exclusive consumer with the higest Lock
// Priority. // Priority.
exclusiveOwner = null; exclusiveOwner = null;
for (Iterator iter = consumers.iterator(); iter.hasNext();) { for (Iterator<Subscription> iter = consumers.iterator(); iter.hasNext();) {
Subscription s = (Subscription)iter.next(); Subscription s = iter.next();
LockOwner so = (LockOwner)s; LockOwner so = (LockOwner)s;
if (s.getConsumerInfo().isExclusive() && (exclusiveOwner == null || so.getLockPriority() > exclusiveOwner.getLockPriority())) if (s.getConsumerInfo().isExclusive() && (exclusiveOwner == null || so.getLockPriority() > exclusiveOwner.getLockPriority())) {
exclusiveOwner = so; exclusiveOwner = so;
}
} }
} }
} }
@ -299,9 +308,9 @@ public class Queue implements Destination, Task {
msgContext.setDestination(destination); msgContext.setDestination(destination);
// lets copy the messages to dispatch to avoid deadlock // lets copy the messages to dispatch to avoid deadlock
List messagesToDispatch = new ArrayList(); List<QueueMessageReference> messagesToDispatch = new ArrayList<QueueMessageReference>();
synchronized (pagedInMessages) { synchronized (pagedInMessages) {
for (Iterator i = pagedInMessages.iterator(); i.hasNext();) { for (Iterator<MessageReference> i = pagedInMessages.iterator(); i.hasNext();) {
QueueMessageReference node = (QueueMessageReference)i.next(); QueueMessageReference node = (QueueMessageReference)i.next();
if (node.isDropped()) { if (node.isDropped()) {
continue; continue;
@ -318,8 +327,8 @@ public class Queue implements Destination, Task {
// now lets dispatch from the copy of the collection to // now lets dispatch from the copy of the collection to
// avoid deadlocks // avoid deadlocks
for (Iterator iter = messagesToDispatch.iterator(); iter.hasNext();) { for (Iterator<QueueMessageReference> iter = messagesToDispatch.iterator(); iter.hasNext();) {
QueueMessageReference node = (QueueMessageReference)iter.next(); QueueMessageReference node = iter.next();
node.incrementRedeliveryCounter(); node.incrementRedeliveryCounter();
node.unlock(); node.unlock();
msgContext.setMessageReference(node); msgContext.setMessageReference(node);
@ -335,16 +344,6 @@ public class Queue implements Destination, Task {
} }
private final LinkedList<Runnable> messagesWaitingForSpace = new LinkedList<Runnable>();
private final Runnable sendMessagesWaitingForSpaceTask = new Runnable() {
public void run() {
try {
taskRunner.wakeup();
} catch (InterruptedException e) {
}
};
};
public void send(final ProducerBrokerExchange producerExchange, final Message message) throws Exception { public void send(final ProducerBrokerExchange producerExchange, final Message message) throws Exception {
final ConnectionContext context = producerExchange.getConnectionContext(); final ConnectionContext context = producerExchange.getConnectionContext();
// There is delay between the client sending it and it arriving at the // There is delay between the client sending it and it arriving at the
@ -419,8 +418,9 @@ public class Queue implements Destination, Task {
// control at the broker // control at the broker
// by blocking this thread until there is space available. // by blocking this thread until there is space available.
while (!usageManager.waitForSpace(1000)) { while (!usageManager.waitForSpace(1000)) {
if (context.getStopping().get()) if (context.getStopping().get()) {
throw new IOException("Connection closed, send aborted."); throw new IOException("Connection closed, send aborted.");
}
} }
// The usage manager could have delayed us by the time // The usage manager could have delayed us by the time
@ -508,7 +508,7 @@ public class Queue implements Destination, Task {
public void gc() { public void gc() {
synchronized (pagedInMessages) { synchronized (pagedInMessages) {
for (Iterator i = pagedInMessages.iterator(); i.hasNext();) { for (Iterator<MessageReference> i = pagedInMessages.iterator(); i.hasNext();) {
// Remove dropped messages from the queue. // Remove dropped messages from the queue.
QueueMessageReference node = (QueueMessageReference)i.next(); QueueMessageReference node = (QueueMessageReference)i.next();
if (node.isDropped()) { if (node.isDropped()) {
@ -557,7 +557,6 @@ public class Queue implements Destination, Task {
} }
public void start() throws Exception { public void start() throws Exception {
started = true;
if (usageManager != null) { if (usageManager != null) {
usageManager.start(); usageManager.start();
} }
@ -566,7 +565,6 @@ public class Queue implements Destination, Task {
} }
public void stop() throws Exception { public void stop() throws Exception {
started = false;
if (taskRunner != null) { if (taskRunner != null) {
taskRunner.shutdown(); taskRunner.shutdown();
} }
@ -652,15 +650,15 @@ public class Queue implements Destination, Task {
} }
public Message[] browse() { public Message[] browse() {
ArrayList l = new ArrayList(); List<Message> l = new ArrayList<Message>();
try { try {
doPageIn(true); doPageIn(true);
} catch (Exception e) { } catch (Exception e) {
log.error("caught an exception browsing " + this, e); log.error("caught an exception browsing " + this, e);
} }
synchronized (pagedInMessages) { synchronized (pagedInMessages) {
for (Iterator i = pagedInMessages.iterator(); i.hasNext();) { for (Iterator<MessageReference> i = pagedInMessages.iterator(); i.hasNext();) {
MessageReference r = (MessageReference)i.next(); MessageReference r = i.next();
r.incrementReferenceCount(); r.incrementReferenceCount();
try { try {
Message m = r.getMessage(); Message m = r.getMessage();
@ -698,7 +696,7 @@ public class Queue implements Destination, Task {
} }
} }
return (Message[])l.toArray(new Message[l.size()]); return l.toArray(new Message[l.size()]);
} }
public Message getMessage(String messageId) { public Message getMessage(String messageId) {
@ -737,7 +735,7 @@ public class Queue implements Destination, Task {
synchronized (pagedInMessages) { synchronized (pagedInMessages) {
ConnectionContext c = createConnectionContext(); ConnectionContext c = createConnectionContext();
for (Iterator i = pagedInMessages.iterator(); i.hasNext();) { for (Iterator<MessageReference> i = pagedInMessages.iterator(); i.hasNext();) {
try { try {
QueueMessageReference r = (QueueMessageReference)i.next(); QueueMessageReference r = (QueueMessageReference)i.next();
@ -798,7 +796,7 @@ public class Queue implements Destination, Task {
int counter = 0; int counter = 0;
synchronized (pagedInMessages) { synchronized (pagedInMessages) {
ConnectionContext c = createConnectionContext(); ConnectionContext c = createConnectionContext();
for (Iterator i = pagedInMessages.iterator(); i.hasNext();) { for (Iterator<MessageReference> i = pagedInMessages.iterator(); i.hasNext();) {
IndirectMessageReference r = (IndirectMessageReference)i.next(); IndirectMessageReference r = (IndirectMessageReference)i.next();
if (filter.evaluate(c, r)) { if (filter.evaluate(c, r)) {
removeMessage(c, r); removeMessage(c, r);
@ -848,8 +846,8 @@ public class Queue implements Destination, Task {
pageInMessages(); pageInMessages();
int counter = 0; int counter = 0;
synchronized (pagedInMessages) { synchronized (pagedInMessages) {
for (Iterator i = pagedInMessages.iterator(); i.hasNext();) { for (Iterator<MessageReference> i = pagedInMessages.iterator(); i.hasNext();) {
MessageReference r = (MessageReference)i.next(); MessageReference r = i.next();
if (filter.evaluate(context, r)) { if (filter.evaluate(context, r)) {
r.incrementReferenceCount(); r.incrementReferenceCount();
try { try {
@ -899,7 +897,7 @@ public class Queue implements Destination, Task {
pageInMessages(); pageInMessages();
int counter = 0; int counter = 0;
synchronized (pagedInMessages) { synchronized (pagedInMessages) {
for (Iterator i = pagedInMessages.iterator(); i.hasNext();) { for (Iterator<MessageReference> i = pagedInMessages.iterator(); i.hasNext();) {
IndirectMessageReference r = (IndirectMessageReference)i.next(); IndirectMessageReference r = (IndirectMessageReference)i.next();
if (filter.evaluate(context, r)) { if (filter.evaluate(context, r)) {
// We should only move messages that can be locked. // We should only move messages that can be locked.
@ -995,20 +993,20 @@ public class Queue implements Destination, Task {
pageInMessages(false); pageInMessages(false);
} }
private List doPageIn() throws Exception { private List<MessageReference> doPageIn() throws Exception {
return doPageIn(true); return doPageIn(true);
} }
private List doPageIn(boolean force) throws Exception { private List<MessageReference> doPageIn(boolean force) throws Exception {
final int toPageIn = maximumPagedInMessages - pagedInMessages.size(); final int toPageIn = maximumPagedInMessages - pagedInMessages.size();
List result = null; List<MessageReference> result = null;
if ((force || !consumers.isEmpty()) && toPageIn > 0) { if ((force || !consumers.isEmpty()) && toPageIn > 0) {
messages.setMaxBatchSize(toPageIn); messages.setMaxBatchSize(toPageIn);
try { try {
dispatchValve.increment(); dispatchValve.increment();
int count = 0; int count = 0;
result = new ArrayList(toPageIn); result = new ArrayList<MessageReference>(toPageIn);
synchronized (messages) { synchronized (messages) {
try { try {
@ -1040,12 +1038,12 @@ public class Queue implements Destination, Task {
return result; return result;
} }
private void doDispatch(List list) throws Exception { private void doDispatch(List<MessageReference> list) throws Exception {
if (list != null && !list.isEmpty()) { if (list != null && !list.isEmpty()) {
try { try {
dispatchValve.increment(); dispatchValve.increment();
for (int i = 0; i < list.size(); i++) { for (int i = 0; i < list.size(); i++) {
MessageReference node = (MessageReference)list.get(i); MessageReference node = list.get(i);
queueMsgConext.setDestination(destination); queueMsgConext.setDestination(destination);
queueMsgConext.setMessageReference(node); queueMsgConext.setMessageReference(node);
dispatchPolicy.dispatch(node, queueMsgConext, consumers); dispatchPolicy.dispatch(node, queueMsgConext, consumers);

View File

@ -53,12 +53,13 @@ public class QueueRegion extends AbstractRegion {
} }
} }
protected Set getInactiveDestinations() { protected Set<ActiveMQDestination> getInactiveDestinations() {
Set inactiveDestinations = super.getInactiveDestinations(); Set<ActiveMQDestination> inactiveDestinations = super.getInactiveDestinations();
for (Iterator iter = inactiveDestinations.iterator(); iter.hasNext();) { for (Iterator<ActiveMQDestination> iter = inactiveDestinations.iterator(); iter.hasNext();) {
ActiveMQDestination dest = (ActiveMQDestination)iter.next(); ActiveMQDestination dest = iter.next();
if (!dest.isQueue()) if (!dest.isQueue()) {
iter.remove(); iter.remove();
}
} }
return inactiveDestinations; return inactiveDestinations;
} }

View File

@ -72,8 +72,9 @@ public class QueueSubscription extends PrefetchSubscription implements LockOwner
protected boolean canDispatch(MessageReference n) throws IOException { protected boolean canDispatch(MessageReference n) throws IOException {
QueueMessageReference node = (QueueMessageReference)n; QueueMessageReference node = (QueueMessageReference)n;
if (node.isAcked()) if (node.isAcked()) {
return false; return false;
}
// Keep message groups together. // Keep message groups together.
String groupId = node.getGroupID(); String groupId = node.getGroupID();
int sequence = node.getGroupSequence(); int sequence = node.getGroupSequence();

View File

@ -69,7 +69,7 @@ public interface Region extends Service {
* *
* @return a copy of the regions currently active at the time of the call with the key the destination and the value the Destination. * @return a copy of the regions currently active at the time of the call with the key the destination and the value the Destination.
*/ */
Map getDestinationMap(); Map<ActiveMQDestination, Destination> getDestinationMap();
/** /**

View File

@ -76,6 +76,10 @@ public class RegionBroker implements Broker {
private static final Log LOG = LogFactory.getLog(RegionBroker.class); private static final Log LOG = LogFactory.getLog(RegionBroker.class);
private static final IdGenerator BROKER_ID_GENERATOR = new IdGenerator(); private static final IdGenerator BROKER_ID_GENERATOR = new IdGenerator();
protected final DestinationStatistics destinationStatistics = new DestinationStatistics();
protected DestinationFactory destinationFactory;
protected final Map<ConnectionId, ConnectionState> connectionStates = Collections.synchronizedMap(new HashMap<ConnectionId, ConnectionState>());
private final Region queueRegion; private final Region queueRegion;
private final Region topicRegion; private final Region topicRegion;
private final Region tempQueueRegion; private final Region tempQueueRegion;
@ -84,23 +88,16 @@ public class RegionBroker implements Broker {
private boolean started; private boolean started;
private boolean keepDurableSubsActive; private boolean keepDurableSubsActive;
protected final DestinationStatistics destinationStatistics = new DestinationStatistics(); private final CopyOnWriteArrayList<Connection> connections = new CopyOnWriteArrayList<Connection>();
private final Map<ActiveMQDestination, Destination> destinations = new ConcurrentHashMap<ActiveMQDestination, Destination>();
private final CopyOnWriteArrayList connections = new CopyOnWriteArrayList(); private final CopyOnWriteArrayList<BrokerInfo> brokerInfos = new CopyOnWriteArrayList<BrokerInfo>();
private final Map destinations = new ConcurrentHashMap();
private final CopyOnWriteArrayList brokerInfos = new CopyOnWriteArrayList();
private final LongSequenceGenerator sequenceGenerator = new LongSequenceGenerator(); private final LongSequenceGenerator sequenceGenerator = new LongSequenceGenerator();
private BrokerId brokerId; private BrokerId brokerId;
private String brokerName; private String brokerName;
private Map<String, ConnectionContext> clientIdSet = new HashMap<String, ConnectionContext>(); // we private Map<String, ConnectionContext> clientIdSet = new HashMap<String, ConnectionContext>();
// will
// synchronize
// access
private final DestinationInterceptor destinationInterceptor; private final DestinationInterceptor destinationInterceptor;
private ConnectionContext adminConnectionContext; private ConnectionContext adminConnectionContext;
protected DestinationFactory destinationFactory;
protected final Map<ConnectionId, ConnectionState> connectionStates = Collections.synchronizedMap(new HashMap<ConnectionId, ConnectionState>());
public RegionBroker(BrokerService brokerService, TaskRunnerFactory taskRunnerFactory, UsageManager memoryManager, DestinationFactory destinationFactory, public RegionBroker(BrokerService brokerService, TaskRunnerFactory taskRunnerFactory, UsageManager memoryManager, DestinationFactory destinationFactory,
DestinationInterceptor destinationInterceptor) throws IOException { DestinationInterceptor destinationInterceptor) throws IOException {
@ -243,7 +240,7 @@ public class RegionBroker implements Broker {
} }
public Connection[] getClients() throws Exception { public Connection[] getClients() throws Exception {
ArrayList l = new ArrayList(connections); ArrayList<Connection> l = new ArrayList<Connection>(connections);
Connection rc[] = new Connection[l.size()]; Connection rc[] = new Connection[l.size()];
l.toArray(rc); l.toArray(rc);
return rc; return rc;
@ -253,9 +250,10 @@ public class RegionBroker implements Broker {
Destination answer; Destination answer;
answer = (Destination)destinations.get(destination); answer = destinations.get(destination);
if (answer != null) if (answer != null) {
return answer; return answer;
}
switch (destination.getDestinationType()) { switch (destination.getDestinationType()) {
case ActiveMQDestination.QUEUE_TYPE: case ActiveMQDestination.QUEUE_TYPE:
@ -313,9 +311,9 @@ public class RegionBroker implements Broker {
} }
public ActiveMQDestination[] getDestinations() throws Exception { public ActiveMQDestination[] getDestinations() throws Exception {
ArrayList l; ArrayList<Destination> l;
l = new ArrayList(destinations.values()); l = new ArrayList<Destination>(destinations.values());
ActiveMQDestination rc[] = new ActiveMQDestination[l.size()]; ActiveMQDestination rc[] = new ActiveMQDestination[l.size()];
l.toArray(rc); l.toArray(rc);
@ -530,7 +528,7 @@ public class RegionBroker implements Broker {
public synchronized BrokerInfo[] getPeerBrokerInfos() { public synchronized BrokerInfo[] getPeerBrokerInfos() {
BrokerInfo[] result = new BrokerInfo[brokerInfos.size()]; BrokerInfo[] result = new BrokerInfo[brokerInfos.size()];
result = (BrokerInfo[])brokerInfos.toArray(result); result = brokerInfos.toArray(result);
return result; return result;
} }

View File

@ -73,8 +73,9 @@ public class TempQueueRegion extends AbstractRegion {
// Force a timeout value so that we don't get an error that // Force a timeout value so that we don't get an error that
// there is still an active sub. Temp destination may be removed // there is still an active sub. Temp destination may be removed
// while a network sub is still active which is valid. // while a network sub is still active which is valid.
if (timeout == 0) if (timeout == 0) {
timeout = 1; timeout = 1;
}
super.removeDestination(context, destination, timeout); super.removeDestination(context, destination, timeout);
} }

View File

@ -75,8 +75,9 @@ public class TempTopicRegion extends AbstractRegion {
// Force a timeout value so that we don't get an error that // Force a timeout value so that we don't get an error that
// there is still an active sub. Temp destination may be removed // there is still an active sub. Temp destination may be removed
// while a network sub is still active which is valid. // while a network sub is still active which is valid.
if (timeout == 0) if (timeout == 0) {
timeout = 1; timeout = 1;
}
super.removeDestination(context, destination, timeout); super.removeDestination(context, destination, timeout);
} }

View File

@ -18,6 +18,7 @@ package org.apache.activemq.broker.region;
import java.io.IOException; import java.io.IOException;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
@ -62,7 +63,7 @@ import org.apache.commons.logging.LogFactory;
public class Topic implements Destination { public class Topic implements Destination {
private static final Log LOG = LogFactory.getLog(Topic.class); private static final Log LOG = LogFactory.getLog(Topic.class);
protected final ActiveMQDestination destination; protected final ActiveMQDestination destination;
protected final CopyOnWriteArrayList consumers = new CopyOnWriteArrayList(); protected final CopyOnWriteArrayList<Subscription> consumers = new CopyOnWriteArrayList<Subscription>();
protected final Valve dispatchValve = new Valve(true); protected final Valve dispatchValve = new Valve(true);
// this could be NULL! (If an advisory) // this could be NULL! (If an advisory)
protected final TopicMessageStore store; protected final TopicMessageStore store;
@ -73,14 +74,32 @@ public class Topic implements Destination {
private SubscriptionRecoveryPolicy subscriptionRecoveryPolicy = new FixedSizedSubscriptionRecoveryPolicy(); private SubscriptionRecoveryPolicy subscriptionRecoveryPolicy = new FixedSizedSubscriptionRecoveryPolicy();
private boolean sendAdvisoryIfNoConsumers; private boolean sendAdvisoryIfNoConsumers;
private DeadLetterStrategy deadLetterStrategy = new SharedDeadLetterStrategy(); private DeadLetterStrategy deadLetterStrategy = new SharedDeadLetterStrategy();
private final ConcurrentHashMap durableSubcribers = new ConcurrentHashMap(); private final ConcurrentHashMap<SubscriptionKey, DurableTopicSubscription> durableSubcribers = new ConcurrentHashMap<SubscriptionKey, DurableTopicSubscription>();
final Broker broker;
private final LinkedList<Runnable> messagesWaitingForSpace = new LinkedList<Runnable>();
private final Runnable sendMessagesWaitingForSpaceTask = new Runnable() {
public void run() {
// We may need to do this in async thread since this is run for
// within a synchronization
// that the UsageManager is holding.
synchronized (messagesWaitingForSpace) {
while (!usageManager.isFull() && !messagesWaitingForSpace.isEmpty()) {
Runnable op = messagesWaitingForSpace.removeFirst();
op.run();
}
}
};
};
private final Broker broker;
public Topic(Broker broker, ActiveMQDestination destination, TopicMessageStore store, UsageManager memoryManager, DestinationStatistics parentStats, public Topic(Broker broker, ActiveMQDestination destination, TopicMessageStore store, UsageManager memoryManager, DestinationStatistics parentStats,
TaskRunnerFactory taskFactory) { TaskRunnerFactory taskFactory) {
this.broker = broker; this.broker = broker;
this.destination = destination; this.destination = destination;
this.store = store; // this could be NULL! (If an advsiory) this.store = store; // this could be NULL! (If an advisory)
this.usageManager = new UsageManager(memoryManager, destination.toString()); this.usageManager = new UsageManager(memoryManager, destination.toString());
this.usageManager.setUsagePortion(1.0f); this.usageManager.setUsagePortion(1.0f);
@ -168,8 +187,9 @@ public class Topic implements Destination {
consumers.add(subscription); consumers.add(subscription);
} }
if (store == null) if (store == null) {
return; return;
}
// Recover the durable subscription. // Recover the durable subscription.
String clientId = subscription.getClientId(); String clientId = subscription.getClientId();
@ -228,9 +248,6 @@ public class Topic implements Destination {
throw new RuntimeException("Should not be called."); throw new RuntimeException("Should not be called.");
} }
public void finished() {
}
public boolean hasSpace() { public boolean hasSpace() {
return true; return true;
} }
@ -255,24 +272,6 @@ public class Topic implements Destination {
} }
} }
private final LinkedList<Runnable> messagesWaitingForSpace = new LinkedList<Runnable>();
private final Runnable sendMessagesWaitingForSpaceTask = new Runnable() {
public void run() {
// We may need to do this in async thread since this is run for
// within a synchronization
// that the UsageManager is holding.
synchronized (messagesWaitingForSpace) {
while (!usageManager.isFull() && !messagesWaitingForSpace.isEmpty()) {
Runnable op = messagesWaitingForSpace.removeFirst();
op.run();
}
}
};
};
public void send(final ProducerBrokerExchange producerExchange, final Message message) throws Exception { public void send(final ProducerBrokerExchange producerExchange, final Message message) throws Exception {
final ConnectionContext context = producerExchange.getConnectionContext(); final ConnectionContext context = producerExchange.getConnectionContext();
@ -342,8 +341,9 @@ public class Topic implements Destination {
// control at the broker // control at the broker
// by blocking this thread until there is space available. // by blocking this thread until there is space available.
while (!usageManager.waitForSpace(1000)) { while (!usageManager.waitForSpace(1000)) {
if (context.getStopping().get()) if (context.getStopping().get()) {
throw new IOException("Connection closed, send aborted."); throw new IOException("Connection closed, send aborted.");
}
} }
// The usage manager could have delayed us by the time // The usage manager could have delayed us by the time
@ -364,8 +364,9 @@ public class Topic implements Destination {
final ConnectionContext context = producerExchange.getConnectionContext(); final ConnectionContext context = producerExchange.getConnectionContext();
message.setRegionDestination(this); message.setRegionDestination(this);
if (store != null && message.isPersistent() && !canOptimizeOutPersistence()) if (store != null && message.isPersistent() && !canOptimizeOutPersistence()) {
store.addMessage(context, message); store.addMessage(context, message);
}
message.incrementReferenceCount(); message.incrementReferenceCount();
try { try {
@ -440,7 +441,7 @@ public class Topic implements Destination {
} }
public Message[] browse() { public Message[] browse() {
final Set result = new CopyOnWriteArraySet(); final Set<Message> result = new CopyOnWriteArraySet<Message>();
try { try {
if (store != null) { if (store != null) {
store.recover(new MessageRecoveryListener() { store.recover(new MessageRecoveryListener() {
@ -453,9 +454,6 @@ public class Topic implements Destination {
return true; return true;
} }
public void finished() {
}
public boolean hasSpace() { public boolean hasSpace() {
return true; return true;
} }
@ -470,7 +468,7 @@ public class Topic implements Destination {
} catch (Throwable e) { } catch (Throwable e) {
LOG.warn("Failed to browse Topic: " + getActiveMQDestination().getPhysicalName(), e); LOG.warn("Failed to browse Topic: " + getActiveMQDestination().getPhysicalName(), e);
} }
return (Message[])result.toArray(new Message[result.size()]); return result.toArray(new Message[result.size()]);
} }
// Properties // Properties
@ -576,10 +574,12 @@ public class Topic implements Destination {
// filled when the message is first sent, // filled when the message is first sent,
// it is only populated if the message is routed to another // it is only populated if the message is routed to another
// destination like the DLQ // destination like the DLQ
if (message.getOriginalDestination() != null) if (message.getOriginalDestination() != null) {
message.setOriginalDestination(message.getDestination()); message.setOriginalDestination(message.getDestination());
if (message.getOriginalTransactionId() != null) }
if (message.getOriginalTransactionId() != null) {
message.setOriginalTransactionId(message.getTransactionId()); message.setOriginalTransactionId(message.getTransactionId());
}
ActiveMQTopic advisoryTopic = AdvisorySupport.getNoTopicConsumersAdvisoryTopic(destination); ActiveMQTopic advisoryTopic = AdvisorySupport.getNoTopicConsumersAdvisoryTopic(destination);
message.setDestination(advisoryTopic); message.setDestination(advisoryTopic);

View File

@ -48,7 +48,7 @@ import org.apache.commons.logging.LogFactory;
*/ */
public class TopicRegion extends AbstractRegion { public class TopicRegion extends AbstractRegion {
private static final Log LOG = LogFactory.getLog(TopicRegion.class); private static final Log LOG = LogFactory.getLog(TopicRegion.class);
protected final ConcurrentHashMap durableSubscriptions = new ConcurrentHashMap(); protected final ConcurrentHashMap<SubscriptionKey, DurableTopicSubscription> durableSubscriptions = new ConcurrentHashMap<SubscriptionKey, DurableTopicSubscription>();
private final LongSequenceGenerator recoveredDurableSubIdGenerator = new LongSequenceGenerator(); private final LongSequenceGenerator recoveredDurableSubIdGenerator = new LongSequenceGenerator();
private final SessionId recoveredDurableSubSessionId = new SessionId(new ConnectionId("OFFLINE"), recoveredDurableSubIdGenerator.getNextSequenceId()); private final SessionId recoveredDurableSubSessionId = new SessionId(new ConnectionId("OFFLINE"), recoveredDurableSubIdGenerator.getNextSequenceId());
private boolean keepDurableSubsActive; private boolean keepDurableSubsActive;
@ -69,7 +69,7 @@ public class TopicRegion extends AbstractRegion {
String clientId = context.getClientId(); String clientId = context.getClientId();
String subscriptionName = info.getSubscriptionName(); String subscriptionName = info.getSubscriptionName();
SubscriptionKey key = new SubscriptionKey(clientId, subscriptionName); SubscriptionKey key = new SubscriptionKey(clientId, subscriptionName);
DurableTopicSubscription sub = (DurableTopicSubscription)durableSubscriptions.get(key); DurableTopicSubscription sub = durableSubscriptions.get(key);
if (sub != null) { if (sub != null) {
if (sub.isActive()) { if (sub.isActive()) {
throw new JMSException("Durable consumer is in use for client: " + clientId + " and subscriptionName: " + subscriptionName); throw new JMSException("Durable consumer is in use for client: " + clientId + " and subscriptionName: " + subscriptionName);
@ -78,22 +78,23 @@ public class TopicRegion extends AbstractRegion {
if (hasDurableSubChanged(info, sub.getConsumerInfo())) { if (hasDurableSubChanged(info, sub.getConsumerInfo())) {
// Remove the consumer first then add it. // Remove the consumer first then add it.
durableSubscriptions.remove(key); durableSubscriptions.remove(key);
for (Iterator iter = destinations.values().iterator(); iter.hasNext();) { for (Iterator<Destination> iter = destinations.values().iterator(); iter.hasNext();) {
Topic topic = (Topic)iter.next(); Topic topic = (Topic)iter.next();
topic.deleteSubscription(context, key); topic.deleteSubscription(context, key);
} }
super.removeConsumer(context, sub.getConsumerInfo()); super.removeConsumer(context, sub.getConsumerInfo());
super.addConsumer(context, info); super.addConsumer(context, info);
sub = (DurableTopicSubscription)durableSubscriptions.get(key); sub = durableSubscriptions.get(key);
} else { } else {
// Change the consumer id key of the durable sub. // Change the consumer id key of the durable sub.
if (sub.getConsumerInfo().getConsumerId() != null) if (sub.getConsumerInfo().getConsumerId() != null) {
subscriptions.remove(sub.getConsumerInfo().getConsumerId()); subscriptions.remove(sub.getConsumerInfo().getConsumerId());
}
subscriptions.put(info.getConsumerId(), sub); subscriptions.put(info.getConsumerId(), sub);
} }
} else { } else {
super.addConsumer(context, info); super.addConsumer(context, info);
sub = (DurableTopicSubscription)durableSubscriptions.get(key); sub = durableSubscriptions.get(key);
if (sub == null) { if (sub == null) {
throw new JMSException("Cannot use the same consumerId: " + info.getConsumerId() + " for two different durable subscriptions clientID: " + key.getClientId() throw new JMSException("Cannot use the same consumerId: " + info.getConsumerId() + " for two different durable subscriptions clientID: " + key.getClientId()
+ " subscriberName: " + key.getSubscriptionName()); + " subscriberName: " + key.getSubscriptionName());
@ -110,7 +111,7 @@ public class TopicRegion extends AbstractRegion {
if (info.isDurable()) { if (info.isDurable()) {
SubscriptionKey key = new SubscriptionKey(context.getClientId(), info.getSubscriptionName()); SubscriptionKey key = new SubscriptionKey(context.getClientId(), info.getSubscriptionName());
DurableTopicSubscription sub = (DurableTopicSubscription)durableSubscriptions.get(key); DurableTopicSubscription sub = durableSubscriptions.get(key);
if (sub != null) { if (sub != null) {
sub.deactivate(keepDurableSubsActive); sub.deactivate(keepDurableSubsActive);
} }
@ -121,17 +122,17 @@ public class TopicRegion extends AbstractRegion {
} }
public void removeSubscription(ConnectionContext context, RemoveSubscriptionInfo info) throws Exception { public void removeSubscription(ConnectionContext context, RemoveSubscriptionInfo info) throws Exception {
SubscriptionKey key = new SubscriptionKey(info.getClientId(), info.getSubcriptionName()); SubscriptionKey key = new SubscriptionKey(info.getClientId(), info.getSubscriptionName());
DurableTopicSubscription sub = (DurableTopicSubscription)durableSubscriptions.get(key); DurableTopicSubscription sub = durableSubscriptions.get(key);
if (sub == null) { if (sub == null) {
throw new InvalidDestinationException("No durable subscription exists for: " + info.getSubcriptionName()); throw new InvalidDestinationException("No durable subscription exists for: " + info.getSubscriptionName());
} }
if (sub.isActive()) { if (sub.isActive()) {
throw new JMSException("Durable consumer is in use"); throw new JMSException("Durable consumer is in use");
} }
durableSubscriptions.remove(key); durableSubscriptions.remove(key);
for (Iterator iter = destinations.values().iterator(); iter.hasNext();) { for (Iterator<Destination> iter = destinations.values().iterator(); iter.hasNext();) {
Topic topic = (Topic)iter.next(); Topic topic = (Topic)iter.next();
topic.deleteSubscription(context, key); topic.deleteSubscription(context, key);
} }
@ -146,7 +147,7 @@ public class TopicRegion extends AbstractRegion {
protected List<Subscription> addSubscriptionsForDestination(ConnectionContext context, Destination dest) throws Exception { protected List<Subscription> addSubscriptionsForDestination(ConnectionContext context, Destination dest) throws Exception {
List<Subscription> rc = super.addSubscriptionsForDestination(context, dest); List<Subscription> rc = super.addSubscriptionsForDestination(context, dest);
HashSet<Subscription> dupChecker = new HashSet<Subscription>(rc); Set<Subscription> dupChecker = new HashSet<Subscription>(rc);
TopicMessageStore store = (TopicMessageStore)dest.getMessageStore(); TopicMessageStore store = (TopicMessageStore)dest.getMessageStore();
// Eagerly recover the durable subscriptions // Eagerly recover the durable subscriptions
@ -160,7 +161,7 @@ public class TopicRegion extends AbstractRegion {
// A single durable sub may be subscribing to multiple topics. // A single durable sub may be subscribing to multiple topics.
// so it might exist already. // so it might exist already.
DurableTopicSubscription sub = (DurableTopicSubscription)durableSubscriptions.get(key); DurableTopicSubscription sub = durableSubscriptions.get(key);
ConsumerInfo consumerInfo = createInactiveConsumerInfo(info); ConsumerInfo consumerInfo = createInactiveConsumerInfo(info);
if (sub == null) { if (sub == null) {
ConnectionContext c = new ConnectionContext(); ConnectionContext c = new ConnectionContext();
@ -182,8 +183,8 @@ public class TopicRegion extends AbstractRegion {
// Now perhaps there other durable subscriptions (via wild card) // Now perhaps there other durable subscriptions (via wild card)
// that would match this destination.. // that would match this destination..
durableSubscriptions.values(); durableSubscriptions.values();
for (Iterator iterator = durableSubscriptions.values().iterator(); iterator.hasNext();) { for (Iterator<DurableTopicSubscription> iterator = durableSubscriptions.values().iterator(); iterator.hasNext();) {
DurableTopicSubscription sub = (DurableTopicSubscription)iterator.next(); DurableTopicSubscription sub = iterator.next();
// Skip over subscriptions that we allready added.. // Skip over subscriptions that we allready added..
if (dupChecker.contains(sub)) { if (dupChecker.contains(sub)) {
continue; continue;
@ -227,7 +228,7 @@ public class TopicRegion extends AbstractRegion {
throw new JMSException("Cannot create a durable subscription for an advisory Topic"); throw new JMSException("Cannot create a durable subscription for an advisory Topic");
} }
SubscriptionKey key = new SubscriptionKey(context.getClientId(), info.getSubscriptionName()); SubscriptionKey key = new SubscriptionKey(context.getClientId(), info.getSubscriptionName());
DurableTopicSubscription sub = (DurableTopicSubscription)durableSubscriptions.get(key); DurableTopicSubscription sub = durableSubscriptions.get(key);
if (sub == null) { if (sub == null) {
sub = new DurableTopicSubscription(broker, memoryManager, context, info, keepDurableSubsActive); sub = new DurableTopicSubscription(broker, memoryManager, context, info, keepDurableSubsActive);
ActiveMQDestination destination = info.getDestination(); ActiveMQDestination destination = info.getDestination();
@ -266,10 +267,12 @@ public class TopicRegion extends AbstractRegion {
/** /**
*/ */
private boolean hasDurableSubChanged(ConsumerInfo info1, ConsumerInfo info2) { private boolean hasDurableSubChanged(ConsumerInfo info1, ConsumerInfo info2) {
if (info1.getSelector() != null ^ info2.getSelector() != null) if (info1.getSelector() != null ^ info2.getSelector() != null) {
return true; return true;
if (info1.getSelector() != null && !info1.getSelector().equals(info2.getSelector())) }
if (info1.getSelector() != null && !info1.getSelector().equals(info2.getSelector())) {
return true; return true;
}
return !info1.getDestination().equals(info2.getDestination()); return !info1.getDestination().equals(info2.getDestination());
} }
@ -277,8 +280,9 @@ public class TopicRegion extends AbstractRegion {
Set inactiveDestinations = super.getInactiveDestinations(); Set inactiveDestinations = super.getInactiveDestinations();
for (Iterator iter = inactiveDestinations.iterator(); iter.hasNext();) { for (Iterator iter = inactiveDestinations.iterator(); iter.hasNext();) {
ActiveMQDestination dest = (ActiveMQDestination)iter.next(); ActiveMQDestination dest = (ActiveMQDestination)iter.next();
if (!dest.isTopic()) if (!dest.isTopic()) {
iter.remove(); iter.remove();
}
} }
return inactiveDestinations; return inactiveDestinations;
} }

View File

@ -45,7 +45,7 @@ public class StoreDurableSubscriberCursor extends AbstractPendingMessageCursor {
private int pendingCount; private int pendingCount;
private String clientId; private String clientId;
private String subscriberName; private String subscriberName;
private Map topics = new HashMap(); private Map<Destination, TopicStorePrefetch> topics = new HashMap<Destination, TopicStorePrefetch>();
private LinkedList<PendingMessageCursor> storePrefetches = new LinkedList<PendingMessageCursor>(); private LinkedList<PendingMessageCursor> storePrefetches = new LinkedList<PendingMessageCursor>();
private boolean started; private boolean started;
private PendingMessageCursor nonPersistent; private PendingMessageCursor nonPersistent;
@ -129,7 +129,7 @@ public class StoreDurableSubscriberCursor extends AbstractPendingMessageCursor {
public boolean isEmpty(Destination destination) { public boolean isEmpty(Destination destination) {
boolean result = true; boolean result = true;
TopicStorePrefetch tsp = (TopicStorePrefetch)topics.get(destination); TopicStorePrefetch tsp = topics.get(destination);
if (tsp != null) { if (tsp != null) {
result = tsp.size() <= 0; result = tsp.size() <= 0;
} }
@ -158,7 +158,7 @@ public class StoreDurableSubscriberCursor extends AbstractPendingMessageCursor {
} }
if (msg.isPersistent()) { if (msg.isPersistent()) {
Destination dest = msg.getRegionDestination(); Destination dest = msg.getRegionDestination();
TopicStorePrefetch tsp = (TopicStorePrefetch)topics.get(dest); TopicStorePrefetch tsp = topics.get(dest);
if (tsp != null) { if (tsp != null) {
tsp.addMessageLast(node); tsp.addMessageLast(node);
} }
@ -212,14 +212,14 @@ public class StoreDurableSubscriberCursor extends AbstractPendingMessageCursor {
} }
public synchronized void reset() { public synchronized void reset() {
for (Iterator i = storePrefetches.iterator(); i.hasNext();) { for (Iterator<PendingMessageCursor> i = storePrefetches.iterator(); i.hasNext();) {
AbstractPendingMessageCursor tsp = (AbstractPendingMessageCursor)i.next(); AbstractPendingMessageCursor tsp = (AbstractPendingMessageCursor)i.next();
tsp.reset(); tsp.reset();
} }
} }
public synchronized void release() { public synchronized void release() {
for (Iterator i = storePrefetches.iterator(); i.hasNext();) { for (Iterator<PendingMessageCursor> i = storePrefetches.iterator(); i.hasNext();) {
AbstractPendingMessageCursor tsp = (AbstractPendingMessageCursor)i.next(); AbstractPendingMessageCursor tsp = (AbstractPendingMessageCursor)i.next();
tsp.release(); tsp.release();
} }
@ -230,7 +230,7 @@ public class StoreDurableSubscriberCursor extends AbstractPendingMessageCursor {
} }
public synchronized void setMaxBatchSize(int maxBatchSize) { public synchronized void setMaxBatchSize(int maxBatchSize) {
for (Iterator i = storePrefetches.iterator(); i.hasNext();) { for (Iterator<PendingMessageCursor> i = storePrefetches.iterator(); i.hasNext();) {
AbstractPendingMessageCursor tsp = (AbstractPendingMessageCursor)i.next(); AbstractPendingMessageCursor tsp = (AbstractPendingMessageCursor)i.next();
tsp.setMaxBatchSize(maxBatchSize); tsp.setMaxBatchSize(maxBatchSize);
} }
@ -238,16 +238,16 @@ public class StoreDurableSubscriberCursor extends AbstractPendingMessageCursor {
} }
public synchronized void gc() { public synchronized void gc() {
for (Iterator i = storePrefetches.iterator(); i.hasNext();) { for (Iterator<PendingMessageCursor> i = storePrefetches.iterator(); i.hasNext();) {
PendingMessageCursor tsp = (PendingMessageCursor)i.next(); PendingMessageCursor tsp = i.next();
tsp.gc(); tsp.gc();
} }
} }
public synchronized void setUsageManager(UsageManager usageManager) { public synchronized void setUsageManager(UsageManager usageManager) {
super.setUsageManager(usageManager); super.setUsageManager(usageManager);
for (Iterator i = storePrefetches.iterator(); i.hasNext();) { for (Iterator<PendingMessageCursor> i = storePrefetches.iterator(); i.hasNext();) {
PendingMessageCursor tsp = (PendingMessageCursor)i.next(); PendingMessageCursor tsp = i.next();
tsp.setUsageManager(usageManager); tsp.setUsageManager(usageManager);
} }
} }
@ -255,7 +255,7 @@ public class StoreDurableSubscriberCursor extends AbstractPendingMessageCursor {
protected synchronized PendingMessageCursor getNextCursor() throws Exception { protected synchronized PendingMessageCursor getNextCursor() throws Exception {
if (currentCursor == null || currentCursor.isEmpty()) { if (currentCursor == null || currentCursor.isEmpty()) {
currentCursor = null; currentCursor = null;
for (Iterator i = storePrefetches.iterator(); i.hasNext();) { for (Iterator<PendingMessageCursor> i = storePrefetches.iterator(); i.hasNext();) {
AbstractPendingMessageCursor tsp = (AbstractPendingMessageCursor)i.next(); AbstractPendingMessageCursor tsp = (AbstractPendingMessageCursor)i.next();
if (tsp.hasNext()) { if (tsp.hasNext()) {
currentCursor = tsp; currentCursor = tsp;

View File

@ -102,8 +102,9 @@ public class MessageGroupHashBucket implements MessageGroupMap {
protected int getBucketNumber(String groupId) { protected int getBucketNumber(String groupId) {
int bucket = groupId.hashCode() % bucketCount; int bucket = groupId.hashCode() % bucketCount;
// bucket could be negative // bucket could be negative
if (bucket < 0) if (bucket < 0) {
bucket *= -1; bucket *= -1;
}
return bucket; return bucket;
} }
} }

View File

@ -47,8 +47,9 @@ public class FixedCountSubscriptionRecoveryPolicy implements SubscriptionRecover
public synchronized boolean add(ConnectionContext context, MessageReference node) throws Exception { public synchronized boolean add(ConnectionContext context, MessageReference node) throws Exception {
messages[tail++] = node; messages[tail++] = node;
if (tail >= messages.length) if (tail >= messages.length) {
tail = 0; tail = 0;
}
return true; return true;
} }
@ -56,18 +57,21 @@ public class FixedCountSubscriptionRecoveryPolicy implements SubscriptionRecover
// Re-dispatch the last message seen. // Re-dispatch the last message seen.
int t = tail; int t = tail;
// The buffer may not have rolled over yet..., start from the front // The buffer may not have rolled over yet..., start from the front
if (messages[t] == null) if (messages[t] == null) {
t = 0; t = 0;
}
// Well the buffer is really empty then. // Well the buffer is really empty then.
if (messages[t] == null) if (messages[t] == null) {
return; return;
}
// Keep dispatching until t hit's tail again. // Keep dispatching until t hit's tail again.
do { do {
MessageReference node = messages[t]; MessageReference node = messages[t];
sub.addRecoveredMessage(context, node); sub.addRecoveredMessage(context, node);
t++; t++;
if (t >= messages.length) if (t >= messages.length) {
t = 0; t = 0;
}
} while (t != tail); } while (t != tail);
} }
@ -92,11 +96,12 @@ public class FixedCountSubscriptionRecoveryPolicy implements SubscriptionRecover
} }
public synchronized Message[] browse(ActiveMQDestination destination) throws Exception { public synchronized Message[] browse(ActiveMQDestination destination) throws Exception {
List result = new ArrayList(); List<Message> result = new ArrayList<Message>();
DestinationFilter filter = DestinationFilter.parseFilter(destination); DestinationFilter filter = DestinationFilter.parseFilter(destination);
int t = tail; int t = tail;
if (messages[t] == null) if (messages[t] == null) {
t = 0; t = 0;
}
if (messages[t] != null) { if (messages[t] != null) {
do { do {
MessageReference ref = messages[t]; MessageReference ref = messages[t];
@ -105,11 +110,12 @@ public class FixedCountSubscriptionRecoveryPolicy implements SubscriptionRecover
result.add(message); result.add(message);
} }
t++; t++;
if (t >= messages.length) if (t >= messages.length) {
t = 0; t = 0;
}
} while (t != tail); } while (t != tail);
} }
return (Message[])result.toArray(new Message[result.size()]); return result.toArray(new Message[result.size()]);
} }
} }

View File

@ -58,8 +58,9 @@ public class RoundRobinDispatchPolicy implements DispatchPolicy {
Subscription sub = (Subscription)iter.next(); Subscription sub = (Subscription)iter.next();
// Only dispatch to interested subscriptions // Only dispatch to interested subscriptions
if (!sub.matches(node, msgContext)) if (!sub.matches(node, msgContext)) {
continue; continue;
}
if (firstMatchingConsumer == null) { if (firstMatchingConsumer == null) {
firstMatchingConsumer = sub; firstMatchingConsumer = sub;

View File

@ -37,11 +37,13 @@ public class SimpleDispatchPolicy implements DispatchPolicy {
Subscription sub = (Subscription)iter.next(); Subscription sub = (Subscription)iter.next();
// Don't deliver to browsers // Don't deliver to browsers
if (sub.getConsumerInfo().isBrowser()) if (sub.getConsumerInfo().isBrowser()) {
continue; continue;
}
// Only dispatch to interested subscriptions // Only dispatch to interested subscriptions
if (!sub.matches(node, msgContext)) if (!sub.matches(node, msgContext)) {
continue; continue;
}
sub.add(node); sub.add(node);
count++; count++;

View File

@ -50,8 +50,9 @@ public class StrictOrderDispatchPolicy implements DispatchPolicy {
Subscription sub = (Subscription)iter.next(); Subscription sub = (Subscription)iter.next();
// Only dispatch to interested subscriptions // Only dispatch to interested subscriptions
if (!sub.matches(node, msgContext)) if (!sub.matches(node, msgContext)) {
continue; continue;
}
sub.add(node); sub.add(node);
count++; count++;

View File

@ -42,7 +42,7 @@ public class VirtualDestinationInterceptor implements DestinationInterceptor {
public Destination intercept(Destination destination) { public Destination intercept(Destination destination) {
Set virtualDestinations = destinationMap.get(destination.getActiveMQDestination()); Set virtualDestinations = destinationMap.get(destination.getActiveMQDestination());
List destinations = new ArrayList(); List<Destination> destinations = new ArrayList<Destination>();
for (Iterator iter = virtualDestinations.iterator(); iter.hasNext();) { for (Iterator iter = virtualDestinations.iterator(); iter.hasNext();) {
VirtualDestination virtualDestination = (VirtualDestination)iter.next(); VirtualDestination virtualDestination = (VirtualDestination)iter.next();
Destination newNestination = virtualDestination.intercept(destination); Destination newNestination = virtualDestination.intercept(destination);
@ -50,7 +50,7 @@ public class VirtualDestinationInterceptor implements DestinationInterceptor {
} }
if (!destinations.isEmpty()) { if (!destinations.isEmpty()) {
if (destinations.size() == 1) { if (destinations.size() == 1) {
return (Destination)destinations.get(0); return destinations.get(0);
} else { } else {
// should rarely be used but here just in case // should rarely be used but here just in case
return createCompositeDestination(destination, destinations); return createCompositeDestination(destination, destinations);
@ -72,11 +72,11 @@ public class VirtualDestinationInterceptor implements DestinationInterceptor {
} }
} }
protected Destination createCompositeDestination(Destination destination, final List destinations) { protected Destination createCompositeDestination(Destination destination, final List<Destination> destinations) {
return new DestinationFilter(destination) { return new DestinationFilter(destination) {
public void send(ProducerBrokerExchange context, Message messageSend) throws Exception { public void send(ProducerBrokerExchange context, Message messageSend) throws Exception {
for (Iterator iter = destinations.iterator(); iter.hasNext();) { for (Iterator<Destination> iter = destinations.iterator(); iter.hasNext();) {
Destination destination = (Destination)iter.next(); Destination destination = iter.next();
destination.send(context, messageSend); destination.send(context, messageSend);
} }
} }

View File

@ -16,10 +16,7 @@
*/ */
package org.apache.activemq.broker.util; package org.apache.activemq.broker.util;
import org.apache.activemq.command.ActiveMQTextMessage; import java.io.IOException;
import org.apache.activemq.util.FactoryFinder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.jms.Destination; import javax.jms.Destination;
import javax.jms.JMSException; import javax.jms.JMSException;
@ -28,9 +25,11 @@ import javax.jms.MessageListener;
import javax.jms.MessageProducer; import javax.jms.MessageProducer;
import javax.jms.Session; import javax.jms.Session;
import javax.jms.TextMessage; import javax.jms.TextMessage;
import java.io.BufferedReader;
import java.io.IOException; import org.apache.activemq.command.ActiveMQTextMessage;
import java.io.InputStreamReader; import org.apache.activemq.util.FactoryFinder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/** /**
* @version $Revision: $ * @version $Revision: $
@ -51,7 +50,7 @@ public class CommandMessageListener implements MessageListener {
LOG.debug("Received command: " + message); LOG.debug("Received command: " + message);
} }
if (message instanceof TextMessage) { if (message instanceof TextMessage) {
TextMessage request = (TextMessage) message; TextMessage request = (TextMessage)message;
try { try {
Destination replyTo = message.getJMSReplyTo(); Destination replyTo = message.getJMSReplyTo();
if (replyTo == null) { if (replyTo == null) {
@ -61,12 +60,10 @@ public class CommandMessageListener implements MessageListener {
Message response = processCommand(request); Message response = processCommand(request);
addReplyHeaders(request, response); addReplyHeaders(request, response);
getProducer().send(replyTo, response); getProducer().send(replyTo, response);
} } catch (Exception e) {
catch (Exception e) {
LOG.error("Failed to process message due to: " + e + ". Message: " + message, e); LOG.error("Failed to process message due to: " + e + ". Message: " + message, e);
} }
} } else {
else {
LOG.warn("Ignoring invalid message: " + message); LOG.warn("Ignoring invalid message: " + message);
} }
} }
@ -88,7 +85,8 @@ public class CommandMessageListener implements MessageListener {
} }
/** /**
* Processes an incoming command from a console and returning the text to output * Processes an incoming command from a console and returning the text to
* output
*/ */
public String processCommandText(String line) throws Exception { public String processCommandText(String line) throws Exception {
TextMessage request = new ActiveMQTextMessage(); TextMessage request = new ActiveMQTextMessage();
@ -118,6 +116,6 @@ public class CommandMessageListener implements MessageListener {
private CommandHandler createHandler() throws IllegalAccessException, IOException, ClassNotFoundException, InstantiationException { private CommandHandler createHandler() throws IllegalAccessException, IOException, ClassNotFoundException, InstantiationException {
FactoryFinder factoryFinder = new FactoryFinder("META-INF/services/org/apache/activemq/broker/"); FactoryFinder factoryFinder = new FactoryFinder("META-INF/services/org/apache/activemq/broker/");
return (CommandHandler) factoryFinder.newInstance("agent"); return (CommandHandler)factoryFinder.newInstance("agent");
} }
} }

View File

@ -87,8 +87,9 @@ public class UDPTraceBrokerPlugin extends BrokerPluginSupport {
public void start() throws Exception { public void start() throws Exception {
super.start(); super.start();
if (getWireFormat() == null) if (getWireFormat() == null) {
throw new IllegalArgumentException("Wireformat must be specifed."); throw new IllegalArgumentException("Wireformat must be specifed.");
}
if (address == null) { if (address == null) {
address = createSocketAddress(destination); address = createSocketAddress(destination);
} }

View File

@ -57,8 +57,8 @@ public class ConnectionDotFileInterceptor extends DotFileInterceptorSupport {
private MBeanServer mbeanServer; private MBeanServer mbeanServer;
// until we have some MBeans for producers, lets do it all ourselves // until we have some MBeans for producers, lets do it all ourselves
private Map producers = new HashMap(); private Map<ProducerId, ProducerInfo> producers = new HashMap<ProducerId, ProducerInfo>();
private Map producerDestinations = new HashMap(); private Map<ProducerId, Set> producerDestinations = new HashMap<ProducerId, Set>();
private Object lock = new Object(); private Object lock = new Object();
public ConnectionDotFileInterceptor(Broker next, String file, boolean redrawOnRemove) throws MalformedObjectNameException { public ConnectionDotFileInterceptor(Broker next, String file, boolean redrawOnRemove) throws MalformedObjectNameException {
@ -109,9 +109,9 @@ public class ConnectionDotFileInterceptor extends DotFileInterceptorSupport {
ProducerId producerId = messageSend.getProducerId(); ProducerId producerId = messageSend.getProducerId();
ActiveMQDestination destination = messageSend.getDestination(); ActiveMQDestination destination = messageSend.getDestination();
synchronized (lock) { synchronized (lock) {
Set destinations = (Set)producerDestinations.get(producerId); Set<ActiveMQDestination> destinations = producerDestinations.get(producerId);
if (destinations == null) { if (destinations == null) {
destinations = new HashSet(); destinations = new HashSet<ActiveMQDestination>();
} }
producerDestinations.put(producerId, destinations); producerDestinations.put(producerId, destinations);
destinations.add(destination); destinations.add(destination);
@ -127,9 +127,9 @@ public class ConnectionDotFileInterceptor extends DotFileInterceptorSupport {
writer.println("node [style = \"rounded,filled\", fillcolor = yellow, fontname=\"Helvetica-Oblique\"];"); writer.println("node [style = \"rounded,filled\", fillcolor = yellow, fontname=\"Helvetica-Oblique\"];");
writer.println(); writer.println();
Map clients = new HashMap(); Map<String, String> clients = new HashMap<String, String>();
Map queues = new HashMap(); Map<String, String> queues = new HashMap<String, String>();
Map topics = new HashMap(); Map<String, String> topics = new HashMap<String, String>();
printSubscribers(writer, clients, queues, "queue_", brokerView.getQueueSubscribers()); printSubscribers(writer, clients, queues, "queue_", brokerView.getQueueSubscribers());
writer.println(); writer.println();
@ -152,7 +152,7 @@ public class ConnectionDotFileInterceptor extends DotFileInterceptorSupport {
} }
} }
protected void printProducers(PrintWriter writer, Map clients, Map queues, Map topics) { protected void printProducers(PrintWriter writer, Map<String, String> clients, Map<String, String> queues, Map<String, String> topics) {
synchronized (lock) { synchronized (lock) {
for (Iterator iter = producerDestinations.entrySet().iterator(); iter.hasNext();) { for (Iterator iter = producerDestinations.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry)iter.next(); Map.Entry entry = (Map.Entry)iter.next();
@ -163,7 +163,7 @@ public class ConnectionDotFileInterceptor extends DotFileInterceptorSupport {
} }
} }
protected void printProducers(PrintWriter writer, Map clients, Map queues, Map topics, ProducerId producerId, Set destinationSet) { protected void printProducers(PrintWriter writer, Map<String, String> clients, Map<String, String> queues, Map<String, String> topics, ProducerId producerId, Set destinationSet) {
for (Iterator iter = destinationSet.iterator(); iter.hasNext();) { for (Iterator iter = destinationSet.iterator(); iter.hasNext();) {
ActiveMQDestination destination = (ActiveMQDestination)iter.next(); ActiveMQDestination destination = (ActiveMQDestination)iter.next();
@ -206,7 +206,7 @@ public class ConnectionDotFileInterceptor extends DotFileInterceptorSupport {
} }
} }
protected void printSubscribers(PrintWriter writer, Map clients, Map destinations, String type, ObjectName[] subscribers) { protected void printSubscribers(PrintWriter writer, Map<String, String> clients, Map<String, String> destinations, String type, ObjectName[] subscribers) {
for (int i = 0; i < subscribers.length; i++) { for (int i = 0; i < subscribers.length; i++) {
ObjectName name = subscribers[i]; ObjectName name = subscribers[i];
SubscriptionViewMBean subscriber = (SubscriptionViewMBean)MBeanServerInvocationHandler.newProxyInstance(mbeanServer, name, SubscriptionViewMBean.class, true); SubscriptionViewMBean subscriber = (SubscriptionViewMBean)MBeanServerInvocationHandler.newProxyInstance(mbeanServer, name, SubscriptionViewMBean.class, true);
@ -246,7 +246,7 @@ public class ConnectionDotFileInterceptor extends DotFileInterceptorSupport {
} }
} }
protected void writeLabels(PrintWriter writer, String color, String prefix, Map map) { protected void writeLabels(PrintWriter writer, String color, String prefix, Map<String, String> map) {
for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry)iter.next(); Map.Entry entry = (Map.Entry)iter.next();
String id = (String)entry.getKey(); String id = (String)entry.getKey();

View File

@ -36,9 +36,11 @@ import org.apache.camel.util.ObjectHelper;
* @version $Revision: $ * @version $Revision: $
*/ */
public class CamelMessageProducer extends ActiveMQMessageProducerSupport { public class CamelMessageProducer extends ActiveMQMessageProducerSupport {
protected Producer producer;
private final CamelDestination destination; private final CamelDestination destination;
private final Endpoint endpoint; private final Endpoint endpoint;
protected Producer producer;
private boolean closed; private boolean closed;
public CamelMessageProducer(CamelDestination destination, Endpoint endpoint, ActiveMQSession session) throws JMSException { public CamelMessageProducer(CamelDestination destination, Endpoint endpoint, ActiveMQSession session) throws JMSException {

View File

@ -817,8 +817,9 @@ public class ActiveMQBytesMessage extends ActiveMQMessage implements BytesMessag
checkWriteOnlyBody(); checkWriteOnlyBody();
if (dataIn == null) { if (dataIn == null) {
ByteSequence data = getContent(); ByteSequence data = getContent();
if (data == null) if (data == null) {
data = new ByteSequence(new byte[] {}, 0, 0); data = new ByteSequence(new byte[] {}, 0, 0);
}
InputStream is = new ByteArrayInputStream(data); InputStream is = new ByteArrayInputStream(data);
if (isCompressed()) { if (isCompressed()) {
// keep track of the real length of the content if // keep track of the real length of the content if

View File

@ -22,6 +22,7 @@ import java.io.ObjectInput;
import java.io.ObjectOutput; import java.io.ObjectOutput;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
import java.util.StringTokenizer; import java.util.StringTokenizer;
@ -41,10 +42,7 @@ import org.apache.activemq.util.URISupport;
* @openwire:marshaller * @openwire:marshaller
* @version $Revision: 1.10 $ * @version $Revision: 1.10 $
*/ */
public abstract class ActiveMQDestination extends JNDIBaseStorable implements DataStructure, Destination, public abstract class ActiveMQDestination extends JNDIBaseStorable implements DataStructure, Destination, Externalizable, Comparable {
Externalizable, Comparable {
private static final long serialVersionUID = -3885260014960795889L;
public static final String PATH_SEPERATOR = "."; public static final String PATH_SEPERATOR = ".";
public static final char COMPOSITE_SEPERATOR = ','; public static final char COMPOSITE_SEPERATOR = ',';
@ -62,13 +60,27 @@ public abstract class ActiveMQDestination extends JNDIBaseStorable implements Da
public static final String TEMP_DESTINATION_NAME_PREFIX = "ID:"; public static final String TEMP_DESTINATION_NAME_PREFIX = "ID:";
private static final long serialVersionUID = -3885260014960795889L;
protected String physicalName; protected String physicalName;
protected transient ActiveMQDestination[] compositeDestinations; protected transient ActiveMQDestination[] compositeDestinations;
protected transient String[] destinationPaths; protected transient String[] destinationPaths;
protected transient boolean isPattern; protected transient boolean isPattern;
protected transient int hashValue; protected transient int hashValue;
protected Map options; protected Map<String, String> options;
public ActiveMQDestination() {
}
protected ActiveMQDestination(String name) {
setPhysicalName(name);
}
public ActiveMQDestination(ActiveMQDestination composites[]) {
setCompositeDestinations(composites);
}
// static helper methods for working with destinations // static helper methods for working with destinations
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
@ -99,18 +111,24 @@ public abstract class ActiveMQDestination extends JNDIBaseStorable implements Da
} }
public static ActiveMQDestination transform(Destination dest) throws JMSException { public static ActiveMQDestination transform(Destination dest) throws JMSException {
if (dest == null) if (dest == null) {
return null; return null;
if (dest instanceof ActiveMQDestination) }
if (dest instanceof ActiveMQDestination) {
return (ActiveMQDestination)dest; return (ActiveMQDestination)dest;
if (dest instanceof TemporaryQueue) }
if (dest instanceof TemporaryQueue) {
return new ActiveMQTempQueue(((TemporaryQueue)dest).getQueueName()); return new ActiveMQTempQueue(((TemporaryQueue)dest).getQueueName());
if (dest instanceof TemporaryTopic) }
if (dest instanceof TemporaryTopic) {
return new ActiveMQTempTopic(((TemporaryTopic)dest).getTopicName()); return new ActiveMQTempTopic(((TemporaryTopic)dest).getTopicName());
if (dest instanceof Queue) }
if (dest instanceof Queue) {
return new ActiveMQQueue(((Queue)dest).getQueueName()); return new ActiveMQQueue(((Queue)dest).getQueueName());
if (dest instanceof Topic) }
if (dest instanceof Topic) {
return new ActiveMQTopic(((Topic)dest).getTopicName()); return new ActiveMQTopic(((Topic)dest).getTopicName());
}
throw new JMSException("Could not transform the destination into a ActiveMQ destination: " + dest); throw new JMSException("Could not transform the destination into a ActiveMQ destination: " + dest);
} }
@ -131,17 +149,6 @@ public abstract class ActiveMQDestination extends JNDIBaseStorable implements Da
} }
} }
public ActiveMQDestination() {
}
protected ActiveMQDestination(String name) {
setPhysicalName(name);
}
public ActiveMQDestination(ActiveMQDestination composites[]) {
setCompositeDestinations(composites);
}
public int compareTo(Object that) { public int compareTo(Object that) {
if (that instanceof ActiveMQDestination) { if (that instanceof ActiveMQDestination) {
return compare(this, (ActiveMQDestination)that); return compare(this, (ActiveMQDestination)that);
@ -169,8 +176,9 @@ public abstract class ActiveMQDestination extends JNDIBaseStorable implements Da
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
for (int i = 0; i < destinations.length; i++) { for (int i = 0; i < destinations.length; i++) {
if (i != 0) if (i != 0) {
sb.append(COMPOSITE_SEPERATOR); sb.append(COMPOSITE_SEPERATOR);
}
if (getDestinationType() == destinations[i].getDestinationType()) { if (getDestinationType() == destinations[i].getDestinationType()) {
sb.append(destinations[i].getPhysicalName()); sb.append(destinations[i].getPhysicalName());
} else { } else {
@ -181,8 +189,9 @@ public abstract class ActiveMQDestination extends JNDIBaseStorable implements Da
} }
public String getQualifiedName() { public String getQualifiedName() {
if (isComposite()) if (isComposite()) {
return physicalName; return physicalName;
}
return getQualifiedPrefix() + physicalName; return getQualifiedPrefix() + physicalName;
} }
@ -221,8 +230,7 @@ public abstract class ActiveMQDestination extends JNDIBaseStorable implements Da
try { try {
options = URISupport.parseQuery(optstring); options = URISupport.parseQuery(optstring);
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
throw new IllegalArgumentException("Invalid destination name: " + physicalName throw new IllegalArgumentException("Invalid destination name: " + physicalName + ", it's options are not encoded properly: " + e);
+ ", it's options are not encoded properly: " + e);
} }
} }
this.physicalName = physicalName; this.physicalName = physicalName;
@ -230,12 +238,13 @@ public abstract class ActiveMQDestination extends JNDIBaseStorable implements Da
this.hashValue = 0; this.hashValue = 0;
if (composite) { if (composite) {
// Check to see if it is a composite. // Check to see if it is a composite.
ArrayList<String> l = new ArrayList<String>(); List<String> l = new ArrayList<String>();
StringTokenizer iter = new StringTokenizer(physicalName, "" + COMPOSITE_SEPERATOR); StringTokenizer iter = new StringTokenizer(physicalName, "" + COMPOSITE_SEPERATOR);
while (iter.hasMoreTokens()) { while (iter.hasMoreTokens()) {
String name = iter.nextToken().trim(); String name = iter.nextToken().trim();
if (name.length() == 0) if (name.length() == 0) {
continue; continue;
}
l.add(name); l.add(name);
} }
if (l.size() > 1) { if (l.size() > 1) {
@ -254,15 +263,17 @@ public abstract class ActiveMQDestination extends JNDIBaseStorable implements Da
public String[] getDestinationPaths() { public String[] getDestinationPaths() {
if (destinationPaths != null) if (destinationPaths != null) {
return destinationPaths; return destinationPaths;
}
ArrayList l = new ArrayList(); List<String> l = new ArrayList<String>();
StringTokenizer iter = new StringTokenizer(physicalName, PATH_SEPERATOR); StringTokenizer iter = new StringTokenizer(physicalName, PATH_SEPERATOR);
while (iter.hasMoreTokens()) { while (iter.hasMoreTokens()) {
String name = iter.nextToken().trim(); String name = iter.nextToken().trim();
if (name.length() == 0) if (name.length() == 0) {
continue; continue;
}
l.add(name); l.add(name);
} }
@ -286,10 +297,12 @@ public abstract class ActiveMQDestination extends JNDIBaseStorable implements Da
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) if (this == o) {
return true; return true;
if (o == null || getClass() != o.getClass()) }
if (o == null || getClass() != o.getClass()) {
return false; return false;
}
ActiveMQDestination d = (ActiveMQDestination)o; ActiveMQDestination d = (ActiveMQDestination)o;
return physicalName.equals(d.physicalName); return physicalName.equals(d.physicalName);
@ -331,7 +344,7 @@ public abstract class ActiveMQDestination extends JNDIBaseStorable implements Da
} }
} }
public Map getOptions() { public Map<String, String> getOptions() {
return options; return options;
} }

View File

@ -99,7 +99,7 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_MAP_MESSAGE; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_MAP_MESSAGE;
protected transient Map map = new HashMap(); protected transient Map<String, Object> map = new HashMap<String, Object>();
public Message copy() { public Message copy() {
ActiveMQMapMessage copy = new ActiveMQMapMessage(); ActiveMQMapMessage copy = new ActiveMQMapMessage();
@ -474,7 +474,7 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
* @return an enumeration of all the names in this <CODE>MapMessage</CODE> * @return an enumeration of all the names in this <CODE>MapMessage</CODE>
* @throws JMSException * @throws JMSException
*/ */
public Enumeration getMapNames() throws JMSException { public Enumeration<String> getMapNames() throws JMSException {
initializeReading(); initializeReading();
return Collections.enumeration(map.keySet()); return Collections.enumeration(map.keySet());
} }
@ -732,7 +732,7 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
return super.toString() + " ActiveMQMapMessage{ " + "theTable = " + map + " }"; return super.toString() + " ActiveMQMapMessage{ " + "theTable = " + map + " }";
} }
public Map getContentMap() throws JMSException { public Map<String, Object> getContentMap() throws JMSException {
initializeReading(); initializeReading();
return map; return map;
} }

View File

@ -45,12 +45,14 @@ import org.apache.activemq.util.TypeConversionSupport;
public class ActiveMQMessage extends Message implements org.apache.activemq.Message { public class ActiveMQMessage extends Message implements org.apache.activemq.Message {
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_MESSAGE; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_MESSAGE;
private static final Map<String, PropertySetter> JMS_PROPERTY_SETERS = new HashMap<String, PropertySetter>();
protected transient Callback acknowledgeCallback;
public byte getDataStructureType() { public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE; return DATA_STRUCTURE_TYPE;
} }
protected transient Callback acknowledgeCallback;
public Message copy() { public Message copy() {
ActiveMQMessage copy = new ActiveMQMessage(); ActiveMQMessage copy = new ActiveMQMessage();
@ -73,10 +75,12 @@ public class ActiveMQMessage extends Message implements org.apache.activemq.Mess
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) if (this == o) {
return true; return true;
if (o == null || o.getClass() != getClass()) }
if (o == null || o.getClass() != getClass()) {
return false; return false;
}
ActiveMQMessage msg = (ActiveMQMessage)o; ActiveMQMessage msg = (ActiveMQMessage)o;
MessageId oMsg = msg.getMessageId(); MessageId oMsg = msg.getMessageId();
@ -273,7 +277,7 @@ public class ActiveMQMessage extends Message implements org.apache.activemq.Mess
public Enumeration getPropertyNames() throws JMSException { public Enumeration getPropertyNames() throws JMSException {
try { try {
return new Vector(this.getProperties().keySet()).elements(); return new Vector<String>(this.getProperties().keySet()).elements();
} catch (IOException e) { } catch (IOException e) {
throw JMSExceptionSupport.create(e); throw JMSExceptionSupport.create(e);
} }
@ -283,7 +287,6 @@ public class ActiveMQMessage extends Message implements org.apache.activemq.Mess
void set(Message message, Object value) throws MessageFormatException; void set(Message message, Object value) throws MessageFormatException;
} }
private static final HashMap JMS_PROPERTY_SETERS = new HashMap();
static { static {
JMS_PROPERTY_SETERS.put("JMSXDeliveryCount", new PropertySetter() { JMS_PROPERTY_SETERS.put("JMSXDeliveryCount", new PropertySetter() {
public void set(Message message, Object value) throws MessageFormatException { public void set(Message message, Object value) throws MessageFormatException {
@ -391,7 +394,7 @@ public class ActiveMQMessage extends Message implements org.apache.activemq.Mess
} }
checkValidObject(value); checkValidObject(value);
PropertySetter setter = (PropertySetter)JMS_PROPERTY_SETERS.get(name); PropertySetter setter = JMS_PROPERTY_SETERS.get(name);
if (setter != null) { if (setter != null) {
setter.set(this, value); setter.set(this, value);
@ -416,7 +419,7 @@ public class ActiveMQMessage extends Message implements org.apache.activemq.Mess
protected void checkValidObject(Object value) throws MessageFormatException { protected void checkValidObject(Object value) throws MessageFormatException {
boolean valid = value instanceof Boolean || value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long ; boolean valid = value instanceof Boolean || value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long;
valid = valid || value instanceof Float || value instanceof Double || value instanceof Character || value instanceof String || value == null; valid = valid || value instanceof Float || value instanceof Double || value instanceof Character || value instanceof String || value == null;
if (!valid) { if (!valid) {
@ -445,8 +448,9 @@ public class ActiveMQMessage extends Message implements org.apache.activemq.Mess
public boolean getBooleanProperty(String name) throws JMSException { public boolean getBooleanProperty(String name) throws JMSException {
Object value = getObjectProperty(name); Object value = getObjectProperty(name);
if (value == null) if (value == null) {
return false; return false;
}
Boolean rc = (Boolean)TypeConversionSupport.convert(value, Boolean.class); Boolean rc = (Boolean)TypeConversionSupport.convert(value, Boolean.class);
if (rc == null) { if (rc == null) {
throw new MessageFormatException("Property " + name + " was a " + value.getClass().getName() + " and cannot be read as a boolean"); throw new MessageFormatException("Property " + name + " was a " + value.getClass().getName() + " and cannot be read as a boolean");
@ -456,8 +460,9 @@ public class ActiveMQMessage extends Message implements org.apache.activemq.Mess
public byte getByteProperty(String name) throws JMSException { public byte getByteProperty(String name) throws JMSException {
Object value = getObjectProperty(name); Object value = getObjectProperty(name);
if (value == null) if (value == null) {
throw new NumberFormatException("property " + name + " was null"); throw new NumberFormatException("property " + name + " was null");
}
Byte rc = (Byte)TypeConversionSupport.convert(value, Byte.class); Byte rc = (Byte)TypeConversionSupport.convert(value, Byte.class);
if (rc == null) { if (rc == null) {
throw new MessageFormatException("Property " + name + " was a " + value.getClass().getName() + " and cannot be read as a byte"); throw new MessageFormatException("Property " + name + " was a " + value.getClass().getName() + " and cannot be read as a byte");
@ -467,8 +472,9 @@ public class ActiveMQMessage extends Message implements org.apache.activemq.Mess
public short getShortProperty(String name) throws JMSException { public short getShortProperty(String name) throws JMSException {
Object value = getObjectProperty(name); Object value = getObjectProperty(name);
if (value == null) if (value == null) {
throw new NumberFormatException("property " + name + " was null"); throw new NumberFormatException("property " + name + " was null");
}
Short rc = (Short)TypeConversionSupport.convert(value, Short.class); Short rc = (Short)TypeConversionSupport.convert(value, Short.class);
if (rc == null) { if (rc == null) {
throw new MessageFormatException("Property " + name + " was a " + value.getClass().getName() + " and cannot be read as a short"); throw new MessageFormatException("Property " + name + " was a " + value.getClass().getName() + " and cannot be read as a short");
@ -478,8 +484,9 @@ public class ActiveMQMessage extends Message implements org.apache.activemq.Mess
public int getIntProperty(String name) throws JMSException { public int getIntProperty(String name) throws JMSException {
Object value = getObjectProperty(name); Object value = getObjectProperty(name);
if (value == null) if (value == null) {
throw new NumberFormatException("property " + name + " was null"); throw new NumberFormatException("property " + name + " was null");
}
Integer rc = (Integer)TypeConversionSupport.convert(value, Integer.class); Integer rc = (Integer)TypeConversionSupport.convert(value, Integer.class);
if (rc == null) { if (rc == null) {
throw new MessageFormatException("Property " + name + " was a " + value.getClass().getName() + " and cannot be read as an integer"); throw new MessageFormatException("Property " + name + " was a " + value.getClass().getName() + " and cannot be read as an integer");
@ -489,8 +496,9 @@ public class ActiveMQMessage extends Message implements org.apache.activemq.Mess
public long getLongProperty(String name) throws JMSException { public long getLongProperty(String name) throws JMSException {
Object value = getObjectProperty(name); Object value = getObjectProperty(name);
if (value == null) if (value == null) {
throw new NumberFormatException("property " + name + " was null"); throw new NumberFormatException("property " + name + " was null");
}
Long rc = (Long)TypeConversionSupport.convert(value, Long.class); Long rc = (Long)TypeConversionSupport.convert(value, Long.class);
if (rc == null) { if (rc == null) {
throw new MessageFormatException("Property " + name + " was a " + value.getClass().getName() + " and cannot be read as a long"); throw new MessageFormatException("Property " + name + " was a " + value.getClass().getName() + " and cannot be read as a long");
@ -500,8 +508,9 @@ public class ActiveMQMessage extends Message implements org.apache.activemq.Mess
public float getFloatProperty(String name) throws JMSException { public float getFloatProperty(String name) throws JMSException {
Object value = getObjectProperty(name); Object value = getObjectProperty(name);
if (value == null) if (value == null) {
throw new NullPointerException("property " + name + " was null"); throw new NullPointerException("property " + name + " was null");
}
Float rc = (Float)TypeConversionSupport.convert(value, Float.class); Float rc = (Float)TypeConversionSupport.convert(value, Float.class);
if (rc == null) { if (rc == null) {
throw new MessageFormatException("Property " + name + " was a " + value.getClass().getName() + " and cannot be read as a float"); throw new MessageFormatException("Property " + name + " was a " + value.getClass().getName() + " and cannot be read as a float");
@ -511,8 +520,9 @@ public class ActiveMQMessage extends Message implements org.apache.activemq.Mess
public double getDoubleProperty(String name) throws JMSException { public double getDoubleProperty(String name) throws JMSException {
Object value = getObjectProperty(name); Object value = getObjectProperty(name);
if (value == null) if (value == null) {
throw new NullPointerException("property " + name + " was null"); throw new NullPointerException("property " + name + " was null");
}
Double rc = (Double)TypeConversionSupport.convert(value, Double.class); Double rc = (Double)TypeConversionSupport.convert(value, Double.class);
if (rc == null) { if (rc == null) {
throw new MessageFormatException("Property " + name + " was a " + value.getClass().getName() + " and cannot be read as a double"); throw new MessageFormatException("Property " + name + " was a " + value.getClass().getName() + " and cannot be read as a double");
@ -527,8 +537,9 @@ public class ActiveMQMessage extends Message implements org.apache.activemq.Mess
value = getUserID(); value = getUserID();
} }
} }
if (value == null) if (value == null) {
return null; return null;
}
String rc = (String)TypeConversionSupport.convert(value, String.class); String rc = (String)TypeConversionSupport.convert(value, String.class);
if (rc == null) { if (rc == null) {
throw new MessageFormatException("Property " + name + " was a " + value.getClass().getName() + " and cannot be read as a String"); throw new MessageFormatException("Property " + name + " was a " + value.getClass().getName() + " and cannot be read as a String");

View File

@ -63,10 +63,10 @@ import org.apache.activemq.util.JMSExceptionSupport;
* @see javax.jms.TextMessage * @see javax.jms.TextMessage
*/ */
public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMessage { public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMessage {
static final ClassLoader ACTIVEMQ_CLASSLOADER = ActiveMQObjectMessage.class.getClassLoader(); // TODO
// verify // TODO: verify classloader
// classloader
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_OBJECT_MESSAGE; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_OBJECT_MESSAGE;
static final ClassLoader ACTIVEMQ_CLASSLOADER = ActiveMQObjectMessage.class.getClassLoader();
protected transient Serializable object; protected transient Serializable object;

View File

@ -29,20 +29,20 @@ import javax.jms.Queue;
*/ */
public class ActiveMQQueue extends ActiveMQDestination implements Queue { public class ActiveMQQueue extends ActiveMQDestination implements Queue {
private static final long serialVersionUID = -3885260014960795889L;
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_QUEUE; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_QUEUE;
private static final long serialVersionUID = -3885260014960795889L;
public ActiveMQQueue() { public ActiveMQQueue() {
} }
public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE;
}
public ActiveMQQueue(String name) { public ActiveMQQueue(String name) {
super(name); super(name);
} }
public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE;
}
public boolean isQueue() { public boolean isQueue() {
return true; return true;
} }

View File

@ -25,8 +25,8 @@ import javax.jms.TemporaryQueue;
*/ */
public class ActiveMQTempQueue extends ActiveMQTempDestination implements TemporaryQueue { public class ActiveMQTempQueue extends ActiveMQTempDestination implements TemporaryQueue {
private static final long serialVersionUID = 6683049467527633867L;
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_TEMP_QUEUE; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_TEMP_QUEUE;
private static final long serialVersionUID = 6683049467527633867L;
public ActiveMQTempQueue() { public ActiveMQTempQueue() {
} }

View File

@ -25,8 +25,8 @@ import javax.jms.TemporaryTopic;
*/ */
public class ActiveMQTempTopic extends ActiveMQTempDestination implements TemporaryTopic { public class ActiveMQTempTopic extends ActiveMQTempDestination implements TemporaryTopic {
private static final long serialVersionUID = -4325596784597300253L;
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_TEMP_TOPIC; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_TEMP_TOPIC;
private static final long serialVersionUID = -4325596784597300253L;
public ActiveMQTempTopic() { public ActiveMQTempTopic() {
} }

View File

@ -27,8 +27,8 @@ import javax.jms.Topic;
*/ */
public class ActiveMQTopic extends ActiveMQDestination implements Topic { public class ActiveMQTopic extends ActiveMQDestination implements Topic {
private static final long serialVersionUID = 7300307405896488588L;
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_TOPIC; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_TOPIC;
private static final long serialVersionUID = 7300307405896488588L;
public ActiveMQTopic() { public ActiveMQTopic() {
} }

View File

@ -24,7 +24,7 @@ package org.apache.activemq.command;
public class BaseEndpoint implements Endpoint { public class BaseEndpoint implements Endpoint {
private String name; private String name;
BrokerInfo brokerInfo; private BrokerInfo brokerInfo;
public BaseEndpoint(String name) { public BaseEndpoint(String name) {
this.name = name; this.name = name;

View File

@ -19,44 +19,53 @@ package org.apache.activemq.command;
import org.apache.activemq.state.CommandVisitor; import org.apache.activemq.state.CommandVisitor;
/** /**
* The Command Pattern so that we can send and receive commands * The Command Pattern so that we can send and receive commands on the different
* on the different transports * transports
* *
* @version $Revision: 1.7 $ * @version $Revision: 1.7 $
*/ */
public interface Command extends DataStructure { public interface Command extends DataStructure {
void setCommandId(int value); void setCommandId(int value);
/** /**
* @return the unique ID of this request used to map responses to requests * @return the unique ID of this request used to map responses to requests
*/ */
int getCommandId(); int getCommandId();
void setResponseRequired(boolean responseRequired); void setResponseRequired(boolean responseRequired);
boolean isResponseRequired(); boolean isResponseRequired();
boolean isResponse(); boolean isResponse();
boolean isMessageDispatch(); boolean isMessageDispatch();
boolean isBrokerInfo(); boolean isBrokerInfo();
boolean isWireFormatInfo(); boolean isWireFormatInfo();
boolean isMessage(); boolean isMessage();
boolean isMessageAck(); boolean isMessageAck();
boolean isMessageDispatchNotification(); boolean isMessageDispatchNotification();
boolean isShutdownInfo(); boolean isShutdownInfo();
Response visit( CommandVisitor visitor) throws Exception; Response visit(CommandVisitor visitor) throws Exception;
/** /**
* The endpoint within the transport where this message came from which could be null if the * The endpoint within the transport where this message came from which
* transport only supports a single endpoint. * could be null if the transport only supports a single endpoint.
*/ */
Endpoint getFrom(); Endpoint getFrom();
void setFrom(Endpoint from); void setFrom(Endpoint from);
/** /**
* The endpoint within the transport where this message is going to - null means all endpoints. * The endpoint within the transport where this message is going to - null
* means all endpoints.
*/ */
Endpoint getTo(); Endpoint getTo();

View File

@ -27,8 +27,8 @@ public class ConnectionError extends BaseCommand {
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.CONNECTION_ERROR; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.CONNECTION_ERROR;
protected ConnectionId connectionId; private ConnectionId connectionId;
Throwable exception; private Throwable exception;
public byte getDataStructureType() { public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE; return DATA_STRUCTURE_TYPE;

View File

@ -54,10 +54,12 @@ public class ConnectionId implements DataStructure, Comparable<ConnectionId> {
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) if (this == o) {
return true; return true;
if (o == null || o.getClass() != ConnectionId.class) }
if (o == null || o.getClass() != ConnectionId.class) {
return false; return false;
}
ConnectionId id = (ConnectionId)o; ConnectionId id = (ConnectionId)o;
return value.equals(id.value); return value.equals(id.value);
} }

View File

@ -62,10 +62,12 @@ public class ConsumerId implements DataStructure {
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) if (this == o) {
return true; return true;
if (o == null || o.getClass() != ConsumerId.class) }
if (o == null || o.getClass() != ConsumerId.class) {
return false; return false;
}
ConsumerId id = (ConsumerId)o; ConsumerId id = (ConsumerId)o;
return sessionId == id.sessionId && value == id.value && connectionId.equals(id.connectionId); return sessionId == id.sessionId && value == id.value && connectionId.equals(id.connectionId);
} }

View File

@ -22,9 +22,10 @@ package org.apache.activemq.command;
*/ */
public class DataArrayResponse extends Response { public class DataArrayResponse extends Response {
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.DATA_ARRAY_RESPONSE;
DataStructure data[]; DataStructure data[];
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.DATA_ARRAY_RESPONSE;
public DataArrayResponse() { public DataArrayResponse() {
} }

View File

@ -23,10 +23,10 @@ package org.apache.activemq.command;
*/ */
public class DataResponse extends Response { public class DataResponse extends Response {
DataStructure data;
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.DATA_RESPONSE; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.DATA_RESPONSE;
DataStructure data;
public DataResponse() { public DataResponse() {
} }

View File

@ -22,10 +22,10 @@ package org.apache.activemq.command;
*/ */
public class ExceptionResponse extends Response { public class ExceptionResponse extends Response {
Throwable exception;
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.EXCEPTION_RESPONSE; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.EXCEPTION_RESPONSE;
Throwable exception;
public ExceptionResponse() { public ExceptionResponse() {
} }

View File

@ -22,10 +22,10 @@ package org.apache.activemq.command;
*/ */
public class IntegerResponse extends Response { public class IntegerResponse extends Response {
int result;
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.INTEGER_RESPONSE; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.INTEGER_RESPONSE;
int result;
public IntegerResponse() { public IntegerResponse() {
} }

View File

@ -69,10 +69,12 @@ public class LocalTransactionId extends TransactionId implements Comparable<Loca
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) if (this == o) {
return true; return true;
if (o == null || o.getClass() != LocalTransactionId.class) }
if (o == null || o.getClass() != LocalTransactionId.class) {
return false; return false;
}
LocalTransactionId tx = (LocalTransactionId)o; LocalTransactionId tx = (LocalTransactionId)o;
return value == tx.value && connectionId.equals(tx.connectionId); return value == tx.value && connectionId.equals(tx.connectionId);
} }

View File

@ -72,17 +72,17 @@ public abstract class Message extends BaseCommand implements MarshallAware, Mess
protected int redeliveryCounter; protected int redeliveryCounter;
protected int size; protected int size;
protected Map properties; protected Map<String, Object> properties;
protected boolean readOnlyProperties; protected boolean readOnlyProperties;
protected boolean readOnlyBody; protected boolean readOnlyBody;
protected transient boolean recievedByDFBridge; protected transient boolean recievedByDFBridge;
protected boolean droppable;
private transient short referenceCount; private transient short referenceCount;
private transient ActiveMQConnection connection; private transient ActiveMQConnection connection;
private transient org.apache.activemq.broker.region.Destination regionDestination; private transient org.apache.activemq.broker.region.Destination regionDestination;
private BrokerId[] brokerPath; private BrokerId[] brokerPath;
protected boolean droppable;
private BrokerId[] cluster; private BrokerId[] cluster;
public abstract Message copy(); public abstract Message copy();
@ -109,7 +109,7 @@ public abstract class Message extends BaseCommand implements MarshallAware, Mess
copy.groupSequence = groupSequence; copy.groupSequence = groupSequence;
if (properties != null) { if (properties != null) {
copy.properties = new HashMap(properties); copy.properties = new HashMap<String, Object>(properties);
} else { } else {
copy.properties = properties; copy.properties = properties;
} }
@ -139,17 +139,20 @@ public abstract class Message extends BaseCommand implements MarshallAware, Mess
public Object getProperty(String name) throws IOException { public Object getProperty(String name) throws IOException {
if (properties == null) { if (properties == null) {
if (marshalledProperties == null) if (marshalledProperties == null) {
return null; return null;
}
properties = unmarsallProperties(marshalledProperties); properties = unmarsallProperties(marshalledProperties);
} }
return properties.get(name); return properties.get(name);
} }
public Map getProperties() throws IOException { @SuppressWarnings("unchecked")
public Map<String, Object> getProperties() throws IOException {
if (properties == null) { if (properties == null) {
if (marshalledProperties == null) if (marshalledProperties == null) {
return Collections.EMPTY_MAP; return Collections.EMPTY_MAP;
}
properties = unmarsallProperties(marshalledProperties); properties = unmarsallProperties(marshalledProperties);
} }
return Collections.unmodifiableMap(properties); return Collections.unmodifiableMap(properties);
@ -168,7 +171,7 @@ public abstract class Message extends BaseCommand implements MarshallAware, Mess
protected void lazyCreateProperties() throws IOException { protected void lazyCreateProperties() throws IOException {
if (properties == null) { if (properties == null) {
if (marshalledProperties == null) { if (marshalledProperties == null) {
properties = new HashMap(); properties = new HashMap<String, Object>();
} else { } else {
properties = unmarsallProperties(marshalledProperties); properties = unmarsallProperties(marshalledProperties);
marshalledProperties = null; marshalledProperties = null;
@ -176,7 +179,7 @@ public abstract class Message extends BaseCommand implements MarshallAware, Mess
} }
} }
private Map unmarsallProperties(ByteSequence marshalledProperties) throws IOException { private Map<String, Object> unmarsallProperties(ByteSequence marshalledProperties) throws IOException {
return MarshallingSupport.unmarshalPrimitiveMap(new DataInputStream(new ByteArrayInputStream(marshalledProperties))); return MarshallingSupport.unmarshalPrimitiveMap(new DataInputStream(new ByteArrayInputStream(marshalledProperties)));
} }
@ -578,8 +581,9 @@ public abstract class Message extends BaseCommand implements MarshallAware, Mess
size = getSize(); size = getSize();
} }
if (rc == 1 && regionDestination != null) if (rc == 1 && regionDestination != null) {
regionDestination.getUsageManager().increaseUsage(size); regionDestination.getUsageManager().increaseUsage(size);
}
// System.out.println(" + "+getDestination()+" :::: "+getMessageId()+" // System.out.println(" + "+getDestination()+" :::: "+getMessageId()+"
// "+rc); // "+rc);
@ -594,9 +598,9 @@ public abstract class Message extends BaseCommand implements MarshallAware, Mess
size = getSize(); size = getSize();
} }
if (rc == 0 && regionDestination != null) if (rc == 0 && regionDestination != null) {
regionDestination.getUsageManager().decreaseUsage(size); regionDestination.getUsageManager().decreaseUsage(size);
}
// System.out.println(" - "+getDestination()+" :::: "+getMessageId()+" // System.out.println(" - "+getDestination()+" :::: "+getMessageId()+"
// "+rc); // "+rc);
@ -606,10 +610,12 @@ public abstract class Message extends BaseCommand implements MarshallAware, Mess
public int getSize() { public int getSize() {
if (size <= AVERAGE_MESSAGE_SIZE_OVERHEAD) { if (size <= AVERAGE_MESSAGE_SIZE_OVERHEAD) {
size = AVERAGE_MESSAGE_SIZE_OVERHEAD; size = AVERAGE_MESSAGE_SIZE_OVERHEAD;
if (marshalledProperties != null) if (marshalledProperties != null) {
size += marshalledProperties.getLength(); size += marshalledProperties.getLength();
if (content != null) }
if (content != null) {
size += content.getLength(); size += content.getLength();
}
} }
return size; return size;
} }

View File

@ -81,10 +81,12 @@ public class MessageId implements DataStructure, Comparable<MessageId> {
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) if (this == o) {
return true; return true;
if (o == null || o.getClass() != getClass()) }
if (o == null || o.getClass() != getClass()) {
return false; return false;
}
MessageId id = (MessageId)o; MessageId id = (MessageId)o;
return producerSequenceId == id.producerSequenceId && producerId.equals(id.producerId); return producerSequenceId == id.producerSequenceId && producerId.equals(id.producerId);

View File

@ -106,8 +106,9 @@ public class NetworkBridgeFilter implements DataStructure, BooleanExpression {
public static boolean contains(BrokerId[] brokerPath, BrokerId brokerId) { public static boolean contains(BrokerId[] brokerPath, BrokerId brokerId) {
if (brokerPath != null && brokerId != null) { if (brokerPath != null && brokerId != null) {
for (int i = 0; i < brokerPath.length; i++) { for (int i = 0; i < brokerPath.length; i++) {
if (brokerId.equals(brokerPath[i])) if (brokerId.equals(brokerPath[i])) {
return true; return true;
}
} }
} }
return false; return false;

View File

@ -72,10 +72,12 @@ public class ProducerId implements DataStructure {
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) if (this == o) {
return true; return true;
if (o == null || o.getClass() != ProducerId.class) }
if (o == null || o.getClass() != ProducerId.class) {
return false; return false;
}
ProducerId id = (ProducerId)o; ProducerId id = (ProducerId)o;
return sessionId == id.sessionId && value == id.value && connectionId.equals(id.connectionId); return sessionId == id.sessionId && value == id.value && connectionId.equals(id.connectionId);
} }

View File

@ -70,10 +70,12 @@ public class SessionId implements DataStructure {
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) if (this == o) {
return true; return true;
if (o == null || o.getClass() != SessionId.class) }
if (o == null || o.getClass() != SessionId.class) {
return false; return false;
}
SessionId id = (SessionId)o; SessionId id = (SessionId)o;
return value == id.value && connectionId.equals(id.connectionId); return value == id.value && connectionId.equals(id.connectionId);
} }

View File

@ -32,21 +32,20 @@ import org.apache.activemq.util.MarshallingSupport;
import org.apache.activemq.wireformat.WireFormat; import org.apache.activemq.wireformat.WireFormat;
/** /**
*
* @openwire:marshaller code="1" * @openwire:marshaller code="1"
* @version $Revision$ * @version $Revision$
*/ */
public class WireFormatInfo implements Command, MarshallAware { public class WireFormatInfo implements Command, MarshallAware {
private static final int MAX_PROPERTY_SIZE = 1024 * 4;
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.WIREFORMAT_INFO; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.WIREFORMAT_INFO;
private static final int MAX_PROPERTY_SIZE = 1024 * 4;
private static final byte MAGIC[] = new byte[] {'A', 'c', 't', 'i', 'v', 'e', 'M', 'Q'}; private static final byte MAGIC[] = new byte[] {'A', 'c', 't', 'i', 'v', 'e', 'M', 'Q'};
protected byte magic[] = MAGIC; protected byte magic[] = MAGIC;
protected int version; protected int version;
protected ByteSequence marshalledProperties; protected ByteSequence marshalledProperties;
protected transient Map properties; protected transient Map<String, Object> properties;
private transient Endpoint from; private transient Endpoint from;
private transient Endpoint to; private transient Endpoint to;
@ -126,17 +125,20 @@ public class WireFormatInfo implements Command, MarshallAware {
public Object getProperty(String name) throws IOException { public Object getProperty(String name) throws IOException {
if (properties == null) { if (properties == null) {
if (marshalledProperties == null) if (marshalledProperties == null) {
return null; return null;
}
properties = unmarsallProperties(marshalledProperties); properties = unmarsallProperties(marshalledProperties);
} }
return properties.get(name); return properties.get(name);
} }
public Map getProperties() throws IOException { @SuppressWarnings("unchecked")
public Map<String, Object> getProperties() throws IOException {
if (properties == null) { if (properties == null) {
if (marshalledProperties == null) if (marshalledProperties == null) {
return Collections.EMPTY_MAP; return Collections.EMPTY_MAP;
}
properties = unmarsallProperties(marshalledProperties); properties = unmarsallProperties(marshalledProperties);
} }
return Collections.unmodifiableMap(properties); return Collections.unmodifiableMap(properties);
@ -155,7 +157,7 @@ public class WireFormatInfo implements Command, MarshallAware {
protected void lazyCreateProperties() throws IOException { protected void lazyCreateProperties() throws IOException {
if (properties == null) { if (properties == null) {
if (marshalledProperties == null) { if (marshalledProperties == null) {
properties = new HashMap(); properties = new HashMap<String, Object>();
} else { } else {
properties = unmarsallProperties(marshalledProperties); properties = unmarsallProperties(marshalledProperties);
marshalledProperties = null; marshalledProperties = null;
@ -163,10 +165,8 @@ public class WireFormatInfo implements Command, MarshallAware {
} }
} }
private Map unmarsallProperties(ByteSequence marshalledProperties) throws IOException { private Map<String, Object> unmarsallProperties(ByteSequence marshalledProperties) throws IOException {
return MarshallingSupport return MarshallingSupport.unmarshalPrimitiveMap(new DataInputStream(new ByteArrayInputStream(marshalledProperties)), MAX_PROPERTY_SIZE);
.unmarshalPrimitiveMap(new DataInputStream(new ByteArrayInputStream(marshalledProperties)),
MAX_PROPERTY_SIZE);
} }
public void beforeMarshall(WireFormat wireFormat) throws IOException { public void beforeMarshall(WireFormat wireFormat) throws IOException {
@ -280,13 +280,12 @@ public class WireFormatInfo implements Command, MarshallAware {
} }
public String toString() { public String toString() {
Map p = null; Map<String, Object> p = null;
try { try {
p = getProperties(); p = getProperties();
} catch (IOException e) { } catch (IOException ignore) {
} }
return "WireFormatInfo { version=" + version + ", properties=" + p + ", magic=" + toString(magic) return "WireFormatInfo { version=" + version + ", properties=" + p + ", magic=" + toString(magic) + "}";
+ "}";
} }
private String toString(byte[] data) { private String toString(byte[] data) {

View File

@ -117,23 +117,26 @@ public class XATransactionId extends TransactionId implements Xid, Comparable {
} }
private static int hash(byte[] bytes, int hash) { private static int hash(byte[] bytes, int hash) {
for (int i = 0, size = bytes.length; i < size; i++) { int size = bytes.length;
for (int i = 0; i < size; i++) {
hash ^= bytes[i] << ((i % 4) * 8); hash ^= bytes[i] << ((i % 4) * 8);
} }
return hash; return hash;
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (o == null || o.getClass() != XATransactionId.class) if (o == null || o.getClass() != XATransactionId.class) {
return false; return false;
}
XATransactionId xid = (XATransactionId)o; XATransactionId xid = (XATransactionId)o;
return xid.formatId == formatId && Arrays.equals(xid.globalTransactionId, globalTransactionId) return xid.formatId == formatId && Arrays.equals(xid.globalTransactionId, globalTransactionId)
&& Arrays.equals(xid.branchQualifier, branchQualifier); && Arrays.equals(xid.branchQualifier, branchQualifier);
} }
public int compareTo(Object o) { public int compareTo(Object o) {
if (o == null || o.getClass() != XATransactionId.class) if (o == null || o.getClass() != XATransactionId.class) {
return -1; return -1;
}
XATransactionId xid = (XATransactionId)o; XATransactionId xid = (XATransactionId)o;
return getTransactionKey().compareTo(xid.getTransactionKey()); return getTransactionKey().compareTo(xid.getTransactionKey());
} }

View File

@ -18,6 +18,7 @@ package org.apache.activemq.filter;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.jms.JMSException; import javax.jms.JMSException;
@ -29,17 +30,24 @@ import javax.jms.JMSException;
*/ */
public abstract class ComparisonExpression extends BinaryExpression implements BooleanExpression { public abstract class ComparisonExpression extends BinaryExpression implements BooleanExpression {
private static final Set<Character> REGEXP_CONTROL_CHARS = new HashSet<Character>();
/**
* @param left
* @param right
*/
public ComparisonExpression(Expression left, Expression right) {
super(left, right);
}
public static BooleanExpression createBetween(Expression value, Expression left, Expression right) { public static BooleanExpression createBetween(Expression value, Expression left, Expression right) {
return LogicExpression.createAND(createGreaterThanEqual(value, left), createLessThanEqual(value, return LogicExpression.createAND(createGreaterThanEqual(value, left), createLessThanEqual(value, right));
right));
} }
public static BooleanExpression createNotBetween(Expression value, Expression left, Expression right) { public static BooleanExpression createNotBetween(Expression value, Expression left, Expression right) {
return LogicExpression.createOR(createLessThan(value, left), createGreaterThan(value, right)); return LogicExpression.createOR(createLessThan(value, left), createGreaterThan(value, right));
} }
private static final HashSet REGEXP_CONTROL_CHARS = new HashSet();
static { static {
REGEXP_CONTROL_CHARS.add(Character.valueOf('.')); REGEXP_CONTROL_CHARS.add(Character.valueOf('.'));
REGEXP_CONTROL_CHARS.add(Character.valueOf('\\')); REGEXP_CONTROL_CHARS.add(Character.valueOf('\\'));
@ -138,9 +146,7 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
public static BooleanExpression createLike(Expression left, String right, String escape) { public static BooleanExpression createLike(Expression left, String right, String escape) {
if (escape != null && escape.length() != 1) { if (escape != null && escape.length() != 1) {
throw new RuntimeException( throw new RuntimeException("The ESCAPE string litteral is invalid. It can only be one character. Litteral used: " + escape);
"The ESCAPE string litteral is invalid. It can only be one character. Litteral used: "
+ escape);
} }
int c = -1; int c = -1;
if (escape != null) { if (escape != null) {
@ -156,16 +162,18 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
public static BooleanExpression createInFilter(Expression left, List elements) { public static BooleanExpression createInFilter(Expression left, List elements) {
if (!(left instanceof PropertyExpression)) if (!(left instanceof PropertyExpression)) {
throw new RuntimeException("Expected a property for In expression, got: " + left); throw new RuntimeException("Expected a property for In expression, got: " + left);
}
return UnaryExpression.createInExpression((PropertyExpression)left, elements, false); return UnaryExpression.createInExpression((PropertyExpression)left, elements, false);
} }
public static BooleanExpression createNotInFilter(Expression left, List elements) { public static BooleanExpression createNotInFilter(Expression left, List elements) {
if (!(left instanceof PropertyExpression)) if (!(left instanceof PropertyExpression)) {
throw new RuntimeException("Expected a property for In expression, got: " + left); throw new RuntimeException("Expected a property for In expression, got: " + left);
}
return UnaryExpression.createInExpression((PropertyExpression)left, elements, true); return UnaryExpression.createInExpression((PropertyExpression)left, elements, true);
} }
@ -286,8 +294,9 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
public static void checkLessThanOperand(Expression expr) { public static void checkLessThanOperand(Expression expr) {
if (expr instanceof ConstantExpression) { if (expr instanceof ConstantExpression) {
Object value = ((ConstantExpression)expr).getValue(); Object value = ((ConstantExpression)expr).getValue();
if (value instanceof Number) if (value instanceof Number) {
return; return;
}
// Else it's boolean or a String.. // Else it's boolean or a String..
throw new RuntimeException("Value '" + expr + "' cannot be compared."); throw new RuntimeException("Value '" + expr + "' cannot be compared.");
@ -306,33 +315,26 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
public static void checkEqualOperand(Expression expr) { public static void checkEqualOperand(Expression expr) {
if (expr instanceof ConstantExpression) { if (expr instanceof ConstantExpression) {
Object value = ((ConstantExpression)expr).getValue(); Object value = ((ConstantExpression)expr).getValue();
if (value == null) if (value == null) {
throw new RuntimeException("'" + expr + "' cannot be compared."); throw new RuntimeException("'" + expr + "' cannot be compared.");
}
} }
} }
/** /**
*
* @param left * @param left
* @param right * @param right
*/ */
private static void checkEqualOperandCompatability(Expression left, Expression right) { private static void checkEqualOperandCompatability(Expression left, Expression right) {
if (left instanceof ConstantExpression && right instanceof ConstantExpression) { if (left instanceof ConstantExpression && right instanceof ConstantExpression) {
if (left instanceof BooleanExpression && !(right instanceof BooleanExpression)) if (left instanceof BooleanExpression && !(right instanceof BooleanExpression)) {
throw new RuntimeException("'" + left + "' cannot be compared with '" + right + "'"); throw new RuntimeException("'" + left + "' cannot be compared with '" + right + "'");
}
} }
} }
/**
* @param left
* @param right
*/
public ComparisonExpression(Expression left, Expression right) {
super(left, right);
}
public Object evaluate(MessageEvaluationContext message) throws JMSException { public Object evaluate(MessageEvaluationContext message) throws JMSException {
Comparable lv = (Comparable)left.evaluate(message); Comparable<Comparable> lv = (Comparable)left.evaluate(message);
if (lv == null) { if (lv == null) {
return null; return null;
} }
@ -344,8 +346,8 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
} }
protected Boolean compare(Comparable lv, Comparable rv) { protected Boolean compare(Comparable lv, Comparable rv) {
Class lc = lv.getClass(); Class<? extends Comparable> lc = lv.getClass();
Class rc = rv.getClass(); Class<? extends Comparable> rc = rv.getClass();
// If the the objects are not of the same type, // If the the objects are not of the same type,
// try to convert up to allow the comparison. // try to convert up to allow the comparison.
if (lc != rc) { if (lc != rc) {

View File

@ -47,8 +47,9 @@ public class ConstantExpression implements Expression {
public static ConstantExpression createFromDecimal(String text) { public static ConstantExpression createFromDecimal(String text) {
// Strip off the 'l' or 'L' if needed. // Strip off the 'l' or 'L' if needed.
if (text.endsWith("l") || text.endsWith("L")) if (text.endsWith("l") || text.endsWith("L")) {
text = text.substring(0, text.length() - 1); text = text.substring(0, text.length() - 1);
}
Number value; Number value;
try { try {

View File

@ -40,8 +40,9 @@ public abstract class DestinationFilter implements BooleanExpression {
public boolean matches(MessageEvaluationContext message) throws JMSException { public boolean matches(MessageEvaluationContext message) throws JMSException {
try { try {
if (message.isDropped()) if (message.isDropped()) {
return false; return false;
}
return matches(message.getMessage().getDestination()); return matches(message.getMessage().getDestination());
} catch (IOException e) { } catch (IOException e) {
throw JMSExceptionSupport.create(e); throw JMSExceptionSupport.create(e);

View File

@ -34,7 +34,7 @@ public class DestinationPath {
protected static final char SEPARATOR = '.'; protected static final char SEPARATOR = '.';
public static String[] getDestinationPaths(String subject) { public static String[] getDestinationPaths(String subject) {
List list = new ArrayList(); List<String> list = new ArrayList<String>();
int previous = 0; int previous = 0;
int lastIndex = subject.length() - 1; int lastIndex = subject.length() - 1;
while (true) { while (true) {

View File

@ -25,6 +25,14 @@ import javax.jms.JMSException;
*/ */
public abstract class LogicExpression extends BinaryExpression implements BooleanExpression { public abstract class LogicExpression extends BinaryExpression implements BooleanExpression {
/**
* @param left
* @param right
*/
public LogicExpression(BooleanExpression left, BooleanExpression right) {
super(left, right);
}
public static BooleanExpression createOR(BooleanExpression lvalue, BooleanExpression rvalue) { public static BooleanExpression createOR(BooleanExpression lvalue, BooleanExpression rvalue) {
return new LogicExpression(lvalue, rvalue) { return new LogicExpression(lvalue, rvalue) {
@ -54,8 +62,9 @@ public abstract class LogicExpression extends BinaryExpression implements Boolea
Boolean lv = (Boolean)left.evaluate(message); Boolean lv = (Boolean)left.evaluate(message);
// Can we do an AND shortcut?? // Can we do an AND shortcut??
if (lv == null) if (lv == null) {
return null; return null;
}
if (!lv.booleanValue()) { if (!lv.booleanValue()) {
return Boolean.FALSE; return Boolean.FALSE;
} }
@ -70,14 +79,6 @@ public abstract class LogicExpression extends BinaryExpression implements Boolea
}; };
} }
/**
* @param left
* @param right
*/
public LogicExpression(BooleanExpression left, BooleanExpression right) {
super(left, right);
}
public abstract Object evaluate(MessageEvaluationContext message) throws JMSException; public abstract Object evaluate(MessageEvaluationContext message) throws JMSException;
public boolean matches(MessageEvaluationContext message) throws JMSException { public boolean matches(MessageEvaluationContext message) throws JMSException {

View File

@ -20,6 +20,8 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.jms.JMSException; import javax.jms.JMSException;
@ -66,8 +68,8 @@ import javax.jms.JMSException;
*/ */
public class MultiExpressionEvaluator { public class MultiExpressionEvaluator {
HashMap rootExpressions = new HashMap(); Map<String, ExpressionListenerSet> rootExpressions = new HashMap<String, ExpressionListenerSet>();
HashMap cachedExpressions = new HashMap(); Map<Expression, CacheExpression> cachedExpressions = new HashMap<Expression, CacheExpression>();
int view; int view;
@ -104,8 +106,9 @@ public class MultiExpressionEvaluator {
} }
public boolean equals(Object o) { public boolean equals(Object o) {
if (o == null) if (o == null) {
return false; return false;
}
return ((CacheExpression)o).right.equals(right); return ((CacheExpression)o).right.equals(right);
} }
@ -125,7 +128,7 @@ public class MultiExpressionEvaluator {
*/ */
static class ExpressionListenerSet { static class ExpressionListenerSet {
Expression expression; Expression expression;
ArrayList listeners = new ArrayList(); List<ExpressionListener> listeners = new ArrayList<ExpressionListener>();
} }
/** /**
@ -142,7 +145,7 @@ public class MultiExpressionEvaluator {
* Expression applied to the evaluated message. * Expression applied to the evaluated message.
*/ */
public void addExpressionListner(Expression selector, ExpressionListener c) { public void addExpressionListner(Expression selector, ExpressionListener c) {
ExpressionListenerSet data = (ExpressionListenerSet)rootExpressions.get(selector.toString()); ExpressionListenerSet data = rootExpressions.get(selector.toString());
if (data == null) { if (data == null) {
data = new ExpressionListenerSet(); data = new ExpressionListenerSet();
data.expression = addToCache(selector); data.expression = addToCache(selector);
@ -157,19 +160,19 @@ public class MultiExpressionEvaluator {
*/ */
public boolean removeEventListner(String selector, ExpressionListener c) { public boolean removeEventListner(String selector, ExpressionListener c) {
String expKey = selector; String expKey = selector;
ExpressionListenerSet d = (ExpressionListenerSet)rootExpressions.get(expKey); ExpressionListenerSet d = rootExpressions.get(expKey);
if (d == null) // that selector had not been added. // that selector had not been added.
{ if (d == null) {
return false; return false;
} }
if (!d.listeners.remove(c)) // that selector did not have that listner.. // that selector did not have that listeners..
{ if (!d.listeners.remove(c)) {
return false; return false;
} }
// If there are no more listners for this expression.... // If there are no more listeners for this expression....
if (d.listeners.size() == 0) { if (d.listeners.size() == 0) {
// Uncache it... // Un-cache it...
removeFromCache((CacheExpression)d.expression); removeFromCache((CacheExpression)d.expression);
rootExpressions.remove(expKey); rootExpressions.remove(expKey);
} }
@ -185,7 +188,7 @@ public class MultiExpressionEvaluator {
*/ */
private CacheExpression addToCache(Expression expr) { private CacheExpression addToCache(Expression expr) {
CacheExpression n = (CacheExpression)cachedExpressions.get(expr); CacheExpression n = cachedExpressions.get(expr);
if (n == null) { if (n == null) {
n = new CacheExpression(expr); n = new CacheExpression(expr);
cachedExpressions.put(expr, n); cachedExpressions.put(expr, n);
@ -239,13 +242,13 @@ public class MultiExpressionEvaluator {
* @param message * @param message
*/ */
public void evaluate(MessageEvaluationContext message) { public void evaluate(MessageEvaluationContext message) {
Collection expressionListeners = rootExpressions.values(); Collection<ExpressionListenerSet> expressionListeners = rootExpressions.values();
for (Iterator iter = expressionListeners.iterator(); iter.hasNext();) { for (Iterator<ExpressionListenerSet> iter = expressionListeners.iterator(); iter.hasNext();) {
ExpressionListenerSet els = (ExpressionListenerSet)iter.next(); ExpressionListenerSet els = iter.next();
try { try {
Object result = els.expression.evaluate(message); Object result = els.expression.evaluate(message);
for (Iterator iterator = els.listeners.iterator(); iterator.hasNext();) { for (Iterator<ExpressionListener> iterator = els.listeners.iterator(); iterator.hasNext();) {
ExpressionListener l = (ExpressionListener)iterator.next(); ExpressionListener l = iterator.next();
l.evaluateResultEvent(els.expression, message, result); l.evaluateResultEvent(els.expression, message, result);
} }
} catch (Throwable e) { } catch (Throwable e) {

View File

@ -27,13 +27,14 @@ public class NoLocalExpression implements BooleanExpression {
private final String connectionId; private final String connectionId;
public NoLocalExpression(String connectionId) { public NoLocalExpression(String connectionId) {
this.connectionId = connectionId; this.connectionId = connectionId;
} }
public boolean matches(MessageEvaluationContext message) throws JMSException { public boolean matches(MessageEvaluationContext message) throws JMSException {
try { try {
if( message.isDropped() ) if (message.isDropped()) {
return false; return false;
}
return !connectionId.equals(message.getMessage().getMessageId().getProducerId().getConnectionId()); return !connectionId.equals(message.getMessage().getMessageId().getProducerId().getConnectionId());
} catch (IOException e) { } catch (IOException e) {
throw JMSExceptionSupport.create(e); throw JMSExceptionSupport.create(e);

View File

@ -19,6 +19,7 @@ package org.apache.activemq.filter;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map;
import javax.jms.DeliveryMode; import javax.jms.DeliveryMode;
import javax.jms.JMSException; import javax.jms.JMSException;
@ -35,28 +36,32 @@ import org.apache.activemq.util.JMSExceptionSupport;
*/ */
public class PropertyExpression implements Expression { public class PropertyExpression implements Expression {
private static final Map<String, SubExpression> JMS_PROPERTY_EXPRESSIONS = new HashMap<String, SubExpression>();
interface SubExpression { interface SubExpression {
Object evaluate(Message message); Object evaluate(Message message);
} }
private static final HashMap JMS_PROPERTY_EXPRESSIONS = new HashMap();
static { static {
JMS_PROPERTY_EXPRESSIONS.put("JMSDestination", new SubExpression() { JMS_PROPERTY_EXPRESSIONS.put("JMSDestination", new SubExpression() {
public Object evaluate(Message message) { public Object evaluate(Message message) {
ActiveMQDestination dest = message.getOriginalDestination(); ActiveMQDestination dest = message.getOriginalDestination();
if (dest == null) if (dest == null) {
dest = message.getDestination(); dest = message.getDestination();
if (dest == null) }
if (dest == null) {
return null; return null;
}
return dest.toString(); return dest.toString();
} }
}); });
JMS_PROPERTY_EXPRESSIONS.put("JMSReplyTo", new SubExpression() { JMS_PROPERTY_EXPRESSIONS.put("JMSReplyTo", new SubExpression() {
public Object evaluate(Message message) { public Object evaluate(Message message) {
if (message.getReplyTo() == null) if (message.getReplyTo() == null) {
return null; return null;
}
return message.getReplyTo().toString(); return message.getReplyTo().toString();
} }
}); });
@ -69,8 +74,7 @@ public class PropertyExpression implements Expression {
JMS_PROPERTY_EXPRESSIONS.put("JMSDeliveryMode", new SubExpression() { JMS_PROPERTY_EXPRESSIONS.put("JMSDeliveryMode", new SubExpression() {
public Object evaluate(Message message) { public Object evaluate(Message message) {
return Integer.valueOf(message.isPersistent() return Integer.valueOf(message.isPersistent() ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
} }
}); });
JMS_PROPERTY_EXPRESSIONS.put("JMSPriority", new SubExpression() { JMS_PROPERTY_EXPRESSIONS.put("JMSPriority", new SubExpression() {
@ -82,8 +86,9 @@ public class PropertyExpression implements Expression {
JMS_PROPERTY_EXPRESSIONS.put("JMSMessageID", new SubExpression() { JMS_PROPERTY_EXPRESSIONS.put("JMSMessageID", new SubExpression() {
public Object evaluate(Message message) { public Object evaluate(Message message) {
if (message.getMessageId() == null) if (message.getMessageId() == null) {
return null; return null;
}
return message.getMessageId().toString(); return message.getMessageId().toString();
} }
}); });
@ -133,10 +138,12 @@ public class PropertyExpression implements Expression {
public Object evaluate(Message message) { public Object evaluate(Message message) {
TransactionId txId = message.getOriginalTransactionId(); TransactionId txId = message.getOriginalTransactionId();
if (txId == null) if (txId == null) {
txId = message.getTransactionId(); txId = message.getTransactionId();
if (txId == null) }
if (txId == null) {
return null; return null;
}
return new Integer(txId.toString()); return new Integer(txId.toString());
} }
}); });
@ -159,21 +166,22 @@ public class PropertyExpression implements Expression {
public PropertyExpression(String name) { public PropertyExpression(String name) {
this.name = name; this.name = name;
jmsPropertyExpression = (SubExpression)JMS_PROPERTY_EXPRESSIONS.get(name); jmsPropertyExpression = JMS_PROPERTY_EXPRESSIONS.get(name);
} }
public Object evaluate(MessageEvaluationContext message) throws JMSException { public Object evaluate(MessageEvaluationContext message) throws JMSException {
try { try {
if (message.isDropped()) if (message.isDropped()) {
return null; return null;
}
if (jmsPropertyExpression != null) if (jmsPropertyExpression != null) {
return jmsPropertyExpression.evaluate(message.getMessage()); return jmsPropertyExpression.evaluate(message.getMessage());
}
try { try {
return message.getMessage().getProperty(name); return message.getMessage().getProperty(name);
} catch (IOException ioe) { } catch (IOException ioe) {
throw JMSExceptionSupport.create("Could not get property: " + name + " reason: " throw JMSExceptionSupport.create("Could not get property: " + name + " reason: " + ioe.getMessage(), ioe);
+ ioe.getMessage(), ioe);
} }
} catch (IOException e) { } catch (IOException e) {
throw JMSExceptionSupport.create(e); throw JMSExceptionSupport.create(e);
@ -182,8 +190,9 @@ public class PropertyExpression implements Expression {
} }
public Object evaluate(Message message) throws JMSException { public Object evaluate(Message message) throws JMSException {
if (jmsPropertyExpression != null) if (jmsPropertyExpression != null) {
return jmsPropertyExpression.evaluate(message); return jmsPropertyExpression.evaluate(message);
}
try { try {
return message.getProperty(name); return message.getProperty(name);
} catch (IOException ioe) { } catch (IOException ioe) {

View File

@ -34,6 +34,10 @@ public abstract class UnaryExpression implements Expression {
private static final BigDecimal BD_LONG_MIN_VALUE = BigDecimal.valueOf(Long.MIN_VALUE); private static final BigDecimal BD_LONG_MIN_VALUE = BigDecimal.valueOf(Long.MIN_VALUE);
protected Expression right; protected Expression right;
public UnaryExpression(Expression left) {
this.right = left;
}
public static Expression createNegate(Expression left) { public static Expression createNegate(Expression left) {
return new UnaryExpression(left) { return new UnaryExpression(left) {
public Object evaluate(MessageEvaluationContext message) throws JMSException { public Object evaluate(MessageEvaluationContext message) throws JMSException {
@ -53,17 +57,16 @@ public abstract class UnaryExpression implements Expression {
}; };
} }
public static BooleanExpression createInExpression(PropertyExpression right, List elements, public static BooleanExpression createInExpression(PropertyExpression right, List<Object> elements, final boolean not) {
final boolean not) {
// Use a HashSet if there are many elements. // Use a HashSet if there are many elements.
Collection t; Collection<Object> t;
if (elements.size() == 0) if (elements.size() == 0) {
t = null; t = null;
else if (elements.size() < 5) } else if (elements.size() < 5) {
t = elements; t = elements;
else { } else {
t = new HashSet(elements); t = new HashSet<Object>(elements);
} }
final Collection inList = t; final Collection inList = t;
@ -74,8 +77,9 @@ public abstract class UnaryExpression implements Expression {
if (rvalue == null) { if (rvalue == null) {
return null; return null;
} }
if (rvalue.getClass() != String.class) if (rvalue.getClass() != String.class) {
return null; return null;
}
if ((inList != null && inList.contains(rvalue)) ^ not) { if ((inList != null && inList.contains(rvalue)) ^ not) {
return Boolean.TRUE; return Boolean.TRUE;
@ -155,10 +159,12 @@ public abstract class UnaryExpression implements Expression {
return new BooleanUnaryExpression(left) { return new BooleanUnaryExpression(left) {
public Object evaluate(MessageEvaluationContext message) throws JMSException { public Object evaluate(MessageEvaluationContext message) throws JMSException {
Object rvalue = right.evaluate(message); Object rvalue = right.evaluate(message);
if (rvalue == null) if (rvalue == null) {
return null; return null;
if (!rvalue.getClass().equals(Boolean.class)) }
if (!rvalue.getClass().equals(Boolean.class)) {
return Boolean.FALSE; return Boolean.FALSE;
}
return ((Boolean)rvalue).booleanValue() ? Boolean.TRUE : Boolean.FALSE; return ((Boolean)rvalue).booleanValue() ? Boolean.TRUE : Boolean.FALSE;
} }
@ -202,10 +208,6 @@ public abstract class UnaryExpression implements Expression {
} }
} }
public UnaryExpression(Expression left) {
this.right = left;
}
public Expression getRight() { public Expression getRight() {
return right; return right;
} }

View File

@ -45,8 +45,7 @@ public final class XPathExpression implements BooleanExpression {
try { try {
m = getXPathEvaluatorConstructor(cn); m = getXPathEvaluatorConstructor(cn);
} catch (Throwable e) { } catch (Throwable e) {
LOG.warn("Invalid " + XPathEvaluator.class.getName() + " implementation: " + cn LOG.warn("Invalid " + XPathEvaluator.class.getName() + " implementation: " + cn + ", reason: " + e, e);
+ ", reason: " + e, e);
cn = DEFAULT_EVALUATOR_CLASS_NAME; cn = DEFAULT_EVALUATOR_CLASS_NAME;
try { try {
m = getXPathEvaluatorConstructor(cn); m = getXPathEvaluatorConstructor(cn);
@ -59,15 +58,6 @@ public final class XPathExpression implements BooleanExpression {
} }
} }
private static Constructor getXPathEvaluatorConstructor(String cn) throws ClassNotFoundException,
SecurityException, NoSuchMethodException {
Class c = XPathExpression.class.getClassLoader().loadClass(cn);
if (!XPathEvaluator.class.isAssignableFrom(c)) {
throw new ClassCastException("" + c + " is not an instance of " + XPathEvaluator.class);
}
return c.getConstructor(new Class[] {String.class});
}
private final String xpath; private final String xpath;
private final XPathEvaluator evaluator; private final XPathEvaluator evaluator;
@ -80,6 +70,14 @@ public final class XPathExpression implements BooleanExpression {
this.evaluator = createEvaluator(xpath); this.evaluator = createEvaluator(xpath);
} }
private static Constructor getXPathEvaluatorConstructor(String cn) throws ClassNotFoundException, SecurityException, NoSuchMethodException {
Class c = XPathExpression.class.getClassLoader().loadClass(cn);
if (!XPathEvaluator.class.isAssignableFrom(c)) {
throw new ClassCastException("" + c + " is not an instance of " + XPathEvaluator.class);
}
return c.getConstructor(new Class[] {String.class});
}
private XPathEvaluator createEvaluator(String xpath2) { private XPathEvaluator createEvaluator(String xpath2) {
try { try {
return (XPathEvaluator)EVALUATOR_CONSTRUCTOR.newInstance(new Object[] {xpath}); return (XPathEvaluator)EVALUATOR_CONSTRUCTOR.newInstance(new Object[] {xpath});
@ -96,8 +94,9 @@ public final class XPathExpression implements BooleanExpression {
public Object evaluate(MessageEvaluationContext message) throws JMSException { public Object evaluate(MessageEvaluationContext message) throws JMSException {
try { try {
if (message.isDropped()) if (message.isDropped()) {
return null; return null;
}
return evaluator.evaluate(message.getMessage()) ? Boolean.TRUE : Boolean.FALSE; return evaluator.evaluate(message.getMessage()) ? Boolean.TRUE : Boolean.FALSE;
} catch (IOException e) { } catch (IOException e) {
throw JMSExceptionSupport.create(e); throw JMSExceptionSupport.create(e);

View File

@ -25,15 +25,14 @@ import javax.jms.TextMessage;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.traversal.NodeIterator;
import org.xml.sax.InputSource;
import org.apache.activemq.command.Message; import org.apache.activemq.command.Message;
import org.apache.activemq.util.ByteArrayInputStream; import org.apache.activemq.util.ByteArrayInputStream;
import org.apache.xpath.CachedXPathAPI; import org.apache.xpath.CachedXPathAPI;
import org.xml.sax.InputSource;
import org.w3c.dom.Document;
import org.w3c.dom.traversal.NodeIterator;
public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator { public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator {
private final String xpath; private final String xpath;

View File

@ -65,37 +65,37 @@ public class ReadOnlyContext implements Context, Serializable {
protected static final NameParser NAME_PARSER = new NameParserImpl(); protected static final NameParser NAME_PARSER = new NameParserImpl();
private static final long serialVersionUID = -5754338187296859149L; private static final long serialVersionUID = -5754338187296859149L;
protected final Hashtable environment; // environment for this context protected final Hashtable<String, Object> environment; // environment for this context
protected final Map bindings; // bindings at my level protected final Map<String, Object> bindings; // bindings at my level
protected final Map treeBindings; // all bindings under me protected final Map<String, Object> treeBindings; // all bindings under me
private boolean frozen; private boolean frozen;
private String nameInNamespace = ""; private String nameInNamespace = "";
public ReadOnlyContext() { public ReadOnlyContext() {
environment = new Hashtable(); environment = new Hashtable<String, Object>();
bindings = new HashMap(); bindings = new HashMap<String, Object>();
treeBindings = new HashMap(); treeBindings = new HashMap<String, Object>();
} }
public ReadOnlyContext(Hashtable env) { public ReadOnlyContext(Hashtable env) {
if (env == null) { if (env == null) {
this.environment = new Hashtable(); this.environment = new Hashtable<String, Object>();
} else { } else {
this.environment = new Hashtable(env); this.environment = new Hashtable<String, Object>(env);
} }
this.bindings = Collections.EMPTY_MAP; this.bindings = Collections.EMPTY_MAP;
this.treeBindings = Collections.EMPTY_MAP; this.treeBindings = Collections.EMPTY_MAP;
} }
public ReadOnlyContext(Hashtable environment, Map bindings) { public ReadOnlyContext(Hashtable environment, Map<String, Object> bindings) {
if (environment == null) { if (environment == null) {
this.environment = new Hashtable(); this.environment = new Hashtable<String, Object>();
} else { } else {
this.environment = new Hashtable(environment); this.environment = new Hashtable<String, Object>(environment);
} }
this.bindings = bindings; this.bindings = bindings;
treeBindings = new HashMap(); treeBindings = new HashMap<String, Object>();
frozen = true; frozen = true;
} }
@ -107,10 +107,10 @@ public class ReadOnlyContext implements Context, Serializable {
protected ReadOnlyContext(ReadOnlyContext clone, Hashtable env) { protected ReadOnlyContext(ReadOnlyContext clone, Hashtable env) {
this.bindings = clone.bindings; this.bindings = clone.bindings;
this.treeBindings = clone.treeBindings; this.treeBindings = clone.treeBindings;
this.environment = new Hashtable(env); this.environment = new Hashtable<String, Object>(env);
} }
protected ReadOnlyContext(ReadOnlyContext clone, Hashtable env, String nameInNamespace) { protected ReadOnlyContext(ReadOnlyContext clone, Hashtable<String, Object> env, String nameInNamespace) {
this(clone, env); this(clone, env);
this.nameInNamespace = nameInNamespace; this.nameInNamespace = nameInNamespace;
} }
@ -138,11 +138,11 @@ public class ReadOnlyContext implements Context, Serializable {
* @return * @return
* @throws javax.naming.NamingException * @throws javax.naming.NamingException
*/ */
protected Map internalBind(String name, Object value) throws NamingException { protected Map<String, Object> internalBind(String name, Object value) throws NamingException {
assert name != null && name.length() > 0; assert name != null && name.length() > 0;
assert !frozen; assert !frozen;
Map newBindings = new HashMap(); Map<String, Object> newBindings = new HashMap<String, Object>();
int pos = name.indexOf('/'); int pos = name.indexOf('/');
if (pos == -1) { if (pos == -1) {
if (treeBindings.put(name, value) != null) { if (treeBindings.put(name, value) != null) {
@ -165,7 +165,7 @@ public class ReadOnlyContext implements Context, Serializable {
} }
ReadOnlyContext readOnlyContext = (ReadOnlyContext)o; ReadOnlyContext readOnlyContext = (ReadOnlyContext)o;
String remainder = name.substring(pos + 1); String remainder = name.substring(pos + 1);
Map subBindings = readOnlyContext.internalBind(remainder, value); Map<String, Object> subBindings = readOnlyContext.internalBind(remainder, value);
for (Iterator iterator = subBindings.entrySet().iterator(); iterator.hasNext();) { for (Iterator iterator = subBindings.entrySet().iterator(); iterator.hasNext();) {
Map.Entry entry = (Map.Entry)iterator.next(); Map.Entry entry = (Map.Entry)iterator.next();
String subName = segment + "/" + (String)entry.getKey(); String subName = segment + "/" + (String)entry.getKey();
@ -185,8 +185,8 @@ public class ReadOnlyContext implements Context, Serializable {
return environment.put(propName, propVal); return environment.put(propName, propVal);
} }
public Hashtable getEnvironment() throws NamingException { public Hashtable<String, Object> getEnvironment() throws NamingException {
return (Hashtable)environment.clone(); return (Hashtable<String, Object>)environment.clone();
} }
public Object removeFromEnvironment(String propName) throws NamingException { public Object removeFromEnvironment(String propName) throws NamingException {

View File

@ -40,13 +40,15 @@ import org.apache.commons.logging.LogFactory;
*/ */
class IndexRootContainer { class IndexRootContainer {
private static final Log LOG = LogFactory.getLog(IndexRootContainer.class);
protected static final Marshaller ROOT_MARSHALLER = Store.OBJECT_MARSHALLER; protected static final Marshaller ROOT_MARSHALLER = Store.OBJECT_MARSHALLER;
private static final Log LOG = LogFactory.getLog(IndexRootContainer.class);
protected IndexItem root; protected IndexItem root;
protected IndexManager indexManager; protected IndexManager indexManager;
protected DataManager dataManager; protected DataManager dataManager;
protected Map map = new ConcurrentHashMap(); protected Map<Object, StoreEntry> map = new ConcurrentHashMap<Object, StoreEntry>();
protected LinkedList list = new LinkedList(); protected LinkedList<StoreEntry> list = new LinkedList<StoreEntry>();
IndexRootContainer(IndexItem root, IndexManager im, DataManager dfm) throws IOException { IndexRootContainer(IndexItem root, IndexManager im, DataManager dfm) throws IOException {
this.root = root; this.root = root;
@ -64,7 +66,7 @@ class IndexRootContainer {
} }
} }
Set getKeys() { Set<Object> getKeys() {
return map.keySet(); return map.keySet();
} }
@ -93,7 +95,7 @@ class IndexRootContainer {
} }
void removeRoot(IndexManager containerIndexManager, ContainerId key) throws IOException { void removeRoot(IndexManager containerIndexManager, ContainerId key) throws IOException {
StoreEntry oldRoot = (StoreEntry)map.remove(key); StoreEntry oldRoot = map.remove(key);
if (oldRoot != null) { if (oldRoot != null) {
dataManager.removeInterestInFile(oldRoot.getKeyFile()); dataManager.removeInterestInFile(oldRoot.getKeyFile());
// get the container root // get the container root
@ -119,7 +121,7 @@ class IndexRootContainer {
} }
IndexItem getRoot(IndexManager containerIndexManager, ContainerId key) throws IOException { IndexItem getRoot(IndexManager containerIndexManager, ContainerId key) throws IOException {
StoreEntry index = (StoreEntry)map.get(key); StoreEntry index = map.get(key);
if (index != null) { if (index != null) {
return containerIndexManager.getIndex(index.getValueOffset()); return containerIndexManager.getIndex(index.getValueOffset());
} }

View File

@ -30,7 +30,6 @@ import java.util.concurrent.ConcurrentHashMap;
import org.apache.activemq.kaha.ContainerId; import org.apache.activemq.kaha.ContainerId;
import org.apache.activemq.kaha.ListContainer; import org.apache.activemq.kaha.ListContainer;
import org.apache.activemq.kaha.MapContainer; import org.apache.activemq.kaha.MapContainer;
import org.apache.activemq.kaha.RuntimeStoreException;
import org.apache.activemq.kaha.Store; import org.apache.activemq.kaha.Store;
import org.apache.activemq.kaha.StoreLocation; import org.apache.activemq.kaha.StoreLocation;
import org.apache.activemq.kaha.impl.async.AsyncDataManager; import org.apache.activemq.kaha.impl.async.AsyncDataManager;
@ -58,7 +57,7 @@ public class KahaStore implements Store {
private static final boolean DISABLE_LOCKING = "true".equals(System.getProperty(PROPERTY_PREFIX + ".DisableLocking", "false")); private static final boolean DISABLE_LOCKING = "true".equals(System.getProperty(PROPERTY_PREFIX + ".DisableLocking", "false"));
private static final Log LOG = LogFactory.getLog(KahaStore.class); private static final Log LOG = LogFactory.getLog(KahaStore.class);
private final File directory; private final File directory;
private final String mode; private final String mode;
private IndexRootContainer mapsContainer; private IndexRootContainer mapsContainer;
@ -74,7 +73,7 @@ public class KahaStore implements Store {
private boolean useAsyncDataManager; private boolean useAsyncDataManager;
private long maxDataFileLength = 1024 * 1024 * 32; private long maxDataFileLength = 1024 * 1024 * 32;
private FileLock lock; private FileLock lock;
private boolean persistentIndex; private boolean persistentIndex=true;
private RandomAccessFile lockFile; private RandomAccessFile lockFile;
public KahaStore(String name, String mode) throws IOException { public KahaStore(String name, String mode) throws IOException {
@ -108,8 +107,9 @@ public class KahaStore implements Store {
iter.remove(); iter.remove();
} }
} }
if (lockFile != null) if (lockFile != null) {
lockFile.close(); lockFile.close();
}
} }
} }
@ -415,8 +415,9 @@ public class KahaStore implements Store {
} }
public synchronized void initialize() throws IOException { public synchronized void initialize() throws IOException {
if (closed) if (closed) {
throw new IOException("Store has been closed."); throw new IOException("Store has been closed.");
}
if (!initialized) { if (!initialized) {
LOG.info("Kaha Store using data directory " + directory); LOG.info("Kaha Store using data directory " + directory);
@ -486,12 +487,6 @@ public class KahaStore implements Store {
return getClass().getName() + ".lock." + directory.getCanonicalPath(); return getClass().getName() + ".lock." + directory.getCanonicalPath();
} }
private void checkClosed() {
if (closed) {
throw new RuntimeStoreException("The store is closed");
}
}
/** /**
* scans the directory and builds up the IndexManager and DataManager * scans the directory and builds up the IndexManager and DataManager
* *

View File

@ -48,10 +48,7 @@ import org.apache.commons.logging.LogFactory;
*/ */
public final class AsyncDataManager { public final class AsyncDataManager {
private static final Log LOG = LogFactory.getLog(AsyncDataManager.class);
public static final int CONTROL_RECORD_MAX_LENGTH = 1024; public static final int CONTROL_RECORD_MAX_LENGTH = 1024;
public static final int ITEM_HEAD_RESERVED_SPACE = 21; public static final int ITEM_HEAD_RESERVED_SPACE = 21;
// ITEM_HEAD_SPACE = length + type+ reserved space + SOR // ITEM_HEAD_SPACE = length + type+ reserved space + SOR
public static final int ITEM_HEAD_SPACE = 4 + 1 + ITEM_HEAD_RESERVED_SPACE + 3; public static final int ITEM_HEAD_SPACE = 4 + 1 + ITEM_HEAD_RESERVED_SPACE + 3;
@ -60,8 +57,8 @@ public final class AsyncDataManager {
public static final int ITEM_HEAD_FOOT_SPACE = ITEM_HEAD_SPACE + ITEM_FOOT_SPACE; public static final int ITEM_HEAD_FOOT_SPACE = ITEM_HEAD_SPACE + ITEM_FOOT_SPACE;
static final byte[] ITEM_HEAD_SOR = new byte[] {'S', 'O', 'R'}; // public static final byte[] ITEM_HEAD_SOR = new byte[] {'S', 'O', 'R'}; //
static final byte[] ITEM_HEAD_EOR = new byte[] {'E', 'O', 'R'}; // public static final byte[] ITEM_HEAD_EOR = new byte[] {'E', 'O', 'R'}; //
public static final byte DATA_ITEM_TYPE = 1; public static final byte DATA_ITEM_TYPE = 1;
public static final byte REDO_ITEM_TYPE = 2; public static final byte REDO_ITEM_TYPE = 2;
@ -70,8 +67,16 @@ public final class AsyncDataManager {
public static final String DEFAULT_FILE_PREFIX = "data-"; public static final String DEFAULT_FILE_PREFIX = "data-";
public static final int DEFAULT_MAX_FILE_LENGTH = 1024 * 1024 * 32; public static final int DEFAULT_MAX_FILE_LENGTH = 1024 * 1024 * 32;
private static final Log LOG = LogFactory.getLog(AsyncDataManager.class);
protected final Map<WriteKey, WriteCommand> inflightWrites = new ConcurrentHashMap<WriteKey, WriteCommand>();
File directory = new File(DEFAULT_DIRECTORY); File directory = new File(DEFAULT_DIRECTORY);
String filePrefix = DEFAULT_FILE_PREFIX; String filePrefix = DEFAULT_FILE_PREFIX;
ControlFile controlFile;
boolean started;
boolean useNio = true;
private int maxFileLength = DEFAULT_MAX_FILE_LENGTH; private int maxFileLength = DEFAULT_MAX_FILE_LENGTH;
private int preferedFileLength = DEFAULT_MAX_FILE_LENGTH - 1024 * 512; private int preferedFileLength = DEFAULT_MAX_FILE_LENGTH - 1024 * 512;
@ -80,15 +85,9 @@ public final class AsyncDataManager {
private Map<Integer, DataFile> fileMap = new HashMap<Integer, DataFile>(); private Map<Integer, DataFile> fileMap = new HashMap<Integer, DataFile>();
private DataFile currentWriteFile; private DataFile currentWriteFile;
ControlFile controlFile;
private Location mark; private Location mark;
private final AtomicReference<Location> lastAppendLocation = new AtomicReference<Location>(); private final AtomicReference<Location> lastAppendLocation = new AtomicReference<Location>();
boolean started;
boolean useNio = true;
protected final ConcurrentHashMap<WriteKey, WriteCommand> inflightWrites = new ConcurrentHashMap<WriteKey, WriteCommand>();
private Runnable cleanupTask; private Runnable cleanupTask;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -130,13 +129,13 @@ public final class AsyncDataManager {
DataFile dataFile = new DataFile(file, num, preferedFileLength); DataFile dataFile = new DataFile(file, num, preferedFileLength);
fileMap.put(dataFile.getDataFileId(), dataFile); fileMap.put(dataFile.getDataFileId(), dataFile);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
// Ignore file that do not match the patern. // Ignore file that do not match the pattern.
} }
} }
// Sort the list so that we can link the DataFiles together in the // Sort the list so that we can link the DataFiles together in the
// right order. // right order.
ArrayList<DataFile> l = new ArrayList<DataFile>(fileMap.values()); List<DataFile> l = new ArrayList<DataFile>(fileMap.values());
Collections.sort(l); Collections.sort(l);
currentWriteFile = null; currentWriteFile = null;
for (DataFile df : l) { for (DataFile df : l) {
@ -534,7 +533,7 @@ public final class AsyncDataManager {
this.filePrefix = filePrefix; this.filePrefix = filePrefix;
} }
public ConcurrentHashMap<WriteKey, WriteCommand> getInflightWrites() { public Map<WriteKey, WriteCommand> getInflightWrites() {
return inflightWrites; return inflightWrites;
} }

View File

@ -56,8 +56,9 @@ public final class ControlFile {
* @throws IOException * @throws IOException
*/ */
public void lock() throws IOException { public void lock() throws IOException {
if (DISABLE_FILE_LOCK) if (DISABLE_FILE_LOCK) {
return; return;
}
if (lock == null) { if (lock == null) {
lock = randomAccessFile.getChannel().tryLock(); lock = randomAccessFile.getChannel().tryLock();
@ -73,8 +74,9 @@ public final class ControlFile {
* @throws IOException * @throws IOException
*/ */
public void unlock() throws IOException { public void unlock() throws IOException {
if (DISABLE_FILE_LOCK) if (DISABLE_FILE_LOCK) {
return; return;
}
if (lock != null) { if (lock != null) {
lock.release(); lock.release();
@ -83,16 +85,17 @@ public final class ControlFile {
} }
public void dispose() { public void dispose() {
if (disposed) if (disposed) {
return; return;
}
disposed = true; disposed = true;
try { try {
unlock(); unlock();
} catch (IOException e) { } catch (IOException ignore) {
} }
try { try {
randomAccessFile.close(); randomAccessFile.close();
} catch (IOException e) { } catch (IOException ignore) {
} }
} }

View File

@ -33,7 +33,7 @@ class DataFile extends LinkedNode implements Comparable<DataFile> {
private final Integer dataFileId; private final Integer dataFileId;
private final int preferedSize; private final int preferedSize;
int length; private int length;
private int referenceCount; private int referenceCount;
DataFile(File file, int number, int preferedSize) { DataFile(File file, int number, int preferedSize) {

View File

@ -18,6 +18,7 @@ package org.apache.activemq.kaha.impl.async;
import java.io.IOException; import java.io.IOException;
import java.io.RandomAccessFile; import java.io.RandomAccessFile;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import org.apache.activemq.kaha.impl.async.DataFileAppender.WriteCommand; import org.apache.activemq.kaha.impl.async.DataFileAppender.WriteCommand;
@ -33,7 +34,7 @@ import org.apache.activemq.util.ByteSequence;
final class DataFileAccessor { final class DataFileAccessor {
private final DataFile dataFile; private final DataFile dataFile;
private final ConcurrentHashMap<WriteKey, WriteCommand> inflightWrites; private final Map<WriteKey, WriteCommand> inflightWrites;
private final RandomAccessFile file; private final RandomAccessFile file;
private boolean disposed; private boolean disposed;
@ -54,8 +55,9 @@ final class DataFileAccessor {
} }
public void dispose() { public void dispose() {
if (disposed) if (disposed) {
return; return;
}
disposed = true; disposed = true;
try { try {
dataFile.closeRandomAccessFile(file); dataFile.closeRandomAccessFile(file);
@ -66,8 +68,9 @@ final class DataFileAccessor {
public ByteSequence readRecord(Location location) throws IOException { public ByteSequence readRecord(Location location) throws IOException {
if (!location.isValid()) if (!location.isValid()) {
throw new IOException("Invalid location: " + location); throw new IOException("Invalid location: " + location);
}
WriteCommand asyncWrite = (WriteCommand)inflightWrites.get(new WriteKey(location)); WriteCommand asyncWrite = (WriteCommand)inflightWrites.get(new WriteKey(location));
if (asyncWrite != null) { if (asyncWrite != null) {

View File

@ -20,6 +20,8 @@ import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.Map;
/** /**
* Used to pool DataFileAccessors. * Used to pool DataFileAccessors.
@ -29,15 +31,14 @@ import java.util.Iterator;
public class DataFileAccessorPool { public class DataFileAccessorPool {
private final AsyncDataManager dataManager; private final AsyncDataManager dataManager;
private final HashMap<Integer, Pool> pools = new HashMap<Integer, Pool>(); private final Map<Integer, Pool> pools = new HashMap<Integer, Pool>();
private boolean closed; private boolean closed;
private int maxOpenReadersPerFile = 5;
int maxOpenReadersPerFile = 5;
class Pool { class Pool {
private final DataFile file; private final DataFile file;
private final ArrayList<DataFileAccessor> pool = new ArrayList<DataFileAccessor>(); private final List<DataFileAccessor> pool = new ArrayList<DataFileAccessor>();
private boolean used; private boolean used;
private int openCounter; private int openCounter;
private boolean disposed; private boolean disposed;
@ -149,8 +150,9 @@ public class DataFileAccessorPool {
} }
public synchronized void close() { public synchronized void close() {
if (closed) if (closed) {
return; return;
}
closed = true; closed = true;
for (Iterator<Pool> iter = pools.values().iterator(); iter.hasNext();) { for (Iterator<Pool> iter = pools.values().iterator(); iter.hasNext();) {
Pool pool = iter.next(); Pool pool = iter.next();

View File

@ -19,6 +19,7 @@ package org.apache.activemq.kaha.impl.async;
import java.io.IOException; import java.io.IOException;
import java.io.InterruptedIOException; import java.io.InterruptedIOException;
import java.io.RandomAccessFile; import java.io.RandomAccessFile;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
@ -37,7 +38,19 @@ class DataFileAppender {
protected static final byte[] RESERVED_SPACE = new byte[AsyncDataManager.ITEM_HEAD_RESERVED_SPACE]; protected static final byte[] RESERVED_SPACE = new byte[AsyncDataManager.ITEM_HEAD_RESERVED_SPACE];
protected static final String SHUTDOWN_COMMAND = "SHUTDOWN"; protected static final String SHUTDOWN_COMMAND = "SHUTDOWN";
int maxWriteBatchSize = 1024 * 1024 * 4;
protected final AsyncDataManager dataManager;
protected final Map<WriteKey, WriteCommand> inflightWrites;
protected final Object enqueueMutex = new Object();
protected WriteBatch nextWriteBatch;
protected boolean shutdown;
protected IOException firstAsyncException;
protected final CountDownLatch shutdownDone = new CountDownLatch(1);
protected int maxWriteBatchSize = 1024 * 1024 * 4;
private boolean running;
private Thread thread;
public static class WriteKey { public static class WriteKey {
private final int file; private final int file;
@ -78,10 +91,12 @@ class DataFileAppender {
} }
public boolean canAppend(DataFile dataFile, WriteCommand write) { public boolean canAppend(DataFile dataFile, WriteCommand write) {
if (dataFile != this.dataFile) if (dataFile != this.dataFile) {
return false; return false;
if (size + write.location.getSize() >= maxWriteBatchSize) }
if (size + write.location.getSize() >= maxWriteBatchSize) {
return false; return false;
}
return true; return true;
} }
@ -103,18 +118,6 @@ class DataFileAppender {
} }
} }
protected final AsyncDataManager dataManager;
protected final ConcurrentHashMap<WriteKey, WriteCommand> inflightWrites;
protected final Object enqueueMutex = new Object();
protected WriteBatch nextWriteBatch;
private boolean running;
protected boolean shutdown;
protected IOException firstAsyncException;
protected final CountDownLatch shutdownDone = new CountDownLatch(1);
private Thread thread;
/** /**
* Construct a Store writer * Construct a Store writer
@ -180,8 +183,9 @@ class DataFileAppender {
if (shutdown) { if (shutdown) {
throw new IOException("Async Writter Thread Shutdown"); throw new IOException("Async Writter Thread Shutdown");
} }
if (firstAsyncException != null) if (firstAsyncException != null) {
throw firstAsyncException; throw firstAsyncException;
}
if (!running) { if (!running) {
running = true; running = true;
@ -368,7 +372,7 @@ class DataFileAppender {
if (file != null) { if (file != null) {
dataFile.closeRandomAccessFile(file); dataFile.closeRandomAccessFile(file);
} }
} catch (IOException e) { } catch (Throwable ignore) {
} }
shutdownDone.countDown(); shutdownDone.countDown();
} }

View File

@ -32,6 +32,12 @@ import org.apache.activemq.util.DataByteArrayOutputStream;
*/ */
public final class DataManagerFacade implements org.apache.activemq.kaha.impl.DataManager { public final class DataManagerFacade implements org.apache.activemq.kaha.impl.DataManager {
private static final ByteSequence FORCE_COMMAND = new ByteSequence(new byte[] {'F', 'O', 'R', 'C', 'E'});
private AsyncDataManager dataManager;
private final String name;
private Marshaller redoMarshaller;
private static class StoreLocationFacade implements StoreLocation { private static class StoreLocationFacade implements StoreLocation {
private final Location location; private final Location location;
@ -56,19 +62,27 @@ public final class DataManagerFacade implements org.apache.activemq.kaha.impl.Da
} }
} }
public DataManagerFacade(AsyncDataManager dataManager, String name) {
this.dataManager = dataManager;
this.name = name;
}
private static StoreLocation convertToStoreLocation(Location location) { private static StoreLocation convertToStoreLocation(Location location) {
if (location == null) if (location == null) {
return null; return null;
}
return new StoreLocationFacade(location); return new StoreLocationFacade(location);
} }
private static Location convertFromStoreLocation(StoreLocation location) { private static Location convertFromStoreLocation(StoreLocation location) {
if (location == null) if (location == null) {
return null; return null;
}
if (location.getClass() == StoreLocationFacade.class) if (location.getClass() == StoreLocationFacade.class) {
return ((StoreLocationFacade)location).getLocation(); return ((StoreLocationFacade)location).getLocation();
}
Location l = new Location(); Location l = new Location();
l.setOffset((int)location.getOffset()); l.setOffset((int)location.getOffset());
@ -77,16 +91,6 @@ public final class DataManagerFacade implements org.apache.activemq.kaha.impl.Da
return l; return l;
} }
private static final ByteSequence FORCE_COMMAND = new ByteSequence(new byte[] {'F', 'O', 'R', 'C', 'E'});
AsyncDataManager dataManager;
private final String name;
private Marshaller redoMarshaller;
public DataManagerFacade(AsyncDataManager dataManager, String name) {
this.dataManager = dataManager;
this.name = name;
}
public Object readItem(Marshaller marshaller, StoreLocation location) throws IOException { public Object readItem(Marshaller marshaller, StoreLocation location) throws IOException {
ByteSequence sequence = dataManager.read(convertFromStoreLocation(location)); ByteSequence sequence = dataManager.read(convertFromStoreLocation(location));

View File

@ -33,6 +33,8 @@ import org.apache.activemq.util.ByteSequence;
*/ */
public final class JournalFacade implements Journal { public final class JournalFacade implements Journal {
private final AsyncDataManager dataManager;
public static class RecordLocationFacade implements RecordLocation { public static class RecordLocationFacade implements RecordLocation {
private final Location location; private final Location location;
@ -51,26 +53,26 @@ public final class JournalFacade implements Journal {
} }
} }
public JournalFacade(AsyncDataManager dataManager) {
this.dataManager = dataManager;
}
private static RecordLocation convertToRecordLocation(Location location) { private static RecordLocation convertToRecordLocation(Location location) {
if (location == null) if (location == null) {
return null; return null;
}
return new RecordLocationFacade(location); return new RecordLocationFacade(location);
} }
private static Location convertFromRecordLocation(RecordLocation location) { private static Location convertFromRecordLocation(RecordLocation location) {
if (location == null) if (location == null) {
return null; return null;
}
return ((RecordLocationFacade)location).getLocation(); return ((RecordLocationFacade)location).getLocation();
} }
AsyncDataManager dataManager;
public JournalFacade(AsyncDataManager dataManager) {
this.dataManager = dataManager;
}
public void close() throws IOException { public void close() throws IOException {
dataManager.close(); dataManager.close();
} }
@ -79,24 +81,22 @@ public final class JournalFacade implements Journal {
return convertToRecordLocation(dataManager.getMark()); return convertToRecordLocation(dataManager.getMark());
} }
public RecordLocation getNextRecordLocation(RecordLocation location) public RecordLocation getNextRecordLocation(RecordLocation location) throws InvalidRecordLocationException, IOException, IllegalStateException {
throws InvalidRecordLocationException, IOException, IllegalStateException {
return convertToRecordLocation(dataManager.getNextLocation(convertFromRecordLocation(location))); return convertToRecordLocation(dataManager.getNextLocation(convertFromRecordLocation(location)));
} }
public Packet read(RecordLocation location) throws InvalidRecordLocationException, IOException, public Packet read(RecordLocation location) throws InvalidRecordLocationException, IOException, IllegalStateException {
IllegalStateException {
ByteSequence rc = dataManager.read(convertFromRecordLocation(location)); ByteSequence rc = dataManager.read(convertFromRecordLocation(location));
if (rc == null) if (rc == null) {
return null; return null;
}
return new ByteArrayPacket(rc.getData(), rc.getOffset(), rc.getLength()); return new ByteArrayPacket(rc.getData(), rc.getOffset(), rc.getLength());
} }
public void setJournalEventListener(JournalEventListener listener) throws IllegalStateException { public void setJournalEventListener(JournalEventListener listener) throws IllegalStateException {
} }
public void setMark(RecordLocation location, boolean sync) throws InvalidRecordLocationException, public void setMark(RecordLocation location, boolean sync) throws InvalidRecordLocationException, IOException, IllegalStateException {
IOException, IllegalStateException {
dataManager.setMark(convertFromRecordLocation(location), sync); dataManager.setMark(convertFromRecordLocation(location), sync);
} }

View File

@ -70,13 +70,12 @@ public class ContainerKeySet extends ContainerCollectionSupport implements Set {
} }
public boolean containsAll(Collection c) { public boolean containsAll(Collection c) {
boolean result = true;
for (Object key : c) { for (Object key : c) {
if (!(result &= container.containsKey(key))) { if (!container.containsKey(key)) {
break; return false;
} }
} }
return result; return true;
} }
public boolean addAll(Collection c) { public boolean addAll(Collection c) {

View File

@ -26,11 +26,13 @@ import org.apache.activemq.kaha.impl.index.IndexLinkedList;
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public class ContainerKeySetIterator implements Iterator { public class ContainerKeySetIterator implements Iterator {
private MapContainerImpl container;
private IndexLinkedList list;
protected IndexItem nextItem; protected IndexItem nextItem;
protected IndexItem currentItem; protected IndexItem currentItem;
private MapContainerImpl container;
private IndexLinkedList list;
ContainerKeySetIterator(MapContainerImpl container) { ContainerKeySetIterator(MapContainerImpl container) {
this.container = container; this.container = container;
this.list = container.getInternalList(); this.list = container.getInternalList();

View File

@ -323,15 +323,13 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine
*/ */
public synchronized boolean containsAll(Collection c) { public synchronized boolean containsAll(Collection c) {
load(); load();
boolean result = false;
for (Iterator i = c.iterator(); i.hasNext();) { for (Iterator i = c.iterator(); i.hasNext();) {
Object obj = i.next(); Object obj = i.next();
if (!(result = contains(obj))) { if (!contains(obj)) {
result = false; return false;
break;
} }
} }
return result; return true;
} }
/* /*
@ -872,8 +870,9 @@ public class ListContainerImpl extends BaseContainerImpl implements ListContaine
Object o = i.next(); Object o = i.next();
result.append(String.valueOf(o)); result.append(String.valueOf(o));
hasNext = i.hasNext(); hasNext = i.hasNext();
if (hasNext) if (hasNext) {
result.append(", "); result.append(", ");
}
} }
result.append("]"); result.append("]");
return result.toString(); return result.toString();

View File

@ -33,7 +33,7 @@ class DataFile {
private int referenceCount; private int referenceCount;
private RandomAccessFile randomAcessFile; private RandomAccessFile randomAcessFile;
private Object writerData; private Object writerData;
long length; private long length;
private boolean dirty; private boolean dirty;
DataFile(File file, int number) { DataFile(File file, int number) {

Some files were not shown because too many files have changed in this diff Show More