git-svn-id: https://svn.apache.org/repos/asf/activemq/trunk@1183143 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Timothy A. Bish 2011-10-13 22:28:47 +00:00
parent 4acd13243a
commit 88f60580e3
3 changed files with 151 additions and 95 deletions

View File

@ -16,6 +16,8 @@
*/ */
package org.apache.activemq.camel.component; package org.apache.activemq.camel.component;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext; import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder; import org.apache.camel.builder.RouteBuilder;
@ -28,7 +30,7 @@ import org.springframework.jms.connection.JmsTransactionManager;
import static org.apache.activemq.camel.component.ActiveMQComponent.activeMQComponent; import static org.apache.activemq.camel.component.ActiveMQComponent.activeMQComponent;
/** /**
* *
*/ */
public class ActiveMQRouteTest extends CamelTestSupport { public class ActiveMQRouteTest extends CamelTestSupport {
protected MockEndpoint resultEndpoint; protected MockEndpoint resultEndpoint;
@ -67,6 +69,36 @@ public class ActiveMQRouteTest extends CamelTestSupport {
return camelContext; return camelContext;
} }
@Test
public void testInvalidDestinationOptionOnConsumer() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(0);
assertMockEndpointsSatisfied(1, TimeUnit.SECONDS);
try {
new RouteBuilder() {
public void configure() throws Exception {
from("activemq:queue:foo?destination.consumer.exclusive=true&destination.consumer.unknown=foo")
.to("mock:result");
}
};
} catch (Exception e) {
fail("Should not have accepted bad destination options.");
}
}
@Test
public void testInvalidDestinationOptionOnProducer() throws Exception {
try {
new RouteBuilder() {
public void configure() throws Exception {
from("activemq:queue:foo")
.to("activemq:queue:bar?destination.producer.exclusive=true");
}
};
} catch (Exception e) {
fail("Should not have accepted bad destination options.");
}
}
protected RouteBuilder createRouteBuilder() throws Exception { protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() { return new RouteBuilder() {
public void configure() throws Exception { public void configure() throws Exception {

View File

@ -91,8 +91,8 @@ import org.slf4j.LoggerFactory;
* <P> * <P>
* It is a client programming error for a <CODE>MessageListener</CODE> to * It is a client programming error for a <CODE>MessageListener</CODE> to
* throw an exception. * throw an exception.
* *
* *
* @see javax.jms.MessageConsumer * @see javax.jms.MessageConsumer
* @see javax.jms.QueueReceiver * @see javax.jms.QueueReceiver
* @see javax.jms.TopicSubscriber * @see javax.jms.TopicSubscriber
@ -148,7 +148,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
private long lastDeliveredSequenceId; private long lastDeliveredSequenceId;
private IOException failureError; private IOException failureError;
private long optimizeAckTimestamp = System.currentTimeMillis(); private long optimizeAckTimestamp = System.currentTimeMillis();
private long optimizeAcknowledgeTimeOut = 0; private long optimizeAcknowledgeTimeOut = 0;
private long failoverRedeliveryWaitPeriod = 0; private long failoverRedeliveryWaitPeriod = 0;
@ -156,7 +156,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
/** /**
* Create a MessageConsumer * Create a MessageConsumer
* *
* @param session * @param session
* @param dest * @param dest
* @param name * @param name
@ -225,6 +225,15 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
if (dest.getOptions() != null) { if (dest.getOptions() != null) {
Map<String, String> options = new HashMap<String, String>(dest.getOptions()); Map<String, String> options = new HashMap<String, String>(dest.getOptions());
IntrospectionSupport.setProperties(this.info, options, "consumer."); IntrospectionSupport.setProperties(this.info, options, "consumer.");
if (options.size() > 0) {
String msg = "There are " + options.size()
+ " consumer options that couldn't be set on the consumer."
+ " Check the options are spelled correctly."
+ " Unknown parameters=[" + options + "]."
+ " This consumer cannot be started.";
LOG.warn(msg);
throw new ConfigurationException(msg);
}
} }
this.info.setDestination(dest); this.info.setDestination(dest);
@ -329,7 +338,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
/** /**
* Retrieve is a browser * Retrieve is a browser
* *
* @return true if a browser * @return true if a browser
*/ */
protected boolean isBrowser() { protected boolean isBrowser() {
@ -359,7 +368,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
/** /**
* Gets this message consumer's message selector expression. * Gets this message consumer's message selector expression.
* *
* @return this message consumer's message selector, or null if no message * @return this message consumer's message selector, or null if no message
* selector exists for the message consumer (that is, if the message * selector exists for the message consumer (that is, if the message
* selector was not set or was set to null or the empty string) * selector was not set or was set to null or the empty string)
@ -373,7 +382,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
/** /**
* Gets the message consumer's <CODE>MessageListener</CODE>. * Gets the message consumer's <CODE>MessageListener</CODE>.
* *
* @return the listener for the message consumer, or null if no listener is * @return the listener for the message consumer, or null if no listener is
* set * set
* @throws JMSException if the JMS provider fails to get the message * @throws JMSException if the JMS provider fails to get the message
@ -394,7 +403,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
* The effect of calling <CODE>MessageConsumer.setMessageListener</CODE> * The effect of calling <CODE>MessageConsumer.setMessageListener</CODE>
* while messages are being consumed by an existing listener or the consumer * while messages are being consumed by an existing listener or the consumer
* is being used to consume messages synchronously is undefined. * is being used to consume messages synchronously is undefined.
* *
* @param listener the listener to which the messages are to be delivered * @param listener the listener to which the messages are to be delivered
* @throws JMSException if the JMS provider fails to receive the next * @throws JMSException if the JMS provider fails to receive the next
* message due to some internal error. * message due to some internal error.
@ -443,7 +452,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
* then it it tries to not block at all, it returns a message if it is * then it it tries to not block at all, it returns a message if it is
* available - if timeout>0 then it blocks up to timeout amount of time. * available - if timeout>0 then it blocks up to timeout amount of time.
* Expired messages will consumed by this method. * Expired messages will consumed by this method.
* *
* @throws JMSException * @throws JMSException
* @return null if we timeout or if the consumer is closed. * @return null if we timeout or if the consumer is closed.
*/ */
@ -459,11 +468,11 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
if (timeout > 0 && !unconsumedMessages.isClosed()) { if (timeout > 0 && !unconsumedMessages.isClosed()) {
timeout = Math.max(deadline - System.currentTimeMillis(), 0); timeout = Math.max(deadline - System.currentTimeMillis(), 0);
} else { } else {
if (failureError != null) { if (failureError != null) {
throw JMSExceptionSupport.create(failureError); throw JMSExceptionSupport.create(failureError);
} else { } else {
return null; return null;
} }
} }
} else if (md.getMessage() == null) { } else if (md.getMessage() == null) {
return null; return null;
@ -497,7 +506,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
* <P> * <P>
* If this <CODE>receive</CODE> is done within a transaction, the consumer * If this <CODE>receive</CODE> is done within a transaction, the consumer
* retains the message until the transaction commits. * retains the message until the transaction commits.
* *
* @return the next message produced for this message consumer, or null if * @return the next message produced for this message consumer, or null if
* this message consumer is concurrently closed * this message consumer is concurrently closed
*/ */
@ -524,7 +533,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
private ActiveMQMessage createActiveMQMessage(final MessageDispatch md) throws JMSException { private ActiveMQMessage createActiveMQMessage(final MessageDispatch md) throws JMSException {
ActiveMQMessage m = (ActiveMQMessage)md.getMessage().copy(); ActiveMQMessage m = (ActiveMQMessage)md.getMessage().copy();
if (m.getDataStructureType()==CommandTypes.ACTIVEMQ_BLOB_MESSAGE) { if (m.getDataStructureType()==CommandTypes.ACTIVEMQ_BLOB_MESSAGE) {
((ActiveMQBlobMessage)m).setBlobDownloader(new BlobDownloader(session.getBlobTransferPolicy())); ((ActiveMQBlobMessage)m).setBlobDownloader(new BlobDownloader(session.getBlobTransferPolicy()));
} }
if (transformer != null) { if (transformer != null) {
Message transformedMessage = transformer.consumerTransform(session, this, m); Message transformedMessage = transformer.consumerTransform(session, this, m);
@ -557,7 +566,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
* This call blocks until a message arrives, the timeout expires, or this * This call blocks until a message arrives, the timeout expires, or this
* message consumer is closed. A <CODE>timeout</CODE> of zero never * message consumer is closed. A <CODE>timeout</CODE> of zero never
* expires, and the call blocks indefinitely. * expires, and the call blocks indefinitely.
* *
* @param timeout the timeout value (in milliseconds), a time out of zero * @param timeout the timeout value (in milliseconds), a time out of zero
* never expires. * never expires.
* @return the next message produced for this message consumer, or null if * @return the next message produced for this message consumer, or null if
@ -595,7 +604,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
/** /**
* Receives the next message if one is immediately available. * Receives the next message if one is immediately available.
* *
* @return the next message produced for this message consumer, or null if * @return the next message produced for this message consumer, or null if
* one is not available * one is not available
* @throws JMSException if the JMS provider fails to receive the next * @throws JMSException if the JMS provider fails to receive the next
@ -635,7 +644,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
* This call blocks until a <CODE>receive</CODE> or message listener in * This call blocks until a <CODE>receive</CODE> or message listener in
* progress has completed. A blocked message consumer <CODE>receive </CODE> * progress has completed. A blocked message consumer <CODE>receive </CODE>
* call returns null when this message consumer is closed. * call returns null when this message consumer is closed.
* *
* @throws JMSException if the JMS provider fails to close the consumer due * @throws JMSException if the JMS provider fails to close the consumer due
* to some internal error. * to some internal error.
*/ */
@ -655,7 +664,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
}); });
} else { } else {
doClose(); doClose();
} }
} }
} }
@ -668,13 +677,13 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
removeCommand.setLastDeliveredSequenceId(lastDeliveredSequenceId); removeCommand.setLastDeliveredSequenceId(lastDeliveredSequenceId);
this.session.asyncSendPacket(removeCommand); this.session.asyncSendPacket(removeCommand);
} }
void inProgressClearRequired() { void inProgressClearRequired() {
inProgressClearRequiredFlag = true; inProgressClearRequiredFlag = true;
// deal with delivered messages async to avoid lock contention with in progress acks // deal with delivered messages async to avoid lock contention with in progress acks
clearDispatchList = true; clearDispatchList = true;
} }
void clearMessagesInProgress() { void clearMessagesInProgress() {
if (inProgressClearRequiredFlag) { if (inProgressClearRequiredFlag) {
synchronized (unconsumedMessages.getMutex()) { synchronized (unconsumedMessages.getMutex()) {
@ -706,18 +715,18 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
if (ack != null) { if (ack != null) {
deliveredMessages.clear(); deliveredMessages.clear();
ackCounter = 0; ackCounter = 0;
} else { } else {
ack = pendingAck; ack = pendingAck;
pendingAck = null; pendingAck = null;
} }
} }
} else if (pendingAck != null && pendingAck.isStandardAck()) { } else if (pendingAck != null && pendingAck.isStandardAck()) {
ack = pendingAck; ack = pendingAck;
pendingAck = null; pendingAck = null;
} }
if (ack != null) { if (ack != null) {
final MessageAck ackToSend = ack; final MessageAck ackToSend = ack;
if (executorService == null) { if (executorService == null) {
executorService = Executors.newSingleThreadExecutor(); executorService = Executors.newSingleThreadExecutor();
} }
@ -740,10 +749,10 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
public void dispose() throws JMSException { public void dispose() throws JMSException {
if (!unconsumedMessages.isClosed()) { if (!unconsumedMessages.isClosed()) {
// Do we have any acks we need to send out before closing? // Do we have any acks we need to send out before closing?
// Ack any delivered messages now. // Ack any delivered messages now.
if (!session.getTransacted()) { if (!session.getTransacted()) {
deliverAcks(); deliverAcks();
if (isAutoAcknowledgeBatch()) { if (isAutoAcknowledgeBatch()) {
acknowledge(); acknowledge();
@ -757,7 +766,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
} }
if (session.isClientAcknowledge()) { if (session.isClientAcknowledge()) {
if (!this.info.isBrowser()) { if (!this.info.isBrowser()) {
// rollback duplicates that aren't acknowledged // rollback duplicates that aren't acknowledged
@ -874,13 +883,13 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
if (optimizeAcknowledge) { if (optimizeAcknowledge) {
ackCounter++; ackCounter++;
if (ackCounter >= (info.getPrefetchSize() * .65) || (optimizeAcknowledgeTimeOut > 0 && System.currentTimeMillis() >= (optimizeAckTimestamp + optimizeAcknowledgeTimeOut))) { if (ackCounter >= (info.getPrefetchSize() * .65) || (optimizeAcknowledgeTimeOut > 0 && System.currentTimeMillis() >= (optimizeAckTimestamp + optimizeAcknowledgeTimeOut))) {
MessageAck ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE); MessageAck ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE);
if (ack != null) { if (ack != null) {
deliveredMessages.clear(); deliveredMessages.clear();
ackCounter = 0; ackCounter = 0;
session.sendAck(ack); session.sendAck(ack);
optimizeAckTimestamp = System.currentTimeMillis(); optimizeAckTimestamp = System.currentTimeMillis();
} }
} }
} else { } else {
MessageAck ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE); MessageAck ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE);
@ -903,7 +912,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
if (messageUnackedByConsumer) { if (messageUnackedByConsumer) {
ackLater(md, MessageAck.DELIVERED_ACK_TYPE); ackLater(md, MessageAck.DELIVERED_ACK_TYPE);
} }
} }
else { else {
throw new IllegalStateException("Invalid session state."); throw new IllegalStateException("Invalid session state.");
} }
@ -913,21 +922,21 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
/** /**
* Creates a MessageAck for all messages contained in deliveredMessages. * Creates a MessageAck for all messages contained in deliveredMessages.
* Caller should hold the lock for deliveredMessages. * Caller should hold the lock for deliveredMessages.
* *
* @param type Ack-Type (i.e. MessageAck.STANDARD_ACK_TYPE) * @param type Ack-Type (i.e. MessageAck.STANDARD_ACK_TYPE)
* @return <code>null</code> if nothing to ack. * @return <code>null</code> if nothing to ack.
*/ */
private MessageAck makeAckForAllDeliveredMessages(byte type) { private MessageAck makeAckForAllDeliveredMessages(byte type) {
synchronized (deliveredMessages) { synchronized (deliveredMessages) {
if (deliveredMessages.isEmpty()) if (deliveredMessages.isEmpty())
return null; return null;
MessageDispatch md = deliveredMessages.getFirst(); MessageDispatch md = deliveredMessages.getFirst();
MessageAck ack = new MessageAck(md, type, deliveredMessages.size()); MessageAck ack = new MessageAck(md, type, deliveredMessages.size());
ack.setFirstMessageId(deliveredMessages.getLast().getMessage().getMessageId()); ack.setFirstMessageId(deliveredMessages.getLast().getMessage().getMessageId());
return ack; return ack;
} }
} }
private void ackLater(MessageDispatch md, byte ackType) throws JMSException { private void ackLater(MessageDispatch md, byte ackType) throws JMSException {
@ -938,7 +947,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
} }
deliveredCounter++; deliveredCounter++;
MessageAck oldPendingAck = pendingAck; MessageAck oldPendingAck = pendingAck;
pendingAck = new MessageAck(md, ackType, deliveredCounter); pendingAck = new MessageAck(md, ackType, deliveredCounter);
pendingAck.setTransactionId(session.getTransactionContext().getTransactionId()); pendingAck.setTransactionId(session.getTransactionContext().getTransactionId());
@ -960,7 +969,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
} }
} }
} }
if ((0.5 * info.getPrefetchSize()) <= (deliveredCounter - additionalWindowSize)) { if ((0.5 * info.getPrefetchSize()) <= (deliveredCounter - additionalWindowSize)) {
session.sendAck(pendingAck); session.sendAck(pendingAck);
pendingAck=null; pendingAck=null;
@ -1006,7 +1015,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
/** /**
* Acknowledge all the messages that have been delivered to the client up to * Acknowledge all the messages that have been delivered to the client up to
* this point. * this point.
* *
* @throws JMSException * @throws JMSException
*/ */
public void acknowledge() throws JMSException { public void acknowledge() throws JMSException {
@ -1016,8 +1025,8 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
// Acknowledge all messages so far. // Acknowledge all messages so far.
MessageAck ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE); MessageAck ack = makeAckForAllDeliveredMessages(MessageAck.STANDARD_ACK_TYPE);
if (ack == null) if (ack == null)
return; // no msgs return; // no msgs
if (session.getTransacted()) { if (session.getTransacted()) {
rollbackOnFailedRecoveryRedelivery(); rollbackOnFailedRecoveryRedelivery();
session.doStartTransaction(); session.doStartTransaction();
@ -1025,17 +1034,17 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
} }
session.sendAck(ack); session.sendAck(ack);
pendingAck = null; pendingAck = null;
// Adjust the counters // Adjust the counters
deliveredCounter = Math.max(0, deliveredCounter - deliveredMessages.size()); deliveredCounter = Math.max(0, deliveredCounter - deliveredMessages.size());
additionalWindowSize = Math.max(0, additionalWindowSize - deliveredMessages.size()); additionalWindowSize = Math.max(0, additionalWindowSize - deliveredMessages.size());
if (!session.getTransacted()) { if (!session.getTransacted()) {
deliveredMessages.clear(); deliveredMessages.clear();
} }
} }
} }
private void waitForRedeliveries() { private void waitForRedeliveries() {
if (failoverRedeliveryWaitPeriod > 0 && previouslyDeliveredMessages != null) { if (failoverRedeliveryWaitPeriod > 0 && previouslyDeliveredMessages != null) {
long expiry = System.currentTimeMillis() + failoverRedeliveryWaitPeriod; long expiry = System.currentTimeMillis() + failoverRedeliveryWaitPeriod;
@ -1043,7 +1052,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
do { do {
numberNotReplayed = 0; numberNotReplayed = 0;
synchronized(deliveredMessages) { synchronized(deliveredMessages) {
if (previouslyDeliveredMessages != null) { if (previouslyDeliveredMessages != null) {
for (Entry<MessageId, Boolean> entry: previouslyDeliveredMessages.entrySet()) { for (Entry<MessageId, Boolean> entry: previouslyDeliveredMessages.entrySet()) {
if (!entry.getValue()) { if (!entry.getValue()) {
numberNotReplayed++; numberNotReplayed++;
@ -1077,17 +1086,17 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
numberNotReplayed++; numberNotReplayed++;
if (LOG.isDebugEnabled()) { if (LOG.isDebugEnabled()) {
LOG.debug("previously delivered message has not been replayed in transaction: " LOG.debug("previously delivered message has not been replayed in transaction: "
+ previouslyDeliveredMessages.transactionId + previouslyDeliveredMessages.transactionId
+ " , messageId: " + entry.getKey()); + " , messageId: " + entry.getKey());
} }
} }
} }
if (numberNotReplayed > 0) { if (numberNotReplayed > 0) {
String message = "rolling back transaction (" String message = "rolling back transaction ("
+ previouslyDeliveredMessages.transactionId + ") post failover recovery. " + numberNotReplayed + previouslyDeliveredMessages.transactionId + ") post failover recovery. " + numberNotReplayed
+ " previously delivered message(s) not replayed to consumer: " + this.getConsumerId(); + " previously delivered message(s) not replayed to consumer: " + this.getConsumerId();
LOG.warn(message); LOG.warn(message);
throw new TransactionRolledBackException(message); throw new TransactionRolledBackException(message);
} }
} }
} }
@ -1128,7 +1137,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
if (deliveredMessages.isEmpty()) { if (deliveredMessages.isEmpty()) {
return; return;
} }
// use initial delay for first redelivery // use initial delay for first redelivery
MessageDispatch lastMd = deliveredMessages.getFirst(); MessageDispatch lastMd = deliveredMessages.getFirst();
final int currentRedeliveryCount = lastMd.getMessage().getRedeliveryCounter(); final int currentRedeliveryCount = lastMd.getMessage().getRedeliveryCounter();
@ -1138,44 +1147,44 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
redeliveryDelay = redeliveryPolicy.getInitialRedeliveryDelay(); redeliveryDelay = redeliveryPolicy.getInitialRedeliveryDelay();
} }
MessageId firstMsgId = deliveredMessages.getLast().getMessage().getMessageId(); MessageId firstMsgId = deliveredMessages.getLast().getMessage().getMessageId();
for (Iterator<MessageDispatch> iter = deliveredMessages.iterator(); iter.hasNext();) { for (Iterator<MessageDispatch> iter = deliveredMessages.iterator(); iter.hasNext();) {
MessageDispatch md = iter.next(); MessageDispatch md = iter.next();
md.getMessage().onMessageRolledBack(); md.getMessage().onMessageRolledBack();
// ensure we don't filter this as a duplicate // ensure we don't filter this as a duplicate
session.connection.rollbackDuplicate(this, md.getMessage()); session.connection.rollbackDuplicate(this, md.getMessage());
} }
if (redeliveryPolicy.getMaximumRedeliveries() != RedeliveryPolicy.NO_MAXIMUM_REDELIVERIES if (redeliveryPolicy.getMaximumRedeliveries() != RedeliveryPolicy.NO_MAXIMUM_REDELIVERIES
&& lastMd.getMessage().getRedeliveryCounter() > redeliveryPolicy.getMaximumRedeliveries()) { && lastMd.getMessage().getRedeliveryCounter() > 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
// DLQ. // DLQ.
// Acknowledge the last message. // Acknowledge the last message.
MessageAck ack = new MessageAck(lastMd, MessageAck.POSION_ACK_TYPE, deliveredMessages.size()); MessageAck ack = new MessageAck(lastMd, MessageAck.POSION_ACK_TYPE, deliveredMessages.size());
ack.setPoisonCause(lastMd.getRollbackCause()); ack.setPoisonCause(lastMd.getRollbackCause());
ack.setFirstMessageId(firstMsgId); ack.setFirstMessageId(firstMsgId);
session.sendAck(ack,true); session.sendAck(ack,true);
// Adjust the window size. // Adjust the window size.
additionalWindowSize = Math.max(0, additionalWindowSize - deliveredMessages.size()); additionalWindowSize = Math.max(0, additionalWindowSize - deliveredMessages.size());
redeliveryDelay = 0; redeliveryDelay = 0;
} else { } else {
// only redelivery_ack after first delivery // only redelivery_ack after first delivery
if (currentRedeliveryCount > 0) { if (currentRedeliveryCount > 0) {
MessageAck ack = new MessageAck(lastMd, MessageAck.REDELIVERED_ACK_TYPE, deliveredMessages.size()); MessageAck ack = new MessageAck(lastMd, MessageAck.REDELIVERED_ACK_TYPE, deliveredMessages.size());
ack.setFirstMessageId(firstMsgId); ack.setFirstMessageId(firstMsgId);
session.sendAck(ack,true); session.sendAck(ack,true);
} }
// stop the delivery of messages. // stop the delivery of messages.
unconsumedMessages.stop(); unconsumedMessages.stop();
for (Iterator<MessageDispatch> iter = deliveredMessages.iterator(); iter.hasNext();) { for (Iterator<MessageDispatch> iter = deliveredMessages.iterator(); iter.hasNext();) {
MessageDispatch md = iter.next(); MessageDispatch md = iter.next();
unconsumedMessages.enqueueFirst(md); unconsumedMessages.enqueueFirst(md);
} }
if (redeliveryDelay > 0 && !unconsumedMessages.isClosed()) { if (redeliveryDelay > 0 && !unconsumedMessages.isClosed()) {
// Start up the delivery again a little later. // Start up the delivery again a little later.
scheduler.executeAfterDelay(new Runnable() { scheduler.executeAfterDelay(new Runnable() {
@ -1192,7 +1201,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
} else { } else {
start(); start();
} }
} }
deliveredCounter -= deliveredMessages.size(); deliveredCounter -= deliveredMessages.size();
deliveredMessages.clear(); deliveredMessages.clear();
@ -1205,13 +1214,13 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
/* /*
* called with unconsumedMessages && deliveredMessages locked * called with unconsumedMessages && deliveredMessages locked
* remove any message not re-delivered as they can't be replayed to this * remove any message not re-delivered as they can't be replayed to this
* consumer on rollback * consumer on rollback
*/ */
private void rollbackPreviouslyDeliveredAndNotRedelivered() { private void rollbackPreviouslyDeliveredAndNotRedelivered() {
if (previouslyDeliveredMessages != null) { if (previouslyDeliveredMessages != null) {
for (Entry<MessageId, Boolean> entry: previouslyDeliveredMessages.entrySet()) { for (Entry<MessageId, Boolean> entry: previouslyDeliveredMessages.entrySet()) {
if (!entry.getValue()) { if (!entry.getValue()) {
removeFromDeliveredMessages(entry.getKey()); removeFromDeliveredMessages(entry.getKey());
} }
} }
@ -1305,7 +1314,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
} }
if (needsPoisonAck) { if (needsPoisonAck) {
LOG.warn("acking duplicate delivery as poison, redelivery must be pending to another" LOG.warn("acking duplicate delivery as poison, redelivery must be pending to another"
+ " consumer on this connection, failoverRedeliveryWaitPeriod=" + " consumer on this connection, failoverRedeliveryWaitPeriod="
+ failoverRedeliveryWaitPeriod + ". Message: " + md); + failoverRedeliveryWaitPeriod + ". Message: " + md);
MessageAck poisonAck = new MessageAck(md, MessageAck.POSION_ACK_TYPE, 1); MessageAck poisonAck = new MessageAck(md, MessageAck.POSION_ACK_TYPE, 1);
poisonAck.setFirstMessageId(md.getMessage().getMessageId()); poisonAck.setFirstMessageId(md.getMessage().getMessageId());
@ -1333,10 +1342,10 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
// async (on next call) clear or track delivered as they may be flagged as duplicates if they arrive again // async (on next call) clear or track delivered as they may be flagged as duplicates if they arrive again
private void clearDispatchList() { private void clearDispatchList() {
if (clearDispatchList) { if (clearDispatchList) {
synchronized (deliveredMessages) { synchronized (deliveredMessages) {
if (clearDispatchList) { if (clearDispatchList) {
if (!deliveredMessages.isEmpty()) { if (!deliveredMessages.isEmpty()) {
if (session.isTransacted()) { if (session.isTransacted()) {
if (LOG.isDebugEnabled()) { if (LOG.isDebugEnabled()) {
LOG.debug(getConsumerId() + " tracking existing transacted delivered list (" + deliveredMessages.size() + ") on transport interrupt"); LOG.debug(getConsumerId() + " tracking existing transacted delivered list (" + deliveredMessages.size() + ") on transport interrupt");
} }
@ -1386,7 +1395,7 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
/** /**
* Delivers a message to the message listener. * Delivers a message to the message listener.
* *
* @return * @return
* @throws JMSException * @throws JMSException
*/ */
@ -1410,11 +1419,11 @@ public class ActiveMQMessageConsumer implements MessageAvailableConsumer, StatsC
return lastDeliveredSequenceId; return lastDeliveredSequenceId;
} }
public IOException getFailureError() { public IOException getFailureError() {
return failureError; return failureError;
} }
public void setFailureError(IOException failureError) { public void setFailureError(IOException failureError) {
this.failureError = failureError; this.failureError = failureError;
} }
} }

View File

@ -33,6 +33,8 @@ import org.apache.activemq.management.StatsCapable;
import org.apache.activemq.management.StatsImpl; import org.apache.activemq.management.StatsImpl;
import org.apache.activemq.usage.MemoryUsage; import org.apache.activemq.usage.MemoryUsage;
import org.apache.activemq.util.IntrospectionSupport; import org.apache.activemq.util.IntrospectionSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* A client uses a <CODE>MessageProducer</CODE> object to send messages to a * A client uses a <CODE>MessageProducer</CODE> object to send messages to a
@ -60,14 +62,16 @@ import org.apache.activemq.util.IntrospectionSupport;
* <P> * <P>
* A JMS provider should do its best to expire messages accurately; however, the * A JMS provider should do its best to expire messages accurately; however, the
* JMS API does not define the accuracy provided. * JMS API does not define the accuracy provided.
* *
* *
* @see javax.jms.TopicPublisher * @see javax.jms.TopicPublisher
* @see javax.jms.QueueSender * @see javax.jms.QueueSender
* @see javax.jms.Session#createProducer * @see javax.jms.Session#createProducer
*/ */
public class ActiveMQMessageProducer extends ActiveMQMessageProducerSupport implements StatsCapable, Disposable { public class ActiveMQMessageProducer extends ActiveMQMessageProducerSupport implements StatsCapable, Disposable {
private static final Logger LOG = LoggerFactory.getLogger(ActiveMQMessageProducer.class);
protected ProducerInfo info; protected ProducerInfo info;
protected boolean closed; protected boolean closed;
@ -81,10 +85,21 @@ public class ActiveMQMessageProducer extends ActiveMQMessageProducerSupport impl
super(session); super(session);
this.info = new ProducerInfo(producerId); this.info = new ProducerInfo(producerId);
this.info.setWindowSize(session.connection.getProducerWindowSize()); this.info.setWindowSize(session.connection.getProducerWindowSize());
// Allows the options on the destination to configure the producerInfo
if (destination != null && destination.getOptions() != null) { if (destination != null && destination.getOptions() != null) {
Map<String, String> options = new HashMap<String, String>(destination.getOptions()); Map<String, String> options = new HashMap<String, String>(destination.getOptions());
IntrospectionSupport.setProperties(this.info, options, "producer."); IntrospectionSupport.setProperties(this.info, options, "producer.");
if (options.size() > 0) {
String msg = "There are " + options.size()
+ " producer options that couldn't be set on the producer."
+ " Check the options are spelled correctly."
+ " Unknown parameters=[" + options + "]."
+ " This producer cannot be started.";
LOG.warn(msg);
throw new ConfigurationException(msg);
}
} }
this.info.setDestination(destination); this.info.setDestination(destination);
// Enable producer window flow control if protocol > 3 and the window // Enable producer window flow control if protocol > 3 and the window
@ -118,7 +133,7 @@ public class ActiveMQMessageProducer extends ActiveMQMessageProducerSupport impl
/** /**
* Gets the destination associated with this <CODE>MessageProducer</CODE>. * Gets the destination associated with this <CODE>MessageProducer</CODE>.
* *
* @return this producer's <CODE>Destination/ <CODE> * @return this producer's <CODE>Destination/ <CODE>
* @throws JMSException if the JMS provider fails to close the producer due to * @throws JMSException if the JMS provider fails to close the producer due to
* some internal error. * some internal error.
@ -137,7 +152,7 @@ public class ActiveMQMessageProducer extends ActiveMQMessageProducerSupport impl
* outside the Java virtual machine, clients should close them when they are * outside the Java virtual machine, clients should close them when they are
* not needed. Relying on garbage collection to eventually reclaim these * not needed. Relying on garbage collection to eventually reclaim these
* resources may not be timely enough. * resources may not be timely enough.
* *
* @throws JMSException if the JMS provider fails to close the producer due * @throws JMSException if the JMS provider fails to close the producer due
* to some internal error. * to some internal error.
*/ */
@ -160,7 +175,7 @@ public class ActiveMQMessageProducer extends ActiveMQMessageProducerSupport impl
/** /**
* Check if the instance of this producer has been closed. * Check if the instance of this producer has been closed.
* *
* @throws IllegalStateException * @throws IllegalStateException
*/ */
@Override @Override
@ -177,7 +192,7 @@ public class ActiveMQMessageProducer extends ActiveMQMessageProducerSupport impl
* Typically, a message producer is assigned a destination at creation time; * Typically, a message producer is assigned a destination at creation time;
* however, the JMS API also supports unidentified message producers, which * however, the JMS API also supports unidentified message producers, which
* require that the destination be supplied every time a message is sent. * require that the destination be supplied every time a message is sent.
* *
* @param destination the destination to send this message to * @param destination the destination to send this message to
* @param message the message to send * @param message the message to send
* @param deliveryMode the delivery mode to use * @param deliveryMode the delivery mode to use