More checkstyle fixes

git-svn-id: https://svn.apache.org/repos/asf/activemq/trunk@563982 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Hiram R. Chirino 2007-08-08 18:56:59 +00:00
parent 43ba1be188
commit f812e34179
452 changed files with 17426 additions and 17633 deletions

View File

@ -32,7 +32,6 @@ import javax.jms.TemporaryTopic;
import javax.jms.TextMessage; import javax.jms.TextMessage;
import javax.jms.Topic; import javax.jms.Topic;
import org.apache.activemq.command.ActiveMQBytesMessage; import org.apache.activemq.command.ActiveMQBytesMessage;
import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQMapMessage; import org.apache.activemq.command.ActiveMQMapMessage;
@ -46,65 +45,66 @@ import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.activemq.command.ActiveMQTopic; import org.apache.activemq.command.ActiveMQTopic;
/** /**
* A helper class for converting normal JMS interfaces into ActiveMQ specific ones. * A helper class for converting normal JMS interfaces into ActiveMQ specific
* ones.
* *
* @version $Revision: 1.1 $ * @version $Revision: 1.1 $
*/ */
public class ActiveMQMessageTransformation { public class ActiveMQMessageTransformation {
/** /**
* Creates a an available JMS message from another provider. * Creates a an available JMS message from another provider.
* *
* @param destination - Destination to be converted into ActiveMQ's implementation. * @param destination - Destination to be converted into ActiveMQ's
* @return ActiveMQDestination - ActiveMQ's implementation of the destination. * implementation.
* @throws JMSException if an error occurs * @return ActiveMQDestination - ActiveMQ's implementation of the
*/ * destination.
public static ActiveMQDestination transformDestination(Destination destination) throws JMSException { * @throws JMSException if an error occurs
*/
public static ActiveMQDestination transformDestination(Destination destination) throws JMSException {
ActiveMQDestination activeMQDestination = null; ActiveMQDestination activeMQDestination = null;
if (destination != null) { if (destination != null) {
if (destination instanceof ActiveMQDestination) { if (destination instanceof ActiveMQDestination) {
return (ActiveMQDestination) destination; return (ActiveMQDestination)destination;
} } else {
else {
if (destination instanceof TemporaryQueue) { if (destination instanceof TemporaryQueue) {
activeMQDestination = new ActiveMQTempQueue(((Queue) destination).getQueueName()); activeMQDestination = new ActiveMQTempQueue(((Queue)destination).getQueueName());
} } else if (destination instanceof TemporaryTopic) {
else if (destination instanceof TemporaryTopic) { activeMQDestination = new ActiveMQTempTopic(((Topic)destination).getTopicName());
activeMQDestination = new ActiveMQTempTopic(((Topic) destination).getTopicName()); } else if (destination instanceof Queue) {
} activeMQDestination = new ActiveMQQueue(((Queue)destination).getQueueName());
else if (destination instanceof Queue) { } else if (destination instanceof Topic) {
activeMQDestination = new ActiveMQQueue(((Queue) destination).getQueueName()); activeMQDestination = new ActiveMQTopic(((Topic)destination).getTopicName());
}
else if (destination instanceof Topic) {
activeMQDestination = new ActiveMQTopic(((Topic) destination).getTopicName());
} }
} }
} }
return activeMQDestination; return activeMQDestination;
} }
/** /**
* Creates a fast shallow copy of the current ActiveMQMessage or creates a whole new * Creates a fast shallow copy of the current ActiveMQMessage or creates a
* message instance from an available JMS message from another provider. * whole new message instance from an available JMS message from another
* * provider.
*
* @param message - Message to be converted into ActiveMQ's implementation. * @param message - Message to be converted into ActiveMQ's implementation.
* @param connection * @param connection
* @return ActiveMQMessage - ActiveMQ's implementation object of the message. * @return ActiveMQMessage - ActiveMQ's implementation object of the
* message.
* @throws JMSException if an error occurs * @throws JMSException if an error occurs
*/ */
public static final ActiveMQMessage transformMessage(Message message, ActiveMQConnection connection) throws JMSException { public static final ActiveMQMessage transformMessage(Message message, ActiveMQConnection connection)
throws JMSException {
if (message instanceof ActiveMQMessage) { if (message instanceof ActiveMQMessage) {
return (ActiveMQMessage) message; return (ActiveMQMessage)message;
} else { } else {
ActiveMQMessage activeMessage = null; ActiveMQMessage activeMessage = null;
if (message instanceof BytesMessage) { if (message instanceof BytesMessage) {
BytesMessage bytesMsg = (BytesMessage) message; BytesMessage bytesMsg = (BytesMessage)message;
bytesMsg.reset(); bytesMsg.reset();
ActiveMQBytesMessage msg = new ActiveMQBytesMessage(); ActiveMQBytesMessage msg = new ActiveMQBytesMessage();
msg.setConnection(connection); msg.setConnection(connection);
@ -121,7 +121,7 @@ public class ActiveMQMessageTransformation {
activeMessage = msg; activeMessage = msg;
} else if (message instanceof MapMessage) { } else if (message instanceof MapMessage) {
MapMessage mapMsg = (MapMessage) message; MapMessage mapMsg = (MapMessage)message;
ActiveMQMapMessage msg = new ActiveMQMapMessage(); ActiveMQMapMessage msg = new ActiveMQMapMessage();
msg.setConnection(connection); msg.setConnection(connection);
Enumeration iter = mapMsg.getMapNames(); Enumeration iter = mapMsg.getMapNames();
@ -133,14 +133,14 @@ public class ActiveMQMessageTransformation {
activeMessage = msg; activeMessage = msg;
} else if (message instanceof ObjectMessage) { } else if (message instanceof ObjectMessage) {
ObjectMessage objMsg = (ObjectMessage) message; ObjectMessage objMsg = (ObjectMessage)message;
ActiveMQObjectMessage msg = new ActiveMQObjectMessage(); ActiveMQObjectMessage msg = new ActiveMQObjectMessage();
msg.setConnection(connection); msg.setConnection(connection);
msg.setObject(objMsg.getObject()); msg.setObject(objMsg.getObject());
msg.storeContent(); msg.storeContent();
activeMessage = msg; activeMessage = msg;
} else if (message instanceof StreamMessage) { } else if (message instanceof StreamMessage) {
StreamMessage streamMessage = (StreamMessage) message; StreamMessage streamMessage = (StreamMessage)message;
streamMessage.reset(); streamMessage.reset();
ActiveMQStreamMessage msg = new ActiveMQStreamMessage(); ActiveMQStreamMessage msg = new ActiveMQStreamMessage();
msg.setConnection(connection); msg.setConnection(connection);
@ -157,7 +157,7 @@ public class ActiveMQMessageTransformation {
activeMessage = msg; activeMessage = msg;
} else if (message instanceof TextMessage) { } else if (message instanceof TextMessage) {
TextMessage textMsg = (TextMessage) message; TextMessage textMsg = (TextMessage)message;
ActiveMQTextMessage msg = new ActiveMQTextMessage(); ActiveMQTextMessage msg = new ActiveMQTextMessage();
msg.setConnection(connection); msg.setConnection(connection);
msg.setText(textMsg.getText()); msg.setText(textMsg.getText());
@ -174,8 +174,9 @@ public class ActiveMQMessageTransformation {
} }
/** /**
* Copies the standard JMS and user defined properties from the givem message to the specified message * Copies the standard JMS and user defined properties from the givem
* * message to the specified message
*
* @param fromMessage the message to take the properties from * @param fromMessage the message to take the properties from
* @param toMesage the message to add the properties to * @param toMesage the message to add the properties to
* @throws JMSException * @throws JMSException

View File

@ -16,22 +16,20 @@
*/ */
package org.apache.activemq; package org.apache.activemq;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ConsumerId;
import javax.jms.JMSException; import javax.jms.JMSException;
import javax.jms.Queue; import javax.jms.Queue;
import javax.jms.QueueReceiver; import javax.jms.QueueReceiver;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ConsumerId;
/** /**
* A client uses a <CODE>QueueReceiver</CODE> object to receive messages that * A client uses a <CODE>QueueReceiver</CODE> object to receive messages that
* have been delivered to a queue. * have been delivered to a queue. <p/>
* <p/>
* <P> * <P>
* Although it is possible to have multiple <CODE>QueueReceiver</CODE> s for * Although it is possible to have multiple <CODE>QueueReceiver</CODE> s for
* the same queue, the JMS API does not define how messages are distributed * the same queue, the JMS API does not define how messages are distributed
* between the <CODE>QueueReceiver</CODE>s. * between the <CODE>QueueReceiver</CODE>s. <p/>
* <p/>
* <P> * <P>
* If a <CODE>QueueReceiver</CODE> specifies a message selector, the messages * If a <CODE>QueueReceiver</CODE> specifies a message selector, the messages
* that are not selected remain on the queue. By definition, a message selector * that are not selected remain on the queue. By definition, a message selector
@ -39,14 +37,14 @@ import javax.jms.QueueReceiver;
* the skipped messages are eventually read, the total ordering of the reads * the skipped messages are eventually read, the total ordering of the reads
* does not retain the partial order defined by each message producer. Only * does not retain the partial order defined by each message producer. Only
* <CODE>QueueReceiver</CODE> s without a message selector will read messages * <CODE>QueueReceiver</CODE> s without a message selector will read messages
* in message producer order. * in message producer order. <p/>
* <p/>
* <P> * <P>
* Creating a <CODE>MessageConsumer</CODE> provides the same features as * Creating a <CODE>MessageConsumer</CODE> provides the same features as
* creating a <CODE>QueueReceiver</CODE>. A <CODE>MessageConsumer</CODE> * creating a <CODE>QueueReceiver</CODE>. A <CODE>MessageConsumer</CODE>
* object is recommended for creating new code. The <CODE>QueueReceiver * object is recommended for creating new code. The <CODE>QueueReceiver
* </CODE> is provided to support existing code. * </CODE>
* * is provided to support existing code.
*
* @see javax.jms.Session#createConsumer(javax.jms.Destination, String) * @see javax.jms.Session#createConsumer(javax.jms.Destination, String)
* @see javax.jms.Session#createConsumer(javax.jms.Destination) * @see javax.jms.Session#createConsumer(javax.jms.Destination)
* @see javax.jms.QueueSession#createReceiver(Queue, String) * @see javax.jms.QueueSession#createReceiver(Queue, String)
@ -54,8 +52,7 @@ import javax.jms.QueueReceiver;
* @see javax.jms.MessageConsumer * @see javax.jms.MessageConsumer
*/ */
public class ActiveMQQueueReceiver extends ActiveMQMessageConsumer implements public class ActiveMQQueueReceiver extends ActiveMQMessageConsumer implements QueueReceiver {
QueueReceiver {
/** /**
* @param theSession * @param theSession
@ -63,26 +60,28 @@ public class ActiveMQQueueReceiver extends ActiveMQMessageConsumer implements
* @param destination * @param destination
* @param messageSelector * @param messageSelector
* @param prefetch * @param prefetch
* @param asyncDispatch * @param asyncDispatch
* @throws JMSException * @throws JMSException
*/ */
protected ActiveMQQueueReceiver(ActiveMQSession theSession, protected ActiveMQQueueReceiver(ActiveMQSession theSession, ConsumerId consumerId,
ConsumerId consumerId, ActiveMQDestination destination, String selector, int prefetch, int maximumPendingMessageCount, boolean asyncDispatch) ActiveMQDestination destination, String selector, int prefetch,
throws JMSException { int maximumPendingMessageCount, boolean asyncDispatch)
super(theSession, consumerId, destination, null, selector, prefetch, maximumPendingMessageCount, false, false, asyncDispatch); throws JMSException {
super(theSession, consumerId, destination, null, selector, prefetch, maximumPendingMessageCount,
false, false, asyncDispatch);
} }
/** /**
* Gets the <CODE>Queue</CODE> associated with this queue receiver. * Gets the <CODE>Queue</CODE> associated with this queue receiver.
* *
* @return this receiver's <CODE>Queue</CODE> * @return this receiver's <CODE>Queue</CODE>
* @throws JMSException if the JMS provider fails to get the queue for this queue * @throws JMSException if the JMS provider fails to get the queue for this
* receiver due to some internal error. * queue receiver due to some internal error.
*/ */
public Queue getQueue() throws JMSException { public Queue getQueue() throws JMSException {
checkClosed(); checkClosed();
return (Queue) super.getDestination(); return (Queue)super.getDestination();
} }
} }

View File

@ -26,47 +26,46 @@ import org.apache.activemq.command.ActiveMQDestination;
/** /**
* A client uses a <CODE>QueueSender</CODE> object to send messages to a * A client uses a <CODE>QueueSender</CODE> object to send messages to a
* queue. * queue. <p/>
* <p/>
* <P> * <P>
* Normally, the <CODE>Queue</CODE> is specified when a <CODE>QueueSender * Normally, the <CODE>Queue</CODE> is specified when a <CODE>QueueSender
* </CODE> is created. In this case, an attempt to use the <CODE>send</CODE> * </CODE>
* methods for an unidentified <CODE>QueueSender</CODE> will throw a <CODE> * is created. In this case, an attempt to use the <CODE>send</CODE> methods
* for an unidentified <CODE>QueueSender</CODE> will throw a <CODE>
* java.lang.UnsupportedOperationException</CODE>. * java.lang.UnsupportedOperationException</CODE>.
* <p/> * <p/>
* <P> * <P>
* If the <CODE>QueueSender</CODE> is created with an unidentified <CODE> * If the <CODE>QueueSender</CODE> is created with an unidentified <CODE>
* Queue</CODE>, an attempt to use the <CODE>send</CODE> methods that * Queue</CODE>,
* assume that the <CODE>Queue</CODE> has been identified will throw a <CODE> * an attempt to use the <CODE>send</CODE> methods that assume that the
* <CODE>Queue</CODE> has been identified will throw a <CODE>
* java.lang.UnsupportedOperationException</CODE>. * java.lang.UnsupportedOperationException</CODE>.
* <p/> * <p/>
* <P> * <P>
* During the execution of its <CODE>send</CODE> method, a message must not * During the execution of its <CODE>send</CODE> method, a message must not be
* be changed by other threads within the client. If the message is modified, * changed by other threads within the client. If the message is modified, the
* the result of the <CODE>send</CODE> is undefined. * result of the <CODE>send</CODE> is undefined. <p/>
* <p/>
* <P> * <P>
* After sending a message, a client may retain and modify it without affecting * After sending a message, a client may retain and modify it without affecting
* the message that has been sent. The same message object may be sent multiple * the message that has been sent. The same message object may be sent multiple
* times. * times. <p/>
* <p/>
* <P> * <P>
* The following message headers are set as part of sending a message: <code>JMSDestination</code>, * The following message headers are set as part of sending a message:
* <code>JMSDeliveryMode</code>,<code>JMSExpiration</code>,<code>JMSPriority</code>, * <code>JMSDestination</code>, <code>JMSDeliveryMode</code>,<code>JMSExpiration</code>,<code>JMSPriority</code>,
* <code>JMSMessageID</code> and <code>JMSTimeStamp</code>. When the * <code>JMSMessageID</code> and <code>JMSTimeStamp</code>. When the
* message is sent, the values of these headers are ignored. After the * message is sent, the values of these headers are ignored. After the
* completion of the <CODE>send</CODE>, the headers hold the values * completion of the <CODE>send</CODE>, the headers hold the values specified
* specified by the method sending the message. It is possible for the <code>send</code> * by the method sending the message. It is possible for the <code>send</code>
* method not to set <code>JMSMessageID</code> and <code>JMSTimeStamp</code> * method not to set <code>JMSMessageID</code> and <code>JMSTimeStamp</code>
* if the setting of these headers is explicitly disabled by the <code>MessageProducer.setDisableMessageID</code> * if the setting of these headers is explicitly disabled by the
* or <code>MessageProducer.setDisableMessageTimestamp</code> method. * <code>MessageProducer.setDisableMessageID</code> or
* <p/> * <code>MessageProducer.setDisableMessageTimestamp</code> method. <p/>
* <P> * <P>
* Creating a <CODE>MessageProducer</CODE> provides the same features as * Creating a <CODE>MessageProducer</CODE> provides the same features as
* creating a <CODE>QueueSender</CODE>. A <CODE>MessageProducer</CODE> * creating a <CODE>QueueSender</CODE>. A <CODE>MessageProducer</CODE>
* object is recommended when creating new code. The <CODE>QueueSender</CODE> * object is recommended when creating new code. The <CODE>QueueSender</CODE>
* is provided to support existing code. * is provided to support existing code.
* *
* @see javax.jms.MessageProducer * @see javax.jms.MessageProducer
* @see javax.jms.QueueSession#createSender(Queue) * @see javax.jms.QueueSession#createSender(Queue)
*/ */
@ -74,38 +73,35 @@ import org.apache.activemq.command.ActiveMQDestination;
public class ActiveMQQueueSender extends ActiveMQMessageProducer implements QueueSender { public class ActiveMQQueueSender extends ActiveMQMessageProducer implements QueueSender {
protected ActiveMQQueueSender(ActiveMQSession session, ActiveMQDestination destination) protected ActiveMQQueueSender(ActiveMQSession session, ActiveMQDestination destination)
throws JMSException { throws JMSException {
super(session, super(session, session.getNextProducerId(), destination);
session.getNextProducerId(),
destination);
} }
/** /**
* Gets the queue associated with this <CODE>QueueSender</CODE>. * Gets the queue associated with this <CODE>QueueSender</CODE>.
* *
* @return this sender's queue * @return this sender's queue
* @throws JMSException if the JMS provider fails to get the queue for this * @throws JMSException if the JMS provider fails to get the queue for this
* <CODE>QueueSender</CODE> due to some internal error. * <CODE>QueueSender</CODE> due to some internal error.
*/ */
public Queue getQueue() throws JMSException { public Queue getQueue() throws JMSException {
return (Queue) super.getDestination(); return (Queue)super.getDestination();
} }
/** /**
* Sends a message to a queue for an unidentified message producer. Uses * Sends a message to a queue for an unidentified message producer. Uses the
* the <CODE>QueueSender</CODE>'s default delivery mode, priority, and * <CODE>QueueSender</CODE>'s default delivery mode, priority, and time
* time to live. * to live. <p/>
* <p/>
* <P> * <P>
* Typically, a message producer is assigned a queue at creation time; * Typically, a message producer is assigned a queue 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 queue be supplied every time a message is sent. * require that the queue be supplied every time a message is sent.
* *
* @param queue the queue to send this message to * @param queue the queue to send this message to
* @param message the message to send * @param message the message to send
* @throws JMSException if the JMS provider fails to send the message due to some * @throws JMSException if the JMS provider fails to send the message due to
* internal error. * some internal error.
* @see javax.jms.MessageProducer#getDeliveryMode() * @see javax.jms.MessageProducer#getDeliveryMode()
* @see javax.jms.MessageProducer#getTimeToLive() * @see javax.jms.MessageProducer#getTimeToLive()
* @see javax.jms.MessageProducer#getPriority() * @see javax.jms.MessageProducer#getPriority()
@ -117,28 +113,23 @@ public class ActiveMQQueueSender extends ActiveMQMessageProducer implements Queu
/** /**
* Sends a message to a queue for an unidentified message producer, * Sends a message to a queue for an unidentified message producer,
* specifying delivery mode, priority and time to live. * specifying delivery mode, priority and time to live. <p/>
* <p/>
* <P> * <P>
* Typically, a message producer is assigned a queue at creation time; * Typically, a message producer is assigned a queue 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 queue be supplied every time a message is sent. * require that the queue be supplied every time a message is sent.
* *
* @param queue the queue to send this message to * @param queue the queue 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
* @param priority the priority for this message * @param priority the priority for this message
* @param timeToLive the message's lifetime (in milliseconds) * @param timeToLive the message's lifetime (in milliseconds)
* @throws JMSException if the JMS provider fails to send the message due to some * @throws JMSException if the JMS provider fails to send the message due to
* internal error. * some internal error.
*/ */
public void send(Queue queue, Message message, int deliveryMode, int priority, long timeToLive) public void send(Queue queue, Message message, int deliveryMode, int priority, long timeToLive)
throws JMSException { throws JMSException {
super.send(queue, super.send(queue, message, deliveryMode, priority, timeToLive);
message,
deliveryMode,
priority,
timeToLive);
} }
} }

View File

@ -96,8 +96,8 @@ public class ActiveMQSessionExecutor implements Task {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
} else { } else {
while (iterate()) while (iterate()) {
; }
} }
} }
} }
@ -128,8 +128,9 @@ public class ActiveMQSessionExecutor implements Task {
synchronized void start() { synchronized void start() {
if (!messageQueue.isRunning()) { if (!messageQueue.isRunning()) {
messageQueue.start(); messageQueue.start();
if (hasUncomsumedMessages()) if (hasUncomsumedMessages()) {
wakeup(); wakeup();
}
} }
} }

View File

@ -104,8 +104,9 @@ public class ActiveMQTopicSession implements TopicSession {
* @throws JMSException * @throws JMSException
*/ */
public MessageConsumer createConsumer(Destination destination) throws JMSException { public MessageConsumer createConsumer(Destination destination) throws JMSException {
if (destination instanceof Queue) if (destination instanceof Queue) {
throw new InvalidDestinationException("Queues are not supported by a TopicSession"); throw new InvalidDestinationException("Queues are not supported by a TopicSession");
}
return next.createConsumer(destination); return next.createConsumer(destination);
} }
@ -116,8 +117,9 @@ public class ActiveMQTopicSession implements TopicSession {
* @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 Queue) if (destination instanceof Queue) {
throw new InvalidDestinationException("Queues are not supported by a TopicSession"); throw new InvalidDestinationException("Queues are not supported by a TopicSession");
}
return next.createConsumer(destination, messageSelector); return next.createConsumer(destination, messageSelector);
} }
@ -129,8 +131,9 @@ public class ActiveMQTopicSession implements TopicSession {
* @throws JMSException * @throws JMSException
*/ */
public MessageConsumer createConsumer(Destination destination, String messageSelector, boolean NoLocal) throws JMSException { public MessageConsumer createConsumer(Destination destination, String messageSelector, boolean NoLocal) throws JMSException {
if (destination instanceof Queue) if (destination instanceof Queue) {
throw new InvalidDestinationException("Queues are not supported by a TopicSession"); throw new InvalidDestinationException("Queues are not supported by a TopicSession");
}
return next.createConsumer(destination, messageSelector, NoLocal); return next.createConsumer(destination, messageSelector, NoLocal);
} }
@ -195,8 +198,9 @@ public class ActiveMQTopicSession implements TopicSession {
* @throws JMSException * @throws JMSException
*/ */
public MessageProducer createProducer(Destination destination) throws JMSException { public MessageProducer createProducer(Destination destination) throws JMSException {
if (destination instanceof Queue) if (destination instanceof Queue) {
throw new InvalidDestinationException("Queues are not supported by a TopicSession"); throw new InvalidDestinationException("Queues are not supported by a TopicSession");
}
return next.createProducer(destination); return next.createProducer(destination);
} }

View File

@ -20,20 +20,21 @@ import javax.jms.JMSException;
/** /**
* Provides a uniform interface that can be used to close all the JMS obejcts * Provides a uniform interface that can be used to close all the JMS obejcts
* that provide a close() method. Useful for when you want to collect * that provide a close() method. Useful for when you want to collect a
* a heterogeous set of JMS object in a collection to be closed at a later time. * heterogeous set of JMS object in a collection to be closed at a later time.
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public interface Closeable { public interface Closeable {
/** /**
* Closes a JMS object. * Closes a JMS object.
* <P> * <P>
* Many JMS objects are closeable such as Connections, Sessions, Consumers and Producers. * Many JMS objects are closeable such as Connections, Sessions, Consumers
* * and Producers.
* @throws JMSException if the JMS provider fails to close the object due to *
* some internal error. * @throws JMSException if the JMS provider fails to close the object due to
*/ * some internal error.
public void close() throws JMSException; */
public void close() throws JMSException;
} }

View File

@ -27,27 +27,31 @@ import javax.jms.JMSException;
import javax.jms.Topic; import javax.jms.Topic;
/** /**
* The StreamConnection interface allows you to send and receive * The StreamConnection interface allows you to send and receive data from a
* data from a Destination in using standard java InputStream and OutputStream * Destination in using standard java InputStream and OutputStream objects. It's
* objects. It's best use case is to send and receive large amounts of data * best use case is to send and receive large amounts of data that would be to
* that would be to large to hold in a single JMS message. * large to hold in a single JMS message.
* *
* @version $Revision$ * @version $Revision$
*/ */
public interface StreamConnection extends Connection { public interface StreamConnection extends Connection {
public InputStream createInputStream(Destination dest) throws JMSException; public InputStream createInputStream(Destination dest) throws JMSException;
public InputStream createInputStream(Destination dest, String messageSelector) throws JMSException; public InputStream createInputStream(Destination dest, String messageSelector) throws JMSException;
public InputStream createInputStream(Destination dest, String messageSelector, boolean noLocal) throws JMSException; public InputStream createInputStream(Destination dest, String messageSelector, boolean noLocal) throws JMSException;
public InputStream createDurableInputStream(Topic dest, String name) throws JMSException; public InputStream createDurableInputStream(Topic dest, String name) throws JMSException;
public InputStream createDurableInputStream(Topic dest, String name, String messageSelector) throws JMSException; public InputStream createDurableInputStream(Topic dest, String name, String messageSelector) throws JMSException;
public InputStream createDurableInputStream(Topic dest, String name, String messageSelector, boolean noLocal) throws JMSException; public InputStream createDurableInputStream(Topic dest, String name, String messageSelector, boolean noLocal) throws JMSException;
public OutputStream createOutputStream(Destination dest) throws JMSException; public OutputStream createOutputStream(Destination dest) throws JMSException;
public OutputStream createOutputStream(Destination dest, Map streamProperties, int deliveryMode,
int priority, long timeToLive) throws JMSException; public OutputStream createOutputStream(Destination dest, Map streamProperties, int deliveryMode, int priority, long timeToLive) throws JMSException;
/** /**
* Unsubscribes a durable subscription that has been created by a client. * Unsubscribes a durable subscription that has been created by a client.
* <P> * <P>
@ -55,17 +59,16 @@ public interface StreamConnection extends Connection {
* subscriber by its provider. * subscriber by its provider.
* <P> * <P>
* It is erroneous for a client to delete a durable subscription while there * It is erroneous for a client to delete a durable subscription while there
* is an active <CODE>MessageConsumer </CODE> or <CODE>TopicSubscriber</CODE> * is an active <CODE>MessageConsumer </CODE> or
* for the subscription, or while a consumed message is part of a pending * <CODE>TopicSubscriber</CODE> for the subscription, or while a consumed
* transaction or has not been acknowledged in the session. * message is part of a pending transaction or has not been acknowledged in
* the session.
* *
* @param name * @param name the name used to identify this subscription
* the name used to identify this subscription * @throws JMSException if the session fails to unsubscribe to the durable
* @throws JMSException * subscription due to some internal error.
* if the session fails to unsubscribe to the durable * @throws InvalidDestinationException if an invalid subscription name is
* subscription due to some internal error. * specified.
* @throws InvalidDestinationException
* if an invalid subscription name is specified.
* @since 1.1 * @since 1.1
*/ */
public void unsubscribe(String name) throws JMSException; public void unsubscribe(String name) throws JMSException;

View File

@ -50,17 +50,19 @@ public class AdvisorySupport {
} }
public static ActiveMQTopic getConsumerAdvisoryTopic(ActiveMQDestination destination) { public static ActiveMQTopic getConsumerAdvisoryTopic(ActiveMQDestination destination) {
if (destination.isQueue()) if (destination.isQueue()) {
return new ActiveMQTopic(QUEUE_CONSUMER_ADVISORY_TOPIC_PREFIX + destination.getPhysicalName()); return new ActiveMQTopic(QUEUE_CONSUMER_ADVISORY_TOPIC_PREFIX + destination.getPhysicalName());
else } else {
return new ActiveMQTopic(TOPIC_CONSUMER_ADVISORY_TOPIC_PREFIX + destination.getPhysicalName()); return new ActiveMQTopic(TOPIC_CONSUMER_ADVISORY_TOPIC_PREFIX + destination.getPhysicalName());
}
} }
public static ActiveMQTopic getProducerAdvisoryTopic(ActiveMQDestination destination) { public static ActiveMQTopic getProducerAdvisoryTopic(ActiveMQDestination destination) {
if (destination.isQueue()) if (destination.isQueue()) {
return new ActiveMQTopic(QUEUE_PRODUCER_ADVISORY_TOPIC_PREFIX + destination.getPhysicalName()); return new ActiveMQTopic(QUEUE_PRODUCER_ADVISORY_TOPIC_PREFIX + destination.getPhysicalName());
else } else {
return new ActiveMQTopic(TOPIC_PRODUCER_ADVISORY_TOPIC_PREFIX + destination.getPhysicalName()); return new ActiveMQTopic(TOPIC_PRODUCER_ADVISORY_TOPIC_PREFIX + destination.getPhysicalName());
}
} }
public static ActiveMQTopic getExpiredMessageTopic(ActiveMQDestination destination) { public static ActiveMQTopic getExpiredMessageTopic(ActiveMQDestination destination) {

View File

@ -30,8 +30,8 @@ import javax.jms.JMSException;
import org.apache.activemq.command.ActiveMQBlobMessage; import org.apache.activemq.command.ActiveMQBlobMessage;
/** /**
* A default implementation of {@link BlobUploadStrategy} which uses the URL class to upload * A default implementation of {@link BlobUploadStrategy} which uses the URL
* files or streams to a remote URL * class to upload files or streams to a remote URL
*/ */
public class DefaultBlobUploadStrategy implements BlobUploadStrategy { public class DefaultBlobUploadStrategy implements BlobUploadStrategy {
private BlobTransferPolicy transferPolicy; private BlobTransferPolicy transferPolicy;
@ -50,30 +50,31 @@ public class DefaultBlobUploadStrategy implements BlobUploadStrategy {
HttpURLConnection connection = (HttpURLConnection)url.openConnection(); HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("PUT"); connection.setRequestMethod("PUT");
connection.setDoOutput(true); connection.setDoOutput(true);
// use chunked mode or otherwise URLConnection loads everything into memory // use chunked mode or otherwise URLConnection loads everything into
// memory
// (chunked mode not supported before JRE 1.5) // (chunked mode not supported before JRE 1.5)
connection.setChunkedStreamingMode(transferPolicy.getBufferSize()); connection.setChunkedStreamingMode(transferPolicy.getBufferSize());
OutputStream os = connection.getOutputStream(); OutputStream os = connection.getOutputStream();
byte[] buf = new byte[transferPolicy.getBufferSize()]; byte[] buf = new byte[transferPolicy.getBufferSize()];
for (int c = fis.read(buf); c != -1; c = fis.read(buf)) { for (int c = fis.read(buf); c != -1; c = fis.read(buf)) {
os.write(buf, 0, c); os.write(buf, 0, c);
os.flush(); os.flush();
} }
os.close(); os.close();
fis.close(); fis.close();
if (!isSuccessfulCode(connection.getResponseCode())) { if (!isSuccessfulCode(connection.getResponseCode())) {
throw new IOException("PUT was not successful: " throw new IOException("PUT was not successful: " + connection.getResponseCode() + " "
+ connection.getResponseCode() + " " + connection.getResponseMessage()); + connection.getResponseMessage());
} }
return url; return url;
} }
public void deleteFile(ActiveMQBlobMessage message) throws IOException, JMSException { public void deleteFile(ActiveMQBlobMessage message) throws IOException, JMSException {
URL url = createUploadURL(message); URL url = createUploadURL(message);
HttpURLConnection connection = (HttpURLConnection)url.openConnection(); HttpURLConnection connection = (HttpURLConnection)url.openConnection();
@ -82,16 +83,16 @@ public class DefaultBlobUploadStrategy implements BlobUploadStrategy {
connection.disconnect(); connection.disconnect();
if (!isSuccessfulCode(connection.getResponseCode())) { if (!isSuccessfulCode(connection.getResponseCode())) {
throw new IOException("DELETE was not successful: " throw new IOException("DELETE was not successful: " + connection.getResponseCode() + " "
+ connection.getResponseCode() + " " + connection.getResponseMessage()); + connection.getResponseMessage());
} }
} }
private boolean isSuccessfulCode(int responseCode) {
return responseCode >= 200 && responseCode < 300; // 2xx => successful
}
protected URL createUploadURL(ActiveMQBlobMessage message) throws JMSException, MalformedURLException { private boolean isSuccessfulCode(int responseCode) {
return responseCode >= 200 && responseCode < 300; // 2xx => successful
}
protected URL createUploadURL(ActiveMQBlobMessage message) throws JMSException, MalformedURLException {
return new URL(transferPolicy.getUploadUrl() + message.getMessageId().toString()); return new URL(transferPolicy.getUploadUrl() + message.getMessageId().toString());
} }
} }

View File

@ -23,26 +23,28 @@ import org.apache.activemq.util.FactoryFinder;
import org.apache.activemq.util.IOExceptionSupport; import org.apache.activemq.util.IOExceptionSupport;
/** /**
* A helper class to create a fully configured broker service using a URI. * A helper class to create a fully configured broker service using a URI. The
* The list of currently supported URI syntaxes is described * list of currently supported URI syntaxes is described <a
* <a href="http://activemq.apache.org/how-do-i-embed-a-broker-inside-a-connection.html">here</a> * href="http://activemq.apache.org/how-do-i-embed-a-broker-inside-a-connection.html">here</a>
* *
* @version $Revision$ * @version $Revision$
*/ */
public class BrokerFactory { public class BrokerFactory {
static final private FactoryFinder brokerFactoryHandlerFinder = new FactoryFinder("META-INF/services/org/apache/activemq/broker/"); static final private FactoryFinder brokerFactoryHandlerFinder = new FactoryFinder(
"META-INF/services/org/apache/activemq/broker/");
public static BrokerFactoryHandler createBrokerFactoryHandler(String type) throws IOException { public static BrokerFactoryHandler createBrokerFactoryHandler(String type) throws IOException {
try { try {
return (BrokerFactoryHandler)brokerFactoryHandlerFinder.newInstance(type); return (BrokerFactoryHandler)brokerFactoryHandlerFinder.newInstance(type);
} catch (Throwable e) { } catch (Throwable e) {
throw IOExceptionSupport.create("Could load "+type+" factory:"+e, e); throw IOExceptionSupport.create("Could load " + type + " factory:" + e, e);
} }
} }
/** /**
* Creates a broker from a URI configuration * Creates a broker from a URI configuration
*
* @param brokerURI the URI scheme to configure the broker * @param brokerURI the URI scheme to configure the broker
* @throws Exception * @throws Exception
*/ */
@ -52,14 +54,17 @@ public class BrokerFactory {
/** /**
* Creates a broker from a URI configuration * Creates a broker from a URI configuration
*
* @param brokerURI the URI scheme to configure the broker * @param brokerURI the URI scheme to configure the broker
* @param startBroker whether or not the broker should have its {@link BrokerService#start()} method called after construction * @param startBroker whether or not the broker should have its
* {@link BrokerService#start()} method called after
* construction
* @throws Exception * @throws Exception
*/ */
public static BrokerService createBroker(URI brokerURI, boolean startBroker) throws Exception { public static BrokerService createBroker(URI brokerURI, boolean startBroker) throws Exception {
if( brokerURI.getScheme() == null ) if (brokerURI.getScheme() == null) {
throw new IllegalArgumentException("Invalid broker URI, no scheme specified: "+brokerURI); throw new IllegalArgumentException("Invalid broker URI, no scheme specified: " + brokerURI);
}
BrokerFactoryHandler handler = createBrokerFactoryHandler(brokerURI.getScheme()); BrokerFactoryHandler handler = createBrokerFactoryHandler(brokerURI.getScheme());
BrokerService broker = handler.createBroker(brokerURI); BrokerService broker = handler.createBroker(brokerURI);
if (startBroker) { if (startBroker) {
@ -68,9 +73,9 @@ public class BrokerFactory {
return broker; return broker;
} }
/** /**
* Creates a broker from a URI configuration * Creates a broker from a URI configuration
*
* @param brokerURI the URI scheme to configure the broker * @param brokerURI the URI scheme to configure the broker
* @throws Exception * @throws Exception
*/ */
@ -78,16 +83,17 @@ public class BrokerFactory {
return createBroker(new URI(brokerURI)); return createBroker(new URI(brokerURI));
} }
/** /**
* Creates a broker from a URI configuration * Creates a broker from a URI configuration
*
* @param brokerURI the URI scheme to configure the broker * @param brokerURI the URI scheme to configure the broker
* @param startBroker whether or not the broker should have its {@link BrokerService#start()} method called after construction * @param startBroker whether or not the broker should have its
* {@link BrokerService#start()} method called after
* construction
* @throws Exception * @throws Exception
*/ */
public static BrokerService createBroker(String brokerURI, boolean startBroker) throws Exception { public static BrokerService createBroker(String brokerURI, boolean startBroker) throws Exception {
return createBroker(new URI(brokerURI), startBroker); return createBroker(new URI(brokerURI), startBroker);
} }
} }

View File

@ -17,29 +17,30 @@
package org.apache.activemq.broker; package org.apache.activemq.broker;
/** /**
* This exception is thrown by the broker when you try to use it after it has been stopped. * This exception is thrown by the broker when you try to use it after it has
* * been stopped.
*
* @author chirino * @author chirino
*/ */
public class BrokerStoppedException extends IllegalStateException { public class BrokerStoppedException extends IllegalStateException {
private static final long serialVersionUID = -3435230276850902220L; private static final long serialVersionUID = -3435230276850902220L;
public BrokerStoppedException() { public BrokerStoppedException() {
super(); super();
} }
public BrokerStoppedException(String message, Throwable cause) { public BrokerStoppedException(String message, Throwable cause) {
super(message); super(message);
initCause(cause); initCause(cause);
} }
public BrokerStoppedException(String s) { public BrokerStoppedException(String s) {
super(s); super(s);
} }
public BrokerStoppedException(Throwable cause) { public BrokerStoppedException(Throwable cause) {
initCause(cause); initCause(cause);
} }
} }

View File

@ -24,7 +24,6 @@ import org.apache.activemq.command.Command;
import org.apache.activemq.command.Response; import org.apache.activemq.command.Response;
/** /**
*
* @version $Revision: 1.5 $ * @version $Revision: 1.5 $
*/ */
public interface Connection extends Service { public interface Connection extends Service {
@ -37,8 +36,7 @@ public interface Connection extends Service {
/** /**
* Sends a message to the client. * Sends a message to the client.
* *
* @param message * @param message the message to send to the client.
* the message to send to the client.
*/ */
public void dispatchSync(Command message); public void dispatchSync(Command message);
@ -87,12 +85,12 @@ public interface Connection extends Service {
* Returns the number of messages to be dispatched to this connection * Returns the number of messages to be dispatched to this connection
*/ */
public int getDispatchQueueSize(); public int getDispatchQueueSize();
/** /**
* Returns the statistics for this connection * Returns the statistics for this connection
*/ */
public ConnectionStatistics getStatistics(); public ConnectionStatistics getStatistics();
/** /**
* @return true if the Connection will process control commands * @return true if the Connection will process control commands
*/ */
@ -101,10 +99,10 @@ public interface Connection extends Service {
/** /**
* @return the source address for this connection * @return the source address for this connection
*/ */
public String getRemoteAddress(); public String getRemoteAddress();
public void serviceExceptionAsync(IOException e); public void serviceExceptionAsync(IOException e);
public String getConnectionId(); public String getConnectionId();
} }

View File

@ -97,7 +97,8 @@ import org.apache.commons.logging.LogFactory;
public class TransportConnection implements Service, Connection, Task, CommandVisitor { public class TransportConnection implements Service, Connection, Task, CommandVisitor {
private static final Log LOG = LogFactory.getLog(TransportConnection.class); private static final Log LOG = LogFactory.getLog(TransportConnection.class);
private static final Log TRANSPORTLOG = LogFactory.getLog(TransportConnection.class.getName() + ".Transport"); private static final Log TRANSPORTLOG = LogFactory.getLog(TransportConnection.class.getName()
+ ".Transport");
private static final Log SERVICELOG = LogFactory.getLog(TransportConnection.class.getName() + ".Service"); private static final Log SERVICELOG = LogFactory.getLog(TransportConnection.class.getName() + ".Service");
// Keeps track of the broker and connector that created this connection. // Keeps track of the broker and connector that created this connection.
protected final Broker broker; protected final Broker broker;
@ -190,7 +191,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
* @param taskRunnerFactory - can be null if you want direct dispatch to the * @param taskRunnerFactory - can be null if you want direct dispatch to the
* transport else commands are sent async. * transport else commands are sent async.
*/ */
public TransportConnection(TransportConnector connector, final Transport transport, Broker broker, TaskRunnerFactory taskRunnerFactory) { public TransportConnection(TransportConnector connector, final Transport transport, Broker broker,
TaskRunnerFactory taskRunnerFactory) {
this.connector = connector; this.connector = connector;
this.broker = broker; this.broker = broker;
RegionBroker rb = (RegionBroker)broker.getAdaptor(RegionBroker.class); RegionBroker rb = (RegionBroker)broker.getAdaptor(RegionBroker.class);
@ -270,7 +272,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
else if (e.getClass() == BrokerStoppedException.class) { 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);
@ -400,7 +403,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
} }
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);
@ -469,7 +473,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
return broker.messagePull(lookupConnectionState(pull.getConsumerId()).getContext(), pull); return broker.messagePull(lookupConnectionState(pull.getConsumerId()).getContext(), pull);
} }
public Response processMessageDispatchNotification(MessageDispatchNotification notification) throws Exception { public Response processMessageDispatchNotification(MessageDispatchNotification notification)
throws Exception {
broker.processDispatchNotification(notification); broker.processDispatchNotification(notification);
return null; return null;
} }
@ -498,7 +503,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
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);
@ -517,7 +524,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
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);
@ -532,7 +541,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
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);
@ -551,7 +562,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
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);
@ -628,7 +641,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
if (state.getConnection() != this) { if (state.getConnection() != this) {
LOG.debug("Killing previous stale connection: " + state.getConnection().getRemoteAddress()); LOG.debug("Killing previous stale connection: " + state.getConnection().getRemoteAddress());
state.getConnection().stop(); state.getConnection().stop();
LOG.debug("Connection " + getRemoteAddress() + " taking over previous connection: " + state.getConnection().getRemoteAddress()); LOG.debug("Connection " + getRemoteAddress() + " taking over previous connection: "
+ state.getConnection().getRemoteAddress());
state.setConnection(this); state.setConnection(this);
state.reset(info); state.reset(info);
} }
@ -751,7 +765,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
} }
protected void processDispatch(Command command) throws IOException { protected void processDispatch(Command command) throws IOException {
final MessageDispatch messageDispatch = (MessageDispatch)(command.isMessageDispatch() ? command : null); final MessageDispatch messageDispatch = (MessageDispatch)(command.isMessageDispatch()
? command : null);
try { try {
if (!disposed.get()) { if (!disposed.get()) {
if (messageDispatch != null) { if (messageDispatch != null) {
@ -831,7 +846,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
transport.start(); transport.start();
if (taskRunnerFactory != null) { if (taskRunnerFactory != null) {
taskRunner = taskRunnerFactory.createTaskRunner(this, "ActiveMQ Connection Dispatcher: " + getRemoteAddress()); taskRunner = taskRunnerFactory.createTaskRunner(this, "ActiveMQ Connection Dispatcher: "
+ getRemoteAddress());
} else { } else {
taskRunner = null; taskRunner = null;
} }
@ -1098,7 +1114,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
uri = URISupport.createURIWithQuery(uri, URISupport.createQueryString(map)); uri = URISupport.createURIWithQuery(uri, URISupport.createQueryString(map));
Transport localTransport = TransportFactory.connect(uri); Transport localTransport = TransportFactory.connect(uri);
Transport remoteBridgeTransport = new ResponseCorrelator(transport); Transport remoteBridgeTransport = new ResponseCorrelator(transport);
duplexBridge = NetworkBridgeFactory.createBridge(config, localTransport, remoteBridgeTransport); duplexBridge = NetworkBridgeFactory.createBridge(config, localTransport,
remoteBridgeTransport);
// now turn duplex off this side // now turn duplex off this side
info.setDuplexConnection(false); info.setDuplexConnection(false);
duplexBridge.setCreatedByDuplex(true); duplexBridge.setCreatedByDuplex(true);
@ -1163,7 +1180,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
ProducerState producerState = ss.getProducerState(id); ProducerState producerState = ss.getProducerState(id);
if (producerState != null && producerState.getInfo() != null) { if (producerState != null && producerState.getInfo() != null) {
ProducerInfo info = producerState.getInfo(); ProducerInfo info = producerState.getInfo();
result.setMutable(info.getDestination() == null || info.getDestination().isComposite()); result.setMutable(info.getDestination() == null
|| info.getDestination().isComposite());
} }
} }
producerExchanges.put(id, result); producerExchanges.put(id, result);
@ -1267,7 +1285,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
// //
// ///////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////////
protected TransportConnectionState registerConnectionState(ConnectionId connectionId, TransportConnectionState state) { protected TransportConnectionState registerConnectionState(ConnectionId connectionId,
TransportConnectionState state) {
TransportConnectionState rc = connectionState; TransportConnectionState rc = connectionState;
connectionState = state; connectionState = state;
return rc; return rc;
@ -1290,35 +1309,44 @@ 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

@ -31,16 +31,16 @@ import org.apache.activemq.command.ConsumerInfo;
import org.apache.activemq.command.RemoveSubscriptionInfo; import org.apache.activemq.command.RemoveSubscriptionInfo;
public class BrokerView implements BrokerViewMBean { public class BrokerView implements BrokerViewMBean {
final ManagedRegionBroker broker; final ManagedRegionBroker broker;
private final BrokerService brokerService; private final BrokerService brokerService;
private final AtomicInteger sessionIdCounter = new AtomicInteger(0); private final AtomicInteger sessionIdCounter = new AtomicInteger(0);
public BrokerView(BrokerService brokerService, ManagedRegionBroker managedBroker) throws Exception { public BrokerView(BrokerService brokerService, ManagedRegionBroker managedBroker) throws Exception {
this.brokerService = brokerService; this.brokerService = brokerService;
this.broker = managedBroker; this.broker = managedBroker;
} }
public ManagedRegionBroker getBroker() { public ManagedRegionBroker getBroker() {
return broker; return broker;
} }
@ -48,31 +48,35 @@ public class BrokerView implements BrokerViewMBean {
public String getBrokerId() { public String getBrokerId() {
return broker.getBrokerId().toString(); return broker.getBrokerId().toString();
} }
public void gc() throws Exception { public void gc() throws Exception {
brokerService.getBroker().gc(); brokerService.getBroker().gc();
} }
public void start() throws Exception { public void start() throws Exception {
brokerService.start(); brokerService.start();
} }
public void stop() throws Exception { public void stop() throws Exception {
brokerService.stop(); brokerService.stop();
} }
public long getTotalEnqueueCount() { public long getTotalEnqueueCount() {
return broker.getDestinationStatistics().getEnqueues().getCount(); return broker.getDestinationStatistics().getEnqueues().getCount();
} }
public long getTotalDequeueCount() { public long getTotalDequeueCount() {
return broker.getDestinationStatistics().getDequeues().getCount(); return broker.getDestinationStatistics().getDequeues().getCount();
} }
public long getTotalConsumerCount() { public long getTotalConsumerCount() {
return broker.getDestinationStatistics().getConsumers().getCount(); return broker.getDestinationStatistics().getConsumers().getCount();
} }
public long getTotalMessageCount() { public long getTotalMessageCount() {
return broker.getDestinationStatistics().getMessages().getCount(); return broker.getDestinationStatistics().getMessages().getCount();
} }
public long getTotalMessagesCached() { public long getTotalMessagesCached() {
return broker.getDestinationStatistics().getMessagesCached().getCount(); return broker.getDestinationStatistics().getMessagesCached().getCount();
} }
@ -80,71 +84,72 @@ public class BrokerView implements BrokerViewMBean {
public int getMemoryPercentageUsed() { public int getMemoryPercentageUsed() {
return brokerService.getMemoryManager().getPercentUsage(); return brokerService.getMemoryManager().getPercentUsage();
} }
public long getMemoryLimit() { public long getMemoryLimit() {
return brokerService.getMemoryManager().getLimit(); return brokerService.getMemoryManager().getLimit();
} }
public void setMemoryLimit(long limit) { public void setMemoryLimit(long limit) {
brokerService.getMemoryManager().setLimit(limit); brokerService.getMemoryManager().setLimit(limit);
} }
public void resetStatistics() { public void resetStatistics() {
broker.getDestinationStatistics().reset(); broker.getDestinationStatistics().reset();
} }
public void enableStatistics() { public void enableStatistics() {
broker.getDestinationStatistics().setEnabled(true); broker.getDestinationStatistics().setEnabled(true);
} }
public void disableStatistics() { public void disableStatistics() {
broker.getDestinationStatistics().setEnabled(false); broker.getDestinationStatistics().setEnabled(false);
}
public boolean isStatisticsEnabled() {
return broker.getDestinationStatistics().isEnabled();
} }
public boolean isStatisticsEnabled() {
return broker.getDestinationStatistics().isEnabled();
}
public void terminateJVM(int exitCode) { public void terminateJVM(int exitCode) {
System.exit(exitCode); System.exit(exitCode);
} }
public ObjectName[] getTopics(){ public ObjectName[] getTopics() {
return broker.getTopics(); return broker.getTopics();
} }
public ObjectName[] getQueues(){ public ObjectName[] getQueues() {
return broker.getQueues(); return broker.getQueues();
} }
public ObjectName[] getTemporaryTopics(){ public ObjectName[] getTemporaryTopics() {
return broker.getTemporaryTopics(); return broker.getTemporaryTopics();
} }
public ObjectName[] getTemporaryQueues(){ public ObjectName[] getTemporaryQueues() {
return broker.getTemporaryQueues(); return broker.getTemporaryQueues();
} }
public ObjectName[] getTopicSubscribers(){ public ObjectName[] getTopicSubscribers() {
return broker.getTemporaryTopicSubscribers();
}
public ObjectName[] getDurableTopicSubscribers(){
return broker.getDurableTopicSubscribers();
}
public ObjectName[] getQueueSubscribers(){
return broker.getQueueSubscribers();
}
public ObjectName[] getTemporaryTopicSubscribers(){
return broker.getTemporaryTopicSubscribers(); return broker.getTemporaryTopicSubscribers();
} }
public ObjectName[] getTemporaryQueueSubscribers(){ public ObjectName[] getDurableTopicSubscribers() {
return broker.getDurableTopicSubscribers();
}
public ObjectName[] getQueueSubscribers() {
return broker.getQueueSubscribers();
}
public ObjectName[] getTemporaryTopicSubscribers() {
return broker.getTemporaryTopicSubscribers();
}
public ObjectName[] getTemporaryQueueSubscribers() {
return broker.getTemporaryQueueSubscribers(); return broker.getTemporaryQueueSubscribers();
} }
public ObjectName[] getInactiveDurableTopicSubscribers(){ public ObjectName[] getInactiveDurableTopicSubscribers() {
return broker.getInactiveDurableTopicSubscribers(); return broker.getInactiveDurableTopicSubscribers();
} }
@ -157,14 +162,17 @@ public class BrokerView implements BrokerViewMBean {
} }
public void removeTopic(String name) throws Exception { public void removeTopic(String name) throws Exception {
broker.removeDestination(getConnectionContext(broker.getContextBroker()), new ActiveMQTopic(name), 1000); broker.removeDestination(getConnectionContext(broker.getContextBroker()), new ActiveMQTopic(name),
1000);
} }
public void removeQueue(String name) throws Exception { public void removeQueue(String name) throws Exception {
broker.removeDestination(getConnectionContext(broker.getContextBroker()), new ActiveMQQueue(name), 1000); broker.removeDestination(getConnectionContext(broker.getContextBroker()), new ActiveMQQueue(name),
1000);
} }
public ObjectName createDurableSubscriber(String clientId, String subscriberName, String topicName, String selector) throws Exception { public ObjectName createDurableSubscriber(String clientId, String subscriberName, String topicName,
String selector) throws Exception {
ConnectionContext context = new ConnectionContext(); ConnectionContext context = new ConnectionContext();
context.setBroker(broker); context.setBroker(broker);
context.setClientId(clientId); context.setClientId(clientId);
@ -194,11 +202,10 @@ public class BrokerView implements BrokerViewMBean {
context.setClientId(clientId); context.setClientId(clientId);
broker.removeSubscription(context, info); broker.removeSubscription(context, info);
} }
/** /**
* Returns the broker's administration connection context used for configuring the broker * Returns the broker's administration connection context used for
* at startup * configuring the broker at startup
*/ */
public static ConnectionContext getConnectionContext(Broker broker) { public static ConnectionContext getConnectionContext(Broker broker) {
ConnectionContext adminConnectionContext = broker.getAdminConnectionContext(); ConnectionContext adminConnectionContext = broker.getAdminConnectionContext();
@ -208,11 +215,12 @@ public class BrokerView implements BrokerViewMBean {
} }
return adminConnectionContext; return adminConnectionContext;
} }
/** /**
* Factory method to create the new administration connection context object. * Factory method to create the new administration connection context
* Note this method is here rather than inside a default broker implementation to * object. Note this method is here rather than inside a default broker
* ensure that the broker reference inside it is the outer most interceptor * implementation to ensure that the broker reference inside it is the outer
* most interceptor
*/ */
protected static ConnectionContext createAdminConnectionContext(Broker broker) { protected static ConnectionContext createAdminConnectionContext(Broker broker) {
ConnectionContext context = new ConnectionContext(); ConnectionContext context = new ConnectionContext();

View File

@ -33,36 +33,34 @@ public class ConnectionView implements ConnectionViewMBean {
public void stop() throws Exception { public void stop() throws Exception {
connection.stop(); connection.stop();
} }
/** /**
* @return true if the Connection is slow * @return true if the Connection is slow
*/ */
public boolean isSlow() { public boolean isSlow() {
return connection.isSlow(); return connection.isSlow();
} }
/** /**
* @return if after being marked, the Connection is still writing * @return if after being marked, the Connection is still writing
*/ */
public boolean isBlocked() { public boolean isBlocked() {
return connection.isBlocked(); return connection.isBlocked();
} }
/** /**
* @return true if the Connection is connected * @return true if the Connection is connected
*/ */
public boolean isConnected() { public boolean isConnected() {
return connection.isConnected(); return connection.isConnected();
} }
/** /**
* @return true if the Connection is active * @return true if the Connection is active
*/ */
public boolean isActive() { public boolean isActive() {
return connection.isActive(); return connection.isActive();
} }
/** /**
* Returns the number of messages to be dispatched to this connection * Returns the number of messages to be dispatched to this connection
@ -70,7 +68,7 @@ public class ConnectionView implements ConnectionViewMBean {
public int getDispatchQueueSize() { public int getDispatchQueueSize() {
return connection.getDispatchQueueSize(); return connection.getDispatchQueueSize();
} }
/** /**
* Resets the statistics * Resets the statistics
*/ */
@ -85,7 +83,7 @@ public class ConnectionView implements ConnectionViewMBean {
*/ */
public long getEnqueueCount() { public long getEnqueueCount() {
return connection.getStatistics().getEnqueues().getCount(); return connection.getStatistics().getEnqueues().getCount();
} }
/** /**
@ -97,12 +95,12 @@ public class ConnectionView implements ConnectionViewMBean {
return connection.getStatistics().getDequeues().getCount(); return connection.getStatistics().getDequeues().getCount();
} }
public String getRemoteAddress() { public String getRemoteAddress() {
return connection.getRemoteAddress(); return connection.getRemoteAddress();
} }
public String getConnectionId() { public String getConnectionId() {
return connection.getConnectionId(); return connection.getConnectionId();
} }
} }

View File

@ -47,10 +47,11 @@ public class ManagedTransportConnection extends TransportConnection {
private ConnectionViewMBean mbean; private ConnectionViewMBean mbean;
private ObjectName byClientIdName; private ObjectName byClientIdName;
private ObjectName byAddressName; private ObjectName byAddressName;
public ManagedTransportConnection(TransportConnector connector, Transport transport, Broker broker, TaskRunnerFactory factory, MBeanServer server, public ManagedTransportConnection(TransportConnector connector, Transport transport, Broker broker,
ObjectName connectorName) throws IOException { TaskRunnerFactory factory, MBeanServer server, ObjectName connectorName)
throws IOException {
super(connector, transport, broker, factory); super(connector, transport, broker, factory);
this.server = server; this.server = server;
this.connectorName = connectorName; this.connectorName = connectorName;
@ -64,12 +65,12 @@ public class ManagedTransportConnection extends TransportConnection {
setPendingStop(true); setPendingStop(true);
return; return;
} }
synchronized(this) { synchronized (this) {
unregisterMBean(byClientIdName); unregisterMBean(byClientIdName);
unregisterMBean(byAddressName); unregisterMBean(byAddressName);
byClientIdName=null; byClientIdName = null;
byAddressName=null; byAddressName = null;
} }
super.doStop(); super.doStop();
} }
@ -85,9 +86,9 @@ public class ManagedTransportConnection extends TransportConnection {
Response answer = super.processAddConnection(info); Response answer = super.processAddConnection(info);
String clientId = info.getClientId(); String clientId = info.getClientId();
if (clientId != null) { if (clientId != null) {
if(byClientIdName==null) { if (byClientIdName == null) {
byClientIdName = createByClientIdObjectName(clientId); byClientIdName = createByClientIdObjectName(clientId);
registerMBean(byClientIdName); registerMBean(byClientIdName);
} }
} }
return answer; return answer;
@ -96,24 +97,23 @@ public class ManagedTransportConnection extends TransportConnection {
// Implementation methods // Implementation methods
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
protected void registerMBean(ObjectName name) { protected void registerMBean(ObjectName name) {
if( name!=null ) { if (name != null) {
try { try {
server.registerMBean(mbean, name); server.registerMBean(mbean, name);
} catch (Throwable e) { } catch (Throwable e) {
log.warn("Failed to register MBean: "+name); log.warn("Failed to register MBean: " + name);
log.debug("Failure reason: "+e,e); log.debug("Failure reason: " + e, e);
} }
} }
} }
protected void unregisterMBean(ObjectName name) { protected void unregisterMBean(ObjectName name) {
if (name != null) { if (name != null) {
try { try {
server.unregisterMBean(name); server.unregisterMBean(name);
} } catch (Throwable e) {
catch (Throwable e) {
log.warn("Failed to unregister mbean: " + name); log.warn("Failed to unregister mbean: " + name);
log.debug("Failure reason: "+e,e); log.debug("Failure reason: " + e, e);
} }
} }
} }
@ -122,36 +122,29 @@ public class ManagedTransportConnection extends TransportConnection {
// Build the object name for the destination // Build the object name for the destination
Hashtable map = connectorName.getKeyPropertyList(); Hashtable map = connectorName.getKeyPropertyList();
try { try {
return new ObjectName( return new ObjectName(connectorName.getDomain() + ":" + "BrokerName="
connectorName.getDomain()+":"+ + JMXSupport.encodeObjectNamePart((String)map.get("BrokerName")) + ","
"BrokerName="+JMXSupport.encodeObjectNamePart((String) map.get("BrokerName"))+","+ + "Type=Connection," + "ConnectorName="
"Type=Connection,"+ + JMXSupport.encodeObjectNamePart((String)map.get("ConnectorName")) + ","
"ConnectorName="+JMXSupport.encodeObjectNamePart((String) map.get("ConnectorName"))+","+ + "ViewType=" + JMXSupport.encodeObjectNamePart(type) + "," + "Name="
"ViewType="+JMXSupport.encodeObjectNamePart(type)+","+ + JMXSupport.encodeObjectNamePart(value));
"Name="+JMXSupport.encodeObjectNamePart(value) } catch (Throwable e) {
);
}
catch (Throwable e) {
throw IOExceptionSupport.create(e); throw IOExceptionSupport.create(e);
} }
} }
protected ObjectName createByClientIdObjectName(String value) throws IOException { protected ObjectName createByClientIdObjectName(String value) throws IOException {
// Build the object name for the destination // Build the object name for the destination
Hashtable map = connectorName.getKeyPropertyList(); Hashtable map = connectorName.getKeyPropertyList();
try { try {
return new ObjectName( return new ObjectName(connectorName.getDomain() + ":" + "BrokerName="
connectorName.getDomain()+":"+ + JMXSupport.encodeObjectNamePart((String)map.get("BrokerName")) + ","
"BrokerName="+JMXSupport.encodeObjectNamePart((String) map.get("BrokerName"))+","+ + "Type=Connection," + "ConnectorName="
"Type=Connection,"+ + JMXSupport.encodeObjectNamePart((String)map.get("ConnectorName")) + ","
"ConnectorName="+JMXSupport.encodeObjectNamePart((String) map.get("ConnectorName"))+","+ + "Connection=" + JMXSupport.encodeObjectNamePart(value));
"Connection="+JMXSupport.encodeObjectNamePart(value) } catch (Throwable e) {
);
}
catch (Throwable e) {
throw IOExceptionSupport.create(e); throw IOExceptionSupport.create(e);
} }
} }
} }

View File

@ -22,40 +22,40 @@ public class NetworkBridgeView implements NetworkBridgeViewMBean {
private final NetworkBridge bridge; private final NetworkBridge bridge;
public NetworkBridgeView(NetworkBridge bridge) { public NetworkBridgeView(NetworkBridge bridge) {
this.bridge = bridge; this.bridge = bridge;
} }
public void start() throws Exception { public void start() throws Exception {
bridge.start(); bridge.start();
} }
public void stop() throws Exception { public void stop() throws Exception {
bridge.stop(); bridge.stop();
} }
public String getLocalAddress() { public String getLocalAddress() {
return bridge.getLocalAddress(); return bridge.getLocalAddress();
} }
public String getRemoteAddress() { public String getRemoteAddress() {
return bridge.getRemoteAddress(); return bridge.getRemoteAddress();
} }
public String getRemoteBrokerName() { public String getRemoteBrokerName() {
return bridge.getRemoteBrokerName(); return bridge.getRemoteBrokerName();
} }
public String getLocalBrokerName() { public String getLocalBrokerName() {
return bridge.getLocalBrokerName(); return bridge.getLocalBrokerName();
} }
public long getEnqueueCounter() { public long getEnqueueCounter() {
return bridge.getEnqueueCounter(); return bridge.getEnqueueCounter();
} }
public long getDequeueCounter() { public long getDequeueCounter() {
return bridge.getDequeueCounter(); return bridge.getDequeueCounter();
} }
} }

View File

@ -25,92 +25,92 @@ public class NetworkConnectorView implements NetworkConnectorViewMBean {
public NetworkConnectorView(NetworkConnector connector) { public NetworkConnectorView(NetworkConnector connector) {
this.connector = connector; this.connector = connector;
} }
public void start() throws Exception { public void start() throws Exception {
connector.start(); connector.start();
} }
public void stop() throws Exception { public void stop() throws Exception {
connector.stop(); connector.stop();
} }
public String getName() { public String getName() {
return connector.getName(); return connector.getName();
} }
public int getNetworkTTL() { public int getNetworkTTL() {
return connector.getNetworkTTL(); return connector.getNetworkTTL();
} }
public int getPrefetchSize() { public int getPrefetchSize() {
return connector.getPrefetchSize(); return connector.getPrefetchSize();
} }
public String getUserName() { public String getUserName() {
return connector.getUserName(); return connector.getUserName();
} }
public boolean isBridgeTempDestinations() { public boolean isBridgeTempDestinations() {
return connector.isBridgeTempDestinations(); return connector.isBridgeTempDestinations();
} }
public boolean isConduitSubscriptions() { public boolean isConduitSubscriptions() {
return connector.isConduitSubscriptions(); return connector.isConduitSubscriptions();
} }
public boolean isDecreaseNetworkConsumerPriority() { public boolean isDecreaseNetworkConsumerPriority() {
return connector.isDecreaseNetworkConsumerPriority(); return connector.isDecreaseNetworkConsumerPriority();
} }
public boolean isDispatchAsync() { public boolean isDispatchAsync() {
return connector.isDispatchAsync(); return connector.isDispatchAsync();
} }
public boolean isDynamicOnly() { public boolean isDynamicOnly() {
return connector.isDynamicOnly(); return connector.isDynamicOnly();
} }
public void setBridgeTempDestinations(boolean bridgeTempDestinations) { public void setBridgeTempDestinations(boolean bridgeTempDestinations) {
connector.setBridgeTempDestinations(bridgeTempDestinations); connector.setBridgeTempDestinations(bridgeTempDestinations);
} }
public void setConduitSubscriptions(boolean conduitSubscriptions) { public void setConduitSubscriptions(boolean conduitSubscriptions) {
connector.setConduitSubscriptions(conduitSubscriptions); connector.setConduitSubscriptions(conduitSubscriptions);
} }
public void setDispatchAsync(boolean dispatchAsync) { public void setDispatchAsync(boolean dispatchAsync) {
connector.setDispatchAsync(dispatchAsync); connector.setDispatchAsync(dispatchAsync);
} }
public void setDynamicOnly(boolean dynamicOnly) { public void setDynamicOnly(boolean dynamicOnly) {
connector.setDynamicOnly(dynamicOnly); connector.setDynamicOnly(dynamicOnly);
} }
public void setNetworkTTL(int networkTTL) { public void setNetworkTTL(int networkTTL) {
connector.setNetworkTTL(networkTTL); connector.setNetworkTTL(networkTTL);
} }
public void setPassword(String password) { public void setPassword(String password) {
connector.setPassword(password); connector.setPassword(password);
} }
public void setPrefetchSize(int prefetchSize) { public void setPrefetchSize(int prefetchSize) {
connector.setPrefetchSize(prefetchSize); connector.setPrefetchSize(prefetchSize);
} }
public void setUserName(String userName) { public void setUserName(String userName) {
connector.setUserName(userName); connector.setUserName(userName);
} }
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;
} }
public void setDecreaseNetworkConsumerPriority(boolean decreaseNetworkConsumerPriority) { public void setDecreaseNetworkConsumerPriority(boolean decreaseNetworkConsumerPriority) {
connector.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority); connector.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority);
} }
} }

View File

@ -20,24 +20,42 @@ import org.apache.activemq.Service;
public interface NetworkConnectorViewMBean extends Service { public interface NetworkConnectorViewMBean extends Service {
public String getName(); public String getName();
public int getNetworkTTL();
public int getPrefetchSize(); public int getNetworkTTL();
public String getUserName();
public boolean isBridgeTempDestinations(); public int getPrefetchSize();
public boolean isConduitSubscriptions();
public boolean isDecreaseNetworkConsumerPriority(); public String getUserName();
public boolean isDispatchAsync();
public boolean isDynamicOnly(); public boolean isBridgeTempDestinations();
public void setBridgeTempDestinations(boolean bridgeTempDestinations);
public void setConduitSubscriptions(boolean conduitSubscriptions); public boolean isConduitSubscriptions();
public void setDispatchAsync(boolean dispatchAsync);
public void setDynamicOnly(boolean dynamicOnly); public boolean isDecreaseNetworkConsumerPriority();
public void setNetworkTTL(int networkTTL);
public void setPassword(String password); public boolean isDispatchAsync();
public void setPrefetchSize(int prefetchSize);
public void setUserName(String userName); public boolean isDynamicOnly();
public String getPassword();
public void setDecreaseNetworkConsumerPriority(boolean decreaseNetworkConsumerPriority); public void setBridgeTempDestinations(boolean bridgeTempDestinations);
public void setConduitSubscriptions(boolean conduitSubscriptions);
public void setDispatchAsync(boolean dispatchAsync);
public void setDynamicOnly(boolean dynamicOnly);
public void setNetworkTTL(int networkTTL);
public void setPassword(String password);
public void setPrefetchSize(int prefetchSize);
public void setUserName(String userName);
public String getPassword();
public void setDecreaseNetworkConsumerPriority(boolean decreaseNetworkConsumerPriority);
} }

View File

@ -22,40 +22,37 @@ import org.apache.activemq.command.ConsumerInfo;
import javax.jms.InvalidSelectorException; import javax.jms.InvalidSelectorException;
/** /**
* @version $Revision: 1.5 $ * @version $Revision: 1.5 $
*/ */
public class SubscriptionView implements SubscriptionViewMBean { public class SubscriptionView implements SubscriptionViewMBean {
protected final Subscription subscription; protected final Subscription subscription;
protected final String clientId; protected final String clientId;
/** /**
* Constructor * Constructor
*
* @param subs * @param subs
*/ */
public SubscriptionView(String clientId,Subscription subs){ public SubscriptionView(String clientId, Subscription subs) {
this.clientId = clientId; this.clientId = clientId;
this.subscription = subs; this.subscription = subs;
} }
/** /**
* @return the clientId * @return the clientId
*/ */
public String getClientId(){ public String getClientId() {
return clientId; return clientId;
} }
/** /**
* @return the id of the Connection the Subscription is on * @return the id of the Connection the Subscription is on
*/ */
public String getConnectionId(){ public String getConnectionId() {
ConsumerInfo info = getConsumerInfo(); ConsumerInfo info = getConsumerInfo();
if (info != null){ if (info != null) {
return info.getConsumerId().getConnectionId(); return info.getConsumerId().getConnectionId();
} }
return "NOTSET"; return "NOTSET";
@ -64,9 +61,9 @@ public class SubscriptionView implements SubscriptionViewMBean {
/** /**
* @return the id of the Session the subscription is on * @return the id of the Session the subscription is on
*/ */
public long getSessionId(){ public long getSessionId() {
ConsumerInfo info = getConsumerInfo(); ConsumerInfo info = getConsumerInfo();
if (info != null){ if (info != null) {
return info.getConsumerId().getSessionId(); return info.getConsumerId().getSessionId();
} }
return 0; return 0;
@ -75,9 +72,9 @@ public class SubscriptionView implements SubscriptionViewMBean {
/** /**
* @return the id of the Subscription * @return the id of the Subscription
*/ */
public long getSubcriptionId(){ public long getSubcriptionId() {
ConsumerInfo info = getConsumerInfo(); ConsumerInfo info = getConsumerInfo();
if (info != null){ if (info != null) {
return info.getConsumerId().getValue(); return info.getConsumerId().getValue();
} }
return 0; return 0;
@ -86,9 +83,9 @@ public class SubscriptionView implements SubscriptionViewMBean {
/** /**
* @return the destination name * @return the destination name
*/ */
public String getDestinationName(){ public String getDestinationName() {
ConsumerInfo info = getConsumerInfo(); ConsumerInfo info = getConsumerInfo();
if (info != null){ if (info != null) {
ActiveMQDestination dest = info.getDestination(); ActiveMQDestination dest = info.getDestination();
return dest.getPhysicalName(); return dest.getPhysicalName();
} }
@ -105,8 +102,7 @@ public class SubscriptionView implements SubscriptionViewMBean {
public void setSelector(String selector) throws InvalidSelectorException, UnsupportedOperationException { public void setSelector(String selector) throws InvalidSelectorException, UnsupportedOperationException {
if (subscription != null) { if (subscription != null) {
subscription.setSelector(selector); subscription.setSelector(selector);
} } else {
else {
throw new UnsupportedOperationException("No subscription object"); throw new UnsupportedOperationException("No subscription object");
} }
} }
@ -114,9 +110,9 @@ public class SubscriptionView implements SubscriptionViewMBean {
/** /**
* @return true if the destination is a Queue * @return true if the destination is a Queue
*/ */
public boolean isDestinationQueue(){ public boolean isDestinationQueue() {
ConsumerInfo info = getConsumerInfo(); ConsumerInfo info = getConsumerInfo();
if (info != null){ if (info != null) {
ActiveMQDestination dest = info.getDestination(); ActiveMQDestination dest = info.getDestination();
return dest.isQueue(); return dest.isQueue();
} }
@ -126,9 +122,9 @@ public class SubscriptionView implements SubscriptionViewMBean {
/** /**
* @return true of the destination is a Topic * @return true of the destination is a Topic
*/ */
public boolean isDestinationTopic(){ public boolean isDestinationTopic() {
ConsumerInfo info = getConsumerInfo(); ConsumerInfo info = getConsumerInfo();
if (info != null){ if (info != null) {
ActiveMQDestination dest = info.getDestination(); ActiveMQDestination dest = info.getDestination();
return dest.isTopic(); return dest.isTopic();
} }
@ -138,32 +134,32 @@ public class SubscriptionView implements SubscriptionViewMBean {
/** /**
* @return true if the destination is temporary * @return true if the destination is temporary
*/ */
public boolean isDestinationTemporary(){ public boolean isDestinationTemporary() {
ConsumerInfo info = getConsumerInfo(); ConsumerInfo info = getConsumerInfo();
if (info != null){ if (info != null) {
ActiveMQDestination dest = info.getDestination(); ActiveMQDestination dest = info.getDestination();
return dest.isTemporary(); return dest.isTemporary();
} }
return false; return false;
} }
/** /**
* @return true if the subscriber is active * @return true if the subscriber is active
*/ */
public boolean isActive(){ public boolean isActive() {
return true; return true;
} }
/** /**
* The subscription should release as may references as it can to help the garbage collector * The subscription should release as may references as it can to help the
* reclaim memory. * garbage collector reclaim memory.
*/ */
public void gc(){ public void gc() {
if (subscription != null){ if (subscription != null) {
subscription.gc(); subscription.gc();
} }
} }
/** /**
* @return whether or not the subscriber is retroactive or not * @return whether or not the subscriber is retroactive or not
*/ */
@ -171,7 +167,7 @@ public class SubscriptionView implements SubscriptionViewMBean {
ConsumerInfo info = getConsumerInfo(); ConsumerInfo info = getConsumerInfo();
return info != null ? info.isRetroactive() : false; return info != null ? info.isRetroactive() : false;
} }
/** /**
* @return whether or not the subscriber is an exclusive consumer * @return whether or not the subscriber is an exclusive consumer
*/ */
@ -179,8 +175,7 @@ public class SubscriptionView implements SubscriptionViewMBean {
ConsumerInfo info = getConsumerInfo(); ConsumerInfo info = getConsumerInfo();
return info != null ? info.isExclusive() : false; return info != null ? info.isExclusive() : false;
} }
/** /**
* @return whether or not the subscriber is durable (persistent) * @return whether or not the subscriber is durable (persistent)
*/ */
@ -188,7 +183,7 @@ public class SubscriptionView implements SubscriptionViewMBean {
ConsumerInfo info = getConsumerInfo(); ConsumerInfo info = getConsumerInfo();
return info != null ? info.isDurable() : false; return info != null ? info.isDurable() : false;
} }
/** /**
* @return whether or not the subscriber ignores local messages * @return whether or not the subscriber ignores local messages
*/ */
@ -196,17 +191,18 @@ public class SubscriptionView implements SubscriptionViewMBean {
ConsumerInfo info = getConsumerInfo(); ConsumerInfo info = getConsumerInfo();
return info != null ? info.isNoLocal() : false; return info != null ? info.isNoLocal() : false;
} }
/** /**
* @return the maximum number of pending messages allowed in addition to the prefetch size. If enabled * @return the maximum number of pending messages allowed in addition to the
* to a non-zero value then this will perform eviction of messages for slow consumers on non-durable topics. * prefetch size. If enabled to a non-zero value then this will
* perform eviction of messages for slow consumers on non-durable
* topics.
*/ */
public int getMaximumPendingMessageLimit() { public int getMaximumPendingMessageLimit() {
ConsumerInfo info = getConsumerInfo(); ConsumerInfo info = getConsumerInfo();
return info != null ? info.getMaximumPendingMessageLimit() : 0; return info != null ? info.getMaximumPendingMessageLimit() : 0;
} }
/** /**
* @return the consumer priority * @return the consumer priority
*/ */
@ -214,29 +210,30 @@ public class SubscriptionView implements SubscriptionViewMBean {
ConsumerInfo info = getConsumerInfo(); ConsumerInfo info = getConsumerInfo();
return info != null ? info.getPriority() : 0; return info != null ? info.getPriority() : 0;
} }
/** /**
* @return the name of the consumer which is only used for durable consumers. * @return the name of the consumer which is only used for durable
* consumers.
*/ */
public String getSubcriptionName() { public String getSubcriptionName() {
ConsumerInfo info = getConsumerInfo(); ConsumerInfo info = getConsumerInfo();
return info != null ? info.getSubscriptionName() : null; return info != null ? info.getSubscriptionName() : null;
} }
/** /**
* @return number of messages pending delivery * @return number of messages pending delivery
*/ */
public int getPendingQueueSize(){ public int getPendingQueueSize() {
return subscription != null ? subscription.getPendingQueueSize() : 0; return subscription != null ? subscription.getPendingQueueSize() : 0;
} }
/** /**
* @return number of messages dispatched * @return number of messages dispatched
*/ */
public int getDispatchedQueueSize(){ public int getDispatchedQueueSize() {
return subscription != null ? subscription.getDispatchedQueueSize() : 0; return subscription != null ? subscription.getDispatchedQueueSize() : 0;
} }
/** /**
* @return number of messages that matched the subscription * @return number of messages that matched the subscription
*/ */
@ -258,15 +255,15 @@ public class SubscriptionView implements SubscriptionViewMBean {
return subscription != null ? subscription.getDequeueCounter() : 0; return subscription != null ? subscription.getDequeueCounter() : 0;
} }
protected ConsumerInfo getConsumerInfo(){ protected ConsumerInfo getConsumerInfo() {
return subscription != null ? subscription.getConsumerInfo() : null; return subscription != null ? subscription.getConsumerInfo() : null;
} }
/** /**
*@return pretty print * @return pretty print
*/ */
public String toString(){ public String toString() {
return "SubscriptionView: " + getClientId() + ":" + getConnectionId(); return "SubscriptionView: " + getClientId() + ":" + getConnectionId();
} }
/** /**

View File

@ -29,7 +29,7 @@ public class TopicSubscriptionView extends SubscriptionView implements TopicSubs
} }
protected TopicSubscription getTopicSubscription() { protected TopicSubscription getTopicSubscription() {
return (TopicSubscription) subscription; return (TopicSubscription)subscription;
} }
/** /**
@ -47,14 +47,14 @@ public class TopicSubscriptionView extends SubscriptionView implements TopicSubs
TopicSubscription topicSubscription = getTopicSubscription(); TopicSubscription topicSubscription = getTopicSubscription();
return topicSubscription != null ? topicSubscription.getMaximumPendingMessages() : 0; return topicSubscription != null ? topicSubscription.getMaximumPendingMessages() : 0;
} }
/** /**
* *
*/ */
public void setMaximumPendingQueueSize(int max) { public void setMaximumPendingQueueSize(int max) {
TopicSubscription topicSubscription = getTopicSubscription(); TopicSubscription topicSubscription = getTopicSubscription();
if ( topicSubscription != null ) { if (topicSubscription != null) {
topicSubscription.setMaximumPendingMessages(max); topicSubscription.setMaximumPendingMessages(max);
} }
} }
} }

View File

@ -27,32 +27,37 @@ import org.apache.activemq.command.Message;
import org.apache.activemq.command.MessageAck; import org.apache.activemq.command.MessageAck;
import org.apache.activemq.memory.UsageManager; import org.apache.activemq.memory.UsageManager;
import org.apache.activemq.store.MessageStore; import org.apache.activemq.store.MessageStore;
import org.apache.activemq.store.TopicMessageStore;
/** /**
*
* @version $Revision: 1.12 $ * @version $Revision: 1.12 $
*/ */
public interface Destination extends Service { public interface Destination extends Service {
void addSubscription(ConnectionContext context, Subscription sub) throws Exception; void addSubscription(ConnectionContext context, Subscription sub) throws Exception;
void removeSubscription(ConnectionContext context, Subscription sub) throws Exception; void removeSubscription(ConnectionContext context, Subscription sub) throws Exception;
void send(ProducerBrokerExchange producerExchange, Message messageSend) throws Exception; void send(ProducerBrokerExchange producerExchange, Message messageSend) throws Exception;
boolean lock(MessageReference node, LockOwner lockOwner); boolean lock(MessageReference node, LockOwner lockOwner);
void acknowledge(ConnectionContext context, Subscription sub, final MessageAck ack, final MessageReference node) throws IOException; void acknowledge(ConnectionContext context, Subscription sub, final MessageAck ack, final MessageReference node) throws IOException;
void gc(); void gc();
ActiveMQDestination getActiveMQDestination(); ActiveMQDestination getActiveMQDestination();
UsageManager getUsageManager(); UsageManager getUsageManager();
void dispose(ConnectionContext context) throws IOException; void dispose(ConnectionContext context) throws IOException;
DestinationStatistics getDestinationStatistics(); DestinationStatistics getDestinationStatistics();
DeadLetterStrategy getDeadLetterStrategy(); DeadLetterStrategy getDeadLetterStrategy();
public Message[] browse(); public Message[] browse();
public String getName(); public String getName();
public MessageStore getMessageStore();
public MessageStore getMessageStore();
} }

View File

@ -16,6 +16,10 @@
*/ */
package org.apache.activemq.broker.region; package org.apache.activemq.broker.region;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
import org.apache.activemq.broker.Broker; import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.broker.ProducerBrokerExchange; import org.apache.activemq.broker.ProducerBrokerExchange;
@ -26,10 +30,6 @@ import org.apache.activemq.command.MessageAck;
import org.apache.activemq.memory.UsageManager; import org.apache.activemq.memory.UsageManager;
import org.apache.activemq.store.MessageStore; import org.apache.activemq.store.MessageStore;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
/** /**
* *
* @version $Revision$ * @version $Revision$
@ -42,7 +42,8 @@ public class DestinationFilter implements Destination {
this.next = next; this.next = next;
} }
public void acknowledge(ConnectionContext context, Subscription sub, MessageAck ack, MessageReference node) throws IOException { public void acknowledge(ConnectionContext context, Subscription sub, MessageAck ack, MessageReference node)
throws IOException {
next.acknowledge(context, sub, ack, node); next.acknowledge(context, sub, ack, node);
} }
@ -105,17 +106,18 @@ public class DestinationFilter implements Destination {
/** /**
* Sends a message to the given destination which may be a wildcard * Sends a message to the given destination which may be a wildcard
*/ */
protected void send(ProducerBrokerExchange context, Message message, ActiveMQDestination destination) throws Exception { protected void send(ProducerBrokerExchange context, Message message, ActiveMQDestination destination)
throws Exception {
Broker broker = context.getConnectionContext().getBroker(); Broker broker = context.getConnectionContext().getBroker();
Set destinations = broker.getDestinations(destination); Set destinations = broker.getDestinations(destination);
for (Iterator iter = destinations.iterator(); iter.hasNext();) { for (Iterator iter = destinations.iterator(); iter.hasNext();) {
Destination dest = (Destination) iter.next(); Destination dest = (Destination)iter.next();
dest.send(context, message); dest.send(context, message);
} }
} }
public MessageStore getMessageStore() { public MessageStore getMessageStore() {
return next.getMessageStore(); return next.getMessageStore();
} }
} }

View File

@ -24,103 +24,102 @@ import org.apache.activemq.command.Message;
import org.apache.activemq.command.MessageId; import org.apache.activemq.command.MessageId;
/** /**
* Only used by the {@link QueueMessageReference#NULL_MESSAGE} * Only used by the {@link QueueMessageReference#NULL_MESSAGE}
*/ */
final class NullMessageReference implements final class NullMessageReference implements QueueMessageReference {
QueueMessageReference {
private ActiveMQMessage message = new ActiveMQMessage(); private ActiveMQMessage message = new ActiveMQMessage();
private volatile int references; private volatile int references;
public void drop() {
throw new RuntimeException("not implemented");
}
public LockOwner getLockOwner() { public void drop() {
throw new RuntimeException("not implemented"); throw new RuntimeException("not implemented");
} }
public boolean isAcked() { public LockOwner getLockOwner() {
return false; throw new RuntimeException("not implemented");
} }
public boolean isDropped() { public boolean isAcked() {
throw new RuntimeException("not implemented"); return false;
} }
public boolean lock(LockOwner subscription) { public boolean isDropped() {
return true; throw new RuntimeException("not implemented");
} }
public void setAcked(boolean b) { public boolean lock(LockOwner subscription) {
throw new RuntimeException("not implemented"); return true;
} }
public void unlock() { public void setAcked(boolean b) {
} throw new RuntimeException("not implemented");
}
public int decrementReferenceCount() { public void unlock() {
return --references; }
}
public long getExpiration() { public int decrementReferenceCount() {
throw new RuntimeException("not implemented"); return --references;
} }
public String getGroupID() { public long getExpiration() {
return null; throw new RuntimeException("not implemented");
} }
public int getGroupSequence() { public String getGroupID() {
return 0; return null;
} }
public Message getMessage() throws IOException { public int getGroupSequence() {
return message; return 0;
} }
public Message getMessageHardRef() { public Message getMessage() throws IOException {
throw new RuntimeException("not implemented"); return message;
} }
public MessageId getMessageId() { public Message getMessageHardRef() {
return message.getMessageId(); throw new RuntimeException("not implemented");
} }
public int getRedeliveryCounter() { public MessageId getMessageId() {
throw new RuntimeException("not implemented"); return message.getMessageId();
} }
public int getReferenceCount() { public int getRedeliveryCounter() {
return references; throw new RuntimeException("not implemented");
} }
public Destination getRegionDestination() { public int getReferenceCount() {
return null; return references;
} }
public int getSize() { public Destination getRegionDestination() {
throw new RuntimeException("not implemented"); return null;
} }
public ConsumerId getTargetConsumerId() { public int getSize() {
throw new RuntimeException("not implemented"); throw new RuntimeException("not implemented");
} }
public void incrementRedeliveryCounter() { public ConsumerId getTargetConsumerId() {
throw new RuntimeException("not implemented"); throw new RuntimeException("not implemented");
} }
public int incrementReferenceCount() { public void incrementRedeliveryCounter() {
return ++references; throw new RuntimeException("not implemented");
} }
public boolean isExpired() { public int incrementReferenceCount() {
throw new RuntimeException("not implemented"); return ++references;
} }
public boolean isPersistent() { public boolean isExpired() {
throw new RuntimeException("not implemented"); throw new RuntimeException("not implemented");
} }
public boolean isPersistent() {
throw new RuntimeException("not implemented");
}
} }

View File

@ -27,32 +27,29 @@ import org.apache.activemq.command.MessageDispatch;
import org.apache.activemq.filter.MessageEvaluationContext; import org.apache.activemq.filter.MessageEvaluationContext;
public class QueueBrowserSubscription extends QueueSubscription { public class QueueBrowserSubscription extends QueueSubscription {
boolean browseDone; boolean browseDone;
public QueueBrowserSubscription(Broker broker,ConnectionContext context, ConsumerInfo info) throws InvalidSelectorException { public QueueBrowserSubscription(Broker broker, ConnectionContext context, ConsumerInfo info)
super(broker,context, info); throws InvalidSelectorException {
super(broker, context, info);
} }
protected boolean canDispatch(MessageReference node) { protected boolean canDispatch(MessageReference node) {
return !((QueueMessageReference)node).isAcked(); return !((QueueMessageReference)node).isAcked();
} }
public synchronized String toString() { public synchronized String toString() {
return return "QueueBrowserSubscription:" + " consumer=" + info.getConsumerId() + ", destinations="
"QueueBrowserSubscription:" + + destinations.size() + ", dispatched=" + dispatched.size() + ", delivered="
" consumer="+info.getConsumerId()+ + this.prefetchExtension + ", pending=" + getPendingQueueSize();
", destinations="+destinations.size()+
", dispatched="+dispatched.size()+
", delivered="+this.prefetchExtension+
", pending="+getPendingQueueSize();
} }
public void browseDone() throws Exception { public void browseDone() throws Exception {
browseDone = true; browseDone = true;
add(QueueMessageReference.NULL_MESSAGE); add(QueueMessageReference.NULL_MESSAGE);
} }
public boolean matches(MessageReference node, MessageEvaluationContext context) throws IOException { public boolean matches(MessageReference node, MessageEvaluationContext context) throws IOException {
return !browseDone && super.matches(node, context); return !browseDone && super.matches(node, context);
} }
@ -60,7 +57,8 @@ public class QueueBrowserSubscription extends QueueSubscription {
/** /**
* Since we are a browser we don't really remove the message from the queue. * Since we are a browser we don't really remove the message from the queue.
*/ */
protected void acknowledge(ConnectionContext context, final MessageAck ack, final MessageReference n) throws IOException { protected void acknowledge(ConnectionContext context, final MessageAck ack, final MessageReference n)
throws IOException {
} }
} }

View File

@ -33,31 +33,30 @@ import java.util.Set;
*/ */
public class QueueRegion extends AbstractRegion { public class QueueRegion extends AbstractRegion {
public QueueRegion(RegionBroker broker, DestinationStatistics destinationStatistics,
UsageManager memoryManager, TaskRunnerFactory taskRunnerFactory,
public QueueRegion(RegionBroker broker,DestinationStatistics destinationStatistics, UsageManager memoryManager, TaskRunnerFactory taskRunnerFactory, DestinationFactory destinationFactory) {
DestinationFactory destinationFactory) { super(broker, destinationStatistics, memoryManager, taskRunnerFactory, destinationFactory);
super(broker,destinationStatistics, memoryManager, taskRunnerFactory, destinationFactory);
} }
public String toString() { public String toString() {
return "QueueRegion: destinations=" + destinations.size() + ", subscriptions=" + subscriptions.size() + ", memory=" + memoryManager.getPercentUsage() return "QueueRegion: destinations=" + destinations.size() + ", subscriptions=" + subscriptions.size()
+ "%"; + ", memory=" + memoryManager.getPercentUsage() + "%";
} }
protected Subscription createSubscription(ConnectionContext context, ConsumerInfo info) throws InvalidSelectorException { protected Subscription createSubscription(ConnectionContext context, ConsumerInfo info)
throws InvalidSelectorException {
if (info.isBrowser()) { if (info.isBrowser()) {
return new QueueBrowserSubscription(broker,context, info); return new QueueBrowserSubscription(broker, context, info);
} } else {
else { return new QueueSubscription(broker, context, info);
return new QueueSubscription(broker,context, info);
} }
} }
protected Set getInactiveDestinations() { protected Set getInactiveDestinations() {
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.isQueue()) if (!dest.isQueue())
iter.remove(); iter.remove();
} }

View File

@ -60,12 +60,12 @@ import org.apache.commons.logging.LogFactory;
* @version $Revision: 1.21 $ * @version $Revision: 1.21 $
*/ */
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 consumers = new CopyOnWriteArrayList();
protected final Valve dispatchValve = new Valve(true); protected final Valve dispatchValve = new Valve(true);
protected final TopicMessageStore store;// this could be NULL! (If an // this could be NULL! (If an advisory)
// advsiory) protected final TopicMessageStore store;
protected final UsageManager usageManager; protected final UsageManager usageManager;
protected final DestinationStatistics destinationStatistics = new DestinationStatistics(); protected final DestinationStatistics destinationStatistics = new DestinationStatistics();
@ -349,8 +349,8 @@ public class Topic implements Destination {
// The usage manager could have delayed us by the time // The usage manager could have delayed us by the time
// we unblock the message could have expired.. // we unblock the message could have expired..
if (message.isExpired()) { if (message.isExpired()) {
if (log.isDebugEnabled()) { if (LOG.isDebugEnabled()) {
log.debug("Expired message: " + message); LOG.debug("Expired message: " + message);
} }
return; return;
} }
@ -468,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 (Message[])result.toArray(new Message[result.size()]);
} }

View File

@ -19,25 +19,25 @@ import org.apache.activemq.broker.region.cursors.FilePendingMessageCursor;
import org.apache.activemq.broker.region.cursors.PendingMessageCursor; import org.apache.activemq.broker.region.cursors.PendingMessageCursor;
import org.apache.activemq.kaha.Store; import org.apache.activemq.kaha.Store;
/** /**
* Creates a FilePendingMessageCursor * Creates a FilePendingMessageCursor *
* * *
* @org.apache.xbean.XBean element="fileQueueCursor" description="Pending messages paged in from file" * @org.apache.xbean.XBean element="fileQueueCursor" description="Pending
* messages paged in from file"
* *
* @version $Revision$ * @version $Revision$
*/ */
public class FilePendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy{ public class FilePendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy {
/** /**
* @param queue * @param queue
* @param tmpStore * @param tmpStore
* @return the cursor * @return the cursor
* @see org.apache.activemq.broker.region.policy.PendingQueueMessageStoragePolicy#getQueuePendingMessageCursor(org.apache.openjpa.lib.util.concurrent.Queue, org.apache.activemq.kaha.Store) * @see org.apache.activemq.broker.region.policy.PendingQueueMessageStoragePolicy#getQueuePendingMessageCursor(org.apache.openjpa.lib.util.concurrent.Queue,
* org.apache.activemq.kaha.Store)
*/ */
public PendingMessageCursor getQueuePendingMessageCursor(Queue queue,Store tmpStore){ public PendingMessageCursor getQueuePendingMessageCursor(Queue queue, Store tmpStore) {
return new FilePendingMessageCursor("PendingCursor:" + queue.getName(),tmpStore); return new FilePendingMessageCursor("PendingCursor:" + queue.getName(), tmpStore);
} }
} }

View File

@ -17,25 +17,26 @@ import org.apache.activemq.broker.region.cursors.FilePendingMessageCursor;
import org.apache.activemq.broker.region.cursors.PendingMessageCursor; import org.apache.activemq.broker.region.cursors.PendingMessageCursor;
import org.apache.activemq.kaha.Store; import org.apache.activemq.kaha.Store;
/** /**
* Creates a PendIngMessageCursor for Durable subscribers * Creates a PendIngMessageCursor for Durable subscribers *
* * *
* @org.apache.xbean.XBean element="fileCursor" description="Pending messages for durable subscribers * @org.apache.xbean.XBean element="fileCursor" description="Pending messages
* held in temporary files" * for durable subscribers held in temporary files"
* *
* @version $Revision$ * @version $Revision$
*/ */
public class FilePendingSubscriberMessageStoragePolicy implements PendingSubscriberMessageStoragePolicy{ public class FilePendingSubscriberMessageStoragePolicy implements PendingSubscriberMessageStoragePolicy {
/** /**
* @param name * @param name
* @param tmpStorage * @param tmpStorage
* @param maxBatchSize * @param maxBatchSize
* @return a Cursor * @return a Cursor
* @see org.apache.activemq.broker.region.policy.PendingSubscriberMessageStoragePolicy#getSubscriberPendingMessageCursor(java.lang.String, org.apache.activemq.kaha.Store, int) * @see org.apache.activemq.broker.region.policy.PendingSubscriberMessageStoragePolicy#getSubscriberPendingMessageCursor(java.lang.String,
* org.apache.activemq.kaha.Store, int)
*/ */
public PendingMessageCursor getSubscriberPendingMessageCursor(String name,Store tmpStorage,int maxBatchSize){ public PendingMessageCursor getSubscriberPendingMessageCursor(String name, Store tmpStorage,
return new FilePendingMessageCursor("PendingCursor:" + name,tmpStorage); int maxBatchSize) {
return new FilePendingMessageCursor("PendingCursor:" + name, tmpStorage);
} }
} }

View File

@ -19,25 +19,25 @@ import org.apache.activemq.broker.region.cursors.PendingMessageCursor;
import org.apache.activemq.broker.region.cursors.StoreQueueCursor; import org.apache.activemq.broker.region.cursors.StoreQueueCursor;
import org.apache.activemq.kaha.Store; import org.apache.activemq.kaha.Store;
/** /**
* Creates a StoreQueueCursor * Creates a StoreQueueCursor *
* * *
* @org.apache.xbean.XBean element="storeCursor" description="Pending messages paged in from the Store" * @org.apache.xbean.XBean element="storeCursor" description="Pending messages
* paged in from the Store"
* *
* @version $Revision$ * @version $Revision$
*/ */
public class StorePendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy{ public class StorePendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy {
/** /**
* @param queue * @param queue
* @param tmpStore * @param tmpStore
* @return the cursor * @return the cursor
* @see org.apache.activemq.broker.region.policy.PendingQueueMessageStoragePolicy#getQueuePendingMessageCursor(org.apache.openjpa.lib.util.concurrent.Queue, org.apache.activemq.kaha.Store) * @see org.apache.activemq.broker.region.policy.PendingQueueMessageStoragePolicy#getQueuePendingMessageCursor(org.apache.openjpa.lib.util.concurrent.Queue,
* org.apache.activemq.kaha.Store)
*/ */
public PendingMessageCursor getQueuePendingMessageCursor(Queue queue,Store tmpStore){ public PendingMessageCursor getQueuePendingMessageCursor(Queue queue, Store tmpStore) {
return new StoreQueueCursor(queue,tmpStore); return new StoreQueueCursor(queue, tmpStore);
} }
} }

View File

@ -20,20 +20,21 @@ import org.apache.activemq.broker.region.cursors.VMPendingMessageCursor;
import org.apache.activemq.kaha.Store; import org.apache.activemq.kaha.Store;
/** /**
* Creates a VMPendingMessageCursor * Creates a VMPendingMessageCursor *
* * *
* @org.apache.xbean.XBean element="vmQueueCursor" description="Pending messages held in the JVM" * @org.apache.xbean.XBean element="vmQueueCursor" description="Pending messages
* held in the JVM"
* *
* @version $Revision$ * @version $Revision$
*/ */
public class VMPendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy{ public class VMPendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy {
/** /**
* @param queue * @param queue
* @param tmpStore * @param tmpStore
* @return the cursor * @return the cursor
*/ */
public PendingMessageCursor getQueuePendingMessageCursor(Queue queue,Store tmpStore){ public PendingMessageCursor getQueuePendingMessageCursor(Queue queue, Store tmpStore) {
return new VMPendingMessageCursor(); return new VMPendingMessageCursor();
} }
} }

View File

@ -17,24 +17,26 @@ import org.apache.activemq.broker.region.cursors.PendingMessageCursor;
import org.apache.activemq.broker.region.cursors.VMPendingMessageCursor; import org.apache.activemq.broker.region.cursors.VMPendingMessageCursor;
import org.apache.activemq.kaha.Store; import org.apache.activemq.kaha.Store;
/** /**
* Creates a VMPendingMessageCursor * Creates a VMPendingMessageCursor *
* * *
* @org.apache.xbean.XBean element="vmCursor" description="Pending messages held in the JVM" * @org.apache.xbean.XBean element="vmCursor" description="Pending messages held
* in the JVM"
* *
* @version $Revision$ * @version $Revision$
*/ */
public class VMPendingSubscriberMessageStoragePolicy implements PendingSubscriberMessageStoragePolicy{ public class VMPendingSubscriberMessageStoragePolicy implements PendingSubscriberMessageStoragePolicy {
/** /**
* @param name * @param name
* @param tmpStorage * @param tmpStorage
* @param maxBatchSize * @param maxBatchSize
* @return a Cursor * @return a Cursor
* @see org.apache.activemq.broker.region.policy.PendingSubscriberMessageStoragePolicy#getSubscriberPendingMessageCursor(java.lang.String, org.apache.activemq.kaha.Store, int) * @see org.apache.activemq.broker.region.policy.PendingSubscriberMessageStoragePolicy#getSubscriberPendingMessageCursor(java.lang.String,
* org.apache.activemq.kaha.Store, int)
*/ */
public PendingMessageCursor getSubscriberPendingMessageCursor(String name,Store tmpStorage,int maxBatchSize){ public PendingMessageCursor getSubscriberPendingMessageCursor(String name, Store tmpStorage,
int maxBatchSize) {
return new VMPendingMessageCursor(); return new VMPendingMessageCursor();
} }
} }

View File

@ -23,7 +23,8 @@ import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
/** /**
* A Broker interceptor which allows you to trace all operations to a Multicast socket. * A Broker interceptor which allows you to trace all operations to a Multicast
* socket.
* *
* @org.apache.xbean.XBean * @org.apache.xbean.XBean
* *
@ -31,30 +32,30 @@ import java.net.URISyntaxException;
*/ */
public class MulticastTraceBrokerPlugin extends UDPTraceBrokerPlugin { public class MulticastTraceBrokerPlugin extends UDPTraceBrokerPlugin {
private int timeToLive = 1; private int timeToLive = 1;
public MulticastTraceBrokerPlugin() { public MulticastTraceBrokerPlugin() {
try { try {
destination = new URI("multicast://224.1.2.3:61616"); destination = new URI("multicast://224.1.2.3:61616");
} catch (URISyntaxException wontHappen) { } catch (URISyntaxException wontHappen) {
} }
} }
protected DatagramSocket createSocket() throws IOException { protected DatagramSocket createSocket() throws IOException {
MulticastSocket s = new MulticastSocket(); MulticastSocket s = new MulticastSocket();
s.setSendBufferSize(maxTraceDatagramSize); s.setSendBufferSize(maxTraceDatagramSize);
s.setBroadcast(broadcast); s.setBroadcast(broadcast);
s.setLoopbackMode(true); s.setLoopbackMode(true);
s.setTimeToLive(timeToLive); s.setTimeToLive(timeToLive);
return s; return s;
} }
public int getTimeToLive() { public int getTimeToLive() {
return timeToLive; return timeToLive;
} }
public void setTimeToLive(int timeToLive) { public void setTimeToLive(int timeToLive) {
this.timeToLive = timeToLive; this.timeToLive = timeToLive;
} }
} }

View File

@ -20,27 +20,27 @@ import org.apache.activemq.broker.BrokerPluginSupport;
import org.apache.activemq.broker.ProducerBrokerExchange; import org.apache.activemq.broker.ProducerBrokerExchange;
import org.apache.activemq.command.Message; import org.apache.activemq.command.Message;
/** /**
* A Broker interceptor which updates a JMS Client's timestamp on the message * A Broker interceptor which updates a JMS Client's timestamp on the message
* with a broker timestamp. Useful when the clocks on client machines are known to * with a broker timestamp. Useful when the clocks on client machines are known
* not be correct and you can only trust the time set on the broker machines. * to not be correct and you can only trust the time set on the broker machines.
* *
* Enabling this plugin will break JMS compliance since the timestamp that the producer * Enabling this plugin will break JMS compliance since the timestamp that the
* sees on the messages after as send() will be different from the timestamp the consumer * producer sees on the messages after as send() will be different from the
* will observe when he receives the message. This plugin is not enabled in the default * timestamp the consumer will observe when he receives the message. This plugin
* ActiveMQ configuration. * is not enabled in the default ActiveMQ configuration.
* *
* @org.apache.xbean.XBean element="timeStampingBrokerPlugin" * @org.apache.xbean.XBean element="timeStampingBrokerPlugin"
* *
* @version $Revision$ * @version $Revision$
*/ */
public class TimeStampingBrokerPlugin extends BrokerPluginSupport { public class TimeStampingBrokerPlugin extends BrokerPluginSupport {
public void send(ProducerBrokerExchange producerExchange, Message message) throws Exception { public void send(ProducerBrokerExchange producerExchange, Message message) throws Exception {
if (message.getTimestamp() > 0 && (message.getBrokerPath() == null || message.getBrokerPath().length == 0)) { if (message.getTimestamp() > 0
//timestamp not been disabled and has not passed through a network && (message.getBrokerPath() == null || message.getBrokerPath().length == 0)) {
// timestamp not been disabled and has not passed through a network
message.setTimestamp(System.currentTimeMillis()); message.setTimestamp(System.currentTimeMillis());
} }
super.send(producerExchange, message); super.send(producerExchange, message);
} }
} }

View File

@ -16,6 +16,10 @@
*/ */
package org.apache.activemq.broker.view; package org.apache.activemq.broker.view;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Iterator;
import org.apache.activemq.broker.Broker; import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.broker.region.Destination; import org.apache.activemq.broker.region.Destination;
@ -23,12 +27,7 @@ import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.filter.DestinationMap; import org.apache.activemq.filter.DestinationMap;
import org.apache.activemq.filter.DestinationMapNode; import org.apache.activemq.filter.DestinationMapNode;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Iterator;
/** /**
*
* @version $Revision: $ * @version $Revision: $
*/ */
public class DestinationDotFileInterceptor extends DotFileInterceptorSupport { public class DestinationDotFileInterceptor extends DotFileInterceptorSupport {
@ -45,13 +44,11 @@ public class DestinationDotFileInterceptor extends DotFileInterceptorSupport {
return answer; return answer;
} }
public void removeDestination(ConnectionContext context, ActiveMQDestination destination, long timeout) public void removeDestination(ConnectionContext context, ActiveMQDestination destination, long timeout) throws Exception {
throws Exception {
super.removeDestination(context, destination, timeout); super.removeDestination(context, destination, timeout);
generateFile(); generateFile();
} }
protected void generateFile(PrintWriter writer) throws Exception { protected void generateFile(PrintWriter writer) throws Exception {
ActiveMQDestination[] destinations = getDestinations(); ActiveMQDestination[] destinations = getDestinations();
@ -71,7 +68,7 @@ public class DestinationDotFileInterceptor extends DotFileInterceptorSupport {
writer.println("topic_root [fillcolor = deepskyblue, label = \"Topics\" ];"); writer.println("topic_root [fillcolor = deepskyblue, label = \"Topics\" ];");
writer.println("queue_root [fillcolor = deepskyblue, label = \"Queues\" ];"); writer.println("queue_root [fillcolor = deepskyblue, label = \"Queues\" ];");
writer.println(); writer.println();
writer.println("subgraph queues {"); writer.println("subgraph queues {");
writer.println(" node [fillcolor=red]; "); writer.println(" node [fillcolor=red]; ");
writer.println(" label = \"Queues\""); writer.println(" label = \"Queues\"");
@ -83,20 +80,20 @@ public class DestinationDotFileInterceptor extends DotFileInterceptorSupport {
writer.println("subgraph topics {"); writer.println("subgraph topics {");
writer.println(" node [fillcolor=green]; "); writer.println(" node [fillcolor=green]; ");
writer.println(" label = \"Topics\""); writer.println(" label = \"Topics\"");
writer.println(); writer.println();
printNodeLinks(writer, map.getTopicRootNode(), "topic"); printNodeLinks(writer, map.getTopicRootNode(), "topic");
writer.println("}"); writer.println("}");
writer.println(); writer.println();
printNodes(writer, map.getQueueRootNode(), "queue"); printNodes(writer, map.getQueueRootNode(), "queue");
writer.println(); writer.println();
printNodes(writer, map.getTopicRootNode(), "topic"); printNodes(writer, map.getTopicRootNode(), "topic");
writer.println(); writer.println();
writer.println("}"); writer.println("}");
} }
protected void printNodes(PrintWriter writer, DestinationMapNode node, String prefix) { protected void printNodes(PrintWriter writer, DestinationMapNode node, String prefix) {
String path = getPath(node); String path = getPath(node);
writer.print(" "); writer.print(" ");
@ -106,8 +103,7 @@ public class DestinationDotFileInterceptor extends DotFileInterceptorSupport {
String label = path; String label = path;
if (prefix.equals("topic")) { if (prefix.equals("topic")) {
label = "Topics"; label = "Topics";
} } else if (prefix.equals("queue")) {
else if (prefix.equals("queue")) {
label = "Queues"; label = "Queues";
} }
writer.print("[ label = \""); writer.print("[ label = \"");
@ -116,7 +112,7 @@ public class DestinationDotFileInterceptor extends DotFileInterceptorSupport {
Collection children = node.getChildren(); Collection children = node.getChildren();
for (Iterator iter = children.iterator(); iter.hasNext();) { for (Iterator iter = children.iterator(); iter.hasNext();) {
DestinationMapNode child = (DestinationMapNode) iter.next(); DestinationMapNode child = (DestinationMapNode)iter.next();
printNodes(writer, child, prefix + ID_SEPARATOR + path); printNodes(writer, child, prefix + ID_SEPARATOR + path);
} }
} }
@ -125,7 +121,7 @@ public class DestinationDotFileInterceptor extends DotFileInterceptorSupport {
String path = getPath(node); String path = getPath(node);
Collection children = node.getChildren(); Collection children = node.getChildren();
for (Iterator iter = children.iterator(); iter.hasNext();) { for (Iterator iter = children.iterator(); iter.hasNext();) {
DestinationMapNode child = (DestinationMapNode) iter.next(); DestinationMapNode child = (DestinationMapNode)iter.next();
writer.print(" "); writer.print(" ");
writer.print(prefix); writer.print(prefix);
@ -143,7 +139,6 @@ public class DestinationDotFileInterceptor extends DotFileInterceptorSupport {
} }
} }
protected String getPath(DestinationMapNode node) { protected String getPath(DestinationMapNode node) {
String path = node.getPath(); String path = node.getPath();
if (path.equals("*")) { if (path.equals("*")) {

View File

@ -16,18 +16,18 @@
*/ */
package org.apache.activemq.camel; package org.apache.activemq.camel;
import org.apache.activemq.ActiveMQSession;
import org.apache.camel.Endpoint;
import javax.jms.JMSException; import javax.jms.JMSException;
import javax.jms.Message; import javax.jms.Message;
import javax.jms.Queue; import javax.jms.Queue;
import javax.jms.QueueSender; import javax.jms.QueueSender;
import org.apache.activemq.ActiveMQSession;
import org.apache.camel.Endpoint;
/** /**
* A JMS {@link javax.jms.QueueSender} which sends message exchanges to a * A JMS {@link javax.jms.QueueSender} which sends message exchanges to a Camel
* Camel {@link org.apache.camel.Endpoint} * {@link org.apache.camel.Endpoint}
* *
* @version $Revision: $ * @version $Revision: $
*/ */
public class CamelQueueSender extends CamelMessageProducer implements QueueSender { public class CamelQueueSender extends CamelMessageProducer implements QueueSender {
@ -36,33 +36,30 @@ public class CamelQueueSender extends CamelMessageProducer implements QueueSende
super(destination, endpoint, session); super(destination, endpoint, session);
} }
/** /**
* Gets the queue associated with this <CODE>QueueSender</CODE>. * Gets the queue associated with this <CODE>QueueSender</CODE>.
* *
* @return this sender's queue * @return this sender's queue
* @throws JMSException if the JMS provider fails to get the queue for this * @throws JMSException if the JMS provider fails to get the queue for this
* <CODE>QueueSender</CODE> due to some internal error. * <CODE>QueueSender</CODE> due to some internal error.
*/ */
public Queue getQueue() throws JMSException { public Queue getQueue() throws JMSException {
return (Queue) super.getDestination(); return (Queue)super.getDestination();
} }
/** /**
* Sends a message to a queue for an unidentified message producer. Uses * Sends a message to a queue for an unidentified message producer. Uses the
* the <CODE>QueueSender</CODE>'s default delivery mode, priority, and * <CODE>QueueSender</CODE>'s default delivery mode, priority, and time
* time to live. * to live. <p/> <p/> Typically, a message producer is assigned a queue at
* <p/> * creation time; however, the JMS API also supports unidentified message
* <p/> * producers, which require that the queue be supplied every time a message
* Typically, a message producer is assigned a queue at creation time; * is sent.
* however, the JMS API also supports unidentified message producers, which *
* require that the queue be supplied every time a message is sent. * @param queue the queue to send this message to
*
* @param queue the queue to send this message to
* @param message the message to send * @param message the message to send
* @throws JMSException if the JMS provider fails to send the message due to some * @throws JMSException if the JMS provider fails to send the message due to
* internal error. * some internal error.
* @see javax.jms.MessageProducer#getDeliveryMode() * @see javax.jms.MessageProducer#getDeliveryMode()
* @see javax.jms.MessageProducer#getTimeToLive() * @see javax.jms.MessageProducer#getTimeToLive()
* @see javax.jms.MessageProducer#getPriority() * @see javax.jms.MessageProducer#getPriority()
@ -74,28 +71,21 @@ public class CamelQueueSender extends CamelMessageProducer implements QueueSende
/** /**
* Sends a message to a queue for an unidentified message producer, * Sends a message to a queue for an unidentified message producer,
* specifying delivery mode, priority and time to live. * specifying delivery mode, priority and time to live. <p/> <p/> Typically,
* <p/> * a message producer is assigned a queue at creation time; however, the JMS
* <p/> * API also supports unidentified message producers, which require that the
* Typically, a message producer is assigned a queue at creation time; * queue be supplied every time a message is sent.
* however, the JMS API also supports unidentified message producers, which *
* require that the queue be supplied every time a message is sent. * @param queue the queue to send this message to
* * @param message the message to send
* @param queue the queue to send this message to
* @param message the message to send
* @param deliveryMode the delivery mode to use * @param deliveryMode the delivery mode to use
* @param priority the priority for this message * @param priority the priority for this message
* @param timeToLive the message's lifetime (in milliseconds) * @param timeToLive the message's lifetime (in milliseconds)
* @throws JMSException if the JMS provider fails to send the message due to some * @throws JMSException if the JMS provider fails to send the message due to
* internal error. * some internal error.
*/ */
public void send(Queue queue, Message message, int deliveryMode, int priority, long timeToLive) public void send(Queue queue, Message message, int deliveryMode, int priority, long timeToLive) throws JMSException {
throws JMSException { super.send(queue, message, deliveryMode, priority, timeToLive);
super.send(queue,
message,
deliveryMode,
priority,
timeToLive);
} }
} }

View File

@ -41,7 +41,8 @@ import java.util.StringTokenizer;
* @openwire:marshaller * @openwire:marshaller
* @version $Revision: 1.10 $ * @version $Revision: 1.10 $
*/ */
abstract public class ActiveMQDestination extends JNDIBaseStorable implements DataStructure, Destination, Externalizable, Comparable { abstract public class ActiveMQDestination extends JNDIBaseStorable implements DataStructure, Destination,
Externalizable, Comparable {
private static final long serialVersionUID = -3885260014960795889L; private static final long serialVersionUID = -3885260014960795889L;
@ -196,7 +197,8 @@ abstract public class ActiveMQDestination extends JNDIBaseStorable implements Da
public void setPhysicalName(String physicalName) { public void setPhysicalName(String physicalName) {
final int len = physicalName.length(); final int len = physicalName.length();
int p = -1;// options offset // options offset
int p = -1;
boolean composite = false; boolean composite = false;
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
char c = physicalName.charAt(i); char c = physicalName.charAt(i);
@ -219,7 +221,8 @@ abstract public 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 + ", it's options are not encoded properly: " + e); throw new IllegalArgumentException("Invalid destination name: " + physicalName
+ ", it's options are not encoded properly: " + e);
} }
} }
this.physicalName = physicalName; this.physicalName = physicalName;

View File

@ -42,33 +42,51 @@ import org.apache.activemq.util.MarshallingSupport;
import org.apache.activemq.wireformat.WireFormat; import org.apache.activemq.wireformat.WireFormat;
/** /**
* A <CODE>MapMessage</CODE> object is used to send a set of name-value pairs. The names are <CODE>String</CODE> * A <CODE>MapMessage</CODE> object is used to send a set of name-value pairs.
* objects, and the values are primitive data types in the Java programming language. The names must have a value that * The names are <CODE>String</CODE> objects, and the values are primitive
* is not null, and not an empty string. The entries can be accessed sequentially or randomly by name. The order of the * data types in the Java programming language. The names must have a value that
* entries is undefined. <CODE>MapMessage</CODE> inherits from the <CODE>Message</CODE> interface and adds a message * is not null, and not an empty string. The entries can be accessed
* body that contains a Map. <P> The primitive types can be read or written explicitly using methods for each type. They * sequentially or randomly by name. The order of the entries is undefined.
* may also be read or written generically as objects. For instance, a call to <CODE>MapMessage.setInt("foo", 6)</CODE> * <CODE>MapMessage</CODE> inherits from the <CODE>Message</CODE> interface
* is equivalent to <CODE> MapMessage.setObject("foo", new Integer(6))</CODE>. Both forms are provided, because the * and adds a message body that contains a Map.
* explicit form is convenient for static programming, and the object form is needed when types are not known at compile * <P>
* time. <P> When a client receives a <CODE>MapMessage</CODE>, it is in read-only mode. If a client attempts to write to * The primitive types can be read or written explicitly using methods for each
* the message at this point, a <CODE>MessageNotWriteableException</CODE> is thrown. If <CODE>clearBody</CODE> is * type. They may also be read or written generically as objects. For instance,
* called, the message can now be both read from and written to. <P> <CODE>MapMessage</CODE> objects support the * a call to <CODE>MapMessage.setInt("foo", 6)</CODE> is equivalent to
* following conversion table. The marked cases must be supported. The unmarked cases must throw a * <CODE> MapMessage.setObject("foo", new Integer(6))</CODE>. Both forms are
* <CODE>JMSException</CODE>. The <CODE>String</CODE> -to-primitive conversions may throw a runtime exception if the * provided, because the explicit form is convenient for static programming, and
* primitive's <CODE>valueOf()</CODE> method does not accept it as a valid <CODE> String</CODE> representation of the * the object form is needed when types are not known at compile time.
* primitive. <P> A value written as the row type can be read as the column type. * <P>
* <p/> * When a client receives a <CODE>MapMessage</CODE>, it is in read-only mode.
* <PRE>| | boolean byte short char int long float double String byte[] |---------------------------------------------------------------------- * If a client attempts to write to the message at this point, a
* <CODE>MessageNotWriteableException</CODE> is thrown. If
* <CODE>clearBody</CODE> is called, the message can now be both read from and
* written to.
* <P>
* <CODE>MapMessage</CODE> objects support the following conversion table. The
* marked cases must be supported. The unmarked cases must throw a
* <CODE>JMSException</CODE>. The <CODE>String</CODE> -to-primitive
* conversions may throw a runtime exception if the primitive's
* <CODE>valueOf()</CODE> method does not accept it as a valid
* <CODE> String</CODE> representation of the primitive.
* <P>
* A value written as the row type can be read as the column type. <p/>
*
* <PRE>
* | | boolean byte short char int long float double String byte[] |----------------------------------------------------------------------
* |boolean | X X |byte | X X X X X |short | X X X X |char | X X |int | X X X |long | X X |float | X X X |double | X X * |boolean | X X |byte | X X X X X |short | X X X X |char | X X |int | X X X |long | X X |float | X X X |double | X X
* |String | X X X X X X X X |byte[] | X |---------------------------------------------------------------------- * |String | X X X X X X X X |byte[] | X |----------------------------------------------------------------------
* <p/> * &lt;p/&gt;
* </PRE> * </PRE>
*
* <p/> * <p/>
* <P> Attempting to read a null value as a primitive type must be treated as calling the primitive's corresponding * <P>
* <code>valueOf(String)</code> conversion method with a null value. Since <code>char</code> does not support a * Attempting to read a null value as a primitive type must be treated as
* <code>String</code> conversion, attempting to read a null value as a <code>char</code> must throw a * calling the primitive's corresponding <code>valueOf(String)</code>
* <code>NullPointerException</code>. * conversion method with a null value. Since <code>char</code> does not
* * support a <code>String</code> conversion, attempting to read a null value
* as a <code>char</code> must throw a <code>NullPointerException</code>.
*
* @openwire:marshaller code="25" * @openwire:marshaller code="25"
* @see javax.jms.Session#createMapMessage() * @see javax.jms.Session#createMapMessage()
* @see javax.jms.BytesMessage * @see javax.jms.BytesMessage
@ -99,14 +117,14 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
super.beforeMarshall(wireFormat); super.beforeMarshall(wireFormat);
storeContent(); storeContent();
} }
private void storeContent() { private void storeContent() {
try { try {
if( getContent()==null && !map.isEmpty()) { if (getContent() == null && !map.isEmpty()) {
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
OutputStream os = bytesOut; OutputStream os = bytesOut;
ActiveMQConnection connection = getConnection(); ActiveMQConnection connection = getConnection();
if( connection!= null && connection.isUseCompression() ) { if (connection != null && connection.isUseCompression()) {
compressed = true; compressed = true;
os = new DeflaterOutputStream(os); os = new DeflaterOutputStream(os);
} }
@ -119,19 +137,20 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
/** /**
* Builds the message body from data * Builds the message body from data
* @throws JMSException *
* * @throws JMSException
*
* @throws IOException * @throws IOException
*/ */
private void loadContent() throws JMSException { private void loadContent() throws JMSException {
try { try {
if( getContent()!=null && map.isEmpty() ) { if (getContent() != null && map.isEmpty()) {
ByteSequence content = getContent(); ByteSequence content = getContent();
InputStream is = new ByteArrayInputStream(content); InputStream is = new ByteArrayInputStream(content);
if( isCompressed() ) { if (isCompressed()) {
is = new InflaterInputStream(is); is = new InflaterInputStream(is);
} }
DataInputStream dataIn = new DataInputStream(is); DataInputStream dataIn = new DataInputStream(is);
@ -146,16 +165,18 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
public byte getDataStructureType() { public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE; return DATA_STRUCTURE_TYPE;
} }
public String getJMSXMimeType() { public String getJMSXMimeType() {
return "jms/map-message"; return "jms/map-message";
} }
/** /**
* Clears out the message body. Clearing a message's body does not clear its header values or property entries. <P> * Clears out the message body. Clearing a message's body does not clear its
* If this message body was read-only, calling this method leaves the message body in the same state as an empty * header values or property entries.
* body in a newly created message. * <P>
* If this message body was read-only, calling this method leaves the
* message body in the same state as an empty body in a newly created
* message.
*/ */
public void clearBody() throws JMSException { public void clearBody() throws JMSException {
super.clearBody(); super.clearBody();
@ -164,10 +185,11 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Returns the <CODE>boolean</CODE> value with the specified name. * Returns the <CODE>boolean</CODE> value with the specified name.
* *
* @param name the name of the <CODE>boolean</CODE> * @param name the name of the <CODE>boolean</CODE>
* @return the <CODE>boolean</CODE> value with the specified name * @return the <CODE>boolean</CODE> value with the specified name
* @throws JMSException if the JMS provider fails to read the message due to some internal error. * @throws JMSException if the JMS provider fails to read the message due to
* some internal error.
* @throws MessageFormatException if this type conversion is invalid. * @throws MessageFormatException if this type conversion is invalid.
*/ */
public boolean getBoolean(String name) throws JMSException { public boolean getBoolean(String name) throws JMSException {
@ -177,7 +199,7 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
return false; return false;
} }
if (value instanceof Boolean) { if (value instanceof Boolean) {
return ((Boolean) value).booleanValue(); return ((Boolean)value).booleanValue();
} }
if (value instanceof String) { if (value instanceof String) {
return Boolean.valueOf(value.toString()).booleanValue(); return Boolean.valueOf(value.toString()).booleanValue();
@ -188,10 +210,11 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Returns the <CODE>byte</CODE> value with the specified name. * Returns the <CODE>byte</CODE> value with the specified name.
* *
* @param name the name of the <CODE>byte</CODE> * @param name the name of the <CODE>byte</CODE>
* @return the <CODE>byte</CODE> value with the specified name * @return the <CODE>byte</CODE> value with the specified name
* @throws JMSException if the JMS provider fails to read the message due to some internal error. * @throws JMSException if the JMS provider fails to read the message due to
* some internal error.
* @throws MessageFormatException if this type conversion is invalid. * @throws MessageFormatException if this type conversion is invalid.
*/ */
public byte getByte(String name) throws JMSException { public byte getByte(String name) throws JMSException {
@ -201,7 +224,7 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
return 0; return 0;
} }
if (value instanceof Byte) { if (value instanceof Byte) {
return ((Byte) value).byteValue(); return ((Byte)value).byteValue();
} }
if (value instanceof String) { if (value instanceof String) {
return Byte.valueOf(value.toString()).byteValue(); return Byte.valueOf(value.toString()).byteValue();
@ -212,10 +235,11 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Returns the <CODE>short</CODE> value with the specified name. * Returns the <CODE>short</CODE> value with the specified name.
* *
* @param name the name of the <CODE>short</CODE> * @param name the name of the <CODE>short</CODE>
* @return the <CODE>short</CODE> value with the specified name * @return the <CODE>short</CODE> value with the specified name
* @throws JMSException if the JMS provider fails to read the message due to some internal error. * @throws JMSException if the JMS provider fails to read the message due to
* some internal error.
* @throws MessageFormatException if this type conversion is invalid. * @throws MessageFormatException if this type conversion is invalid.
*/ */
public short getShort(String name) throws JMSException { public short getShort(String name) throws JMSException {
@ -225,10 +249,10 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
return 0; return 0;
} }
if (value instanceof Short) { if (value instanceof Short) {
return ((Short) value).shortValue(); return ((Short)value).shortValue();
} }
if (value instanceof Byte) { if (value instanceof Byte) {
return ((Byte) value).shortValue(); return ((Byte)value).shortValue();
} }
if (value instanceof String) { if (value instanceof String) {
return Short.valueOf(value.toString()).shortValue(); return Short.valueOf(value.toString()).shortValue();
@ -239,10 +263,11 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Returns the Unicode character value with the specified name. * Returns the Unicode character value with the specified name.
* *
* @param name the name of the Unicode character * @param name the name of the Unicode character
* @return the Unicode character value with the specified name * @return the Unicode character value with the specified name
* @throws JMSException if the JMS provider fails to read the message due to some internal error. * @throws JMSException if the JMS provider fails to read the message due to
* some internal error.
* @throws MessageFormatException if this type conversion is invalid. * @throws MessageFormatException if this type conversion is invalid.
*/ */
public char getChar(String name) throws JMSException { public char getChar(String name) throws JMSException {
@ -252,7 +277,7 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
throw new NullPointerException(); throw new NullPointerException();
} }
if (value instanceof Character) { if (value instanceof Character) {
return ((Character) value).charValue(); return ((Character)value).charValue();
} else { } else {
throw new MessageFormatException(" cannot read a short from " + value.getClass().getName()); throw new MessageFormatException(" cannot read a short from " + value.getClass().getName());
} }
@ -260,10 +285,11 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Returns the <CODE>int</CODE> value with the specified name. * Returns the <CODE>int</CODE> value with the specified name.
* *
* @param name the name of the <CODE>int</CODE> * @param name the name of the <CODE>int</CODE>
* @return the <CODE>int</CODE> value with the specified name * @return the <CODE>int</CODE> value with the specified name
* @throws JMSException if the JMS provider fails to read the message due to some internal error. * @throws JMSException if the JMS provider fails to read the message due to
* some internal error.
* @throws MessageFormatException if this type conversion is invalid. * @throws MessageFormatException if this type conversion is invalid.
*/ */
public int getInt(String name) throws JMSException { public int getInt(String name) throws JMSException {
@ -273,13 +299,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
return 0; return 0;
} }
if (value instanceof Integer) { if (value instanceof Integer) {
return ((Integer) value).intValue(); return ((Integer)value).intValue();
} }
if (value instanceof Short) { if (value instanceof Short) {
return ((Short) value).intValue(); return ((Short)value).intValue();
} }
if (value instanceof Byte) { if (value instanceof Byte) {
return ((Byte) value).intValue(); return ((Byte)value).intValue();
} }
if (value instanceof String) { if (value instanceof String) {
return Integer.valueOf(value.toString()).intValue(); return Integer.valueOf(value.toString()).intValue();
@ -290,10 +316,11 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Returns the <CODE>long</CODE> value with the specified name. * Returns the <CODE>long</CODE> value with the specified name.
* *
* @param name the name of the <CODE>long</CODE> * @param name the name of the <CODE>long</CODE>
* @return the <CODE>long</CODE> value with the specified name * @return the <CODE>long</CODE> value with the specified name
* @throws JMSException if the JMS provider fails to read the message due to some internal error. * @throws JMSException if the JMS provider fails to read the message due to
* some internal error.
* @throws MessageFormatException if this type conversion is invalid. * @throws MessageFormatException if this type conversion is invalid.
*/ */
public long getLong(String name) throws JMSException { public long getLong(String name) throws JMSException {
@ -303,16 +330,16 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
return 0; return 0;
} }
if (value instanceof Long) { if (value instanceof Long) {
return ((Long) value).longValue(); return ((Long)value).longValue();
} }
if (value instanceof Integer) { if (value instanceof Integer) {
return ((Integer) value).longValue(); return ((Integer)value).longValue();
} }
if (value instanceof Short) { if (value instanceof Short) {
return ((Short) value).longValue(); return ((Short)value).longValue();
} }
if (value instanceof Byte) { if (value instanceof Byte) {
return ((Byte) value).longValue(); return ((Byte)value).longValue();
} }
if (value instanceof String) { if (value instanceof String) {
return Long.valueOf(value.toString()).longValue(); return Long.valueOf(value.toString()).longValue();
@ -323,10 +350,11 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Returns the <CODE>float</CODE> value with the specified name. * Returns the <CODE>float</CODE> value with the specified name.
* *
* @param name the name of the <CODE>float</CODE> * @param name the name of the <CODE>float</CODE>
* @return the <CODE>float</CODE> value with the specified name * @return the <CODE>float</CODE> value with the specified name
* @throws JMSException if the JMS provider fails to read the message due to some internal error. * @throws JMSException if the JMS provider fails to read the message due to
* some internal error.
* @throws MessageFormatException if this type conversion is invalid. * @throws MessageFormatException if this type conversion is invalid.
*/ */
public float getFloat(String name) throws JMSException { public float getFloat(String name) throws JMSException {
@ -336,7 +364,7 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
return 0; return 0;
} }
if (value instanceof Float) { if (value instanceof Float) {
return ((Float) value).floatValue(); return ((Float)value).floatValue();
} }
if (value instanceof String) { if (value instanceof String) {
return Float.valueOf(value.toString()).floatValue(); return Float.valueOf(value.toString()).floatValue();
@ -347,10 +375,11 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Returns the <CODE>double</CODE> value with the specified name. * Returns the <CODE>double</CODE> value with the specified name.
* *
* @param name the name of the <CODE>double</CODE> * @param name the name of the <CODE>double</CODE>
* @return the <CODE>double</CODE> value with the specified name * @return the <CODE>double</CODE> value with the specified name
* @throws JMSException if the JMS provider fails to read the message due to some internal error. * @throws JMSException if the JMS provider fails to read the message due to
* some internal error.
* @throws MessageFormatException if this type conversion is invalid. * @throws MessageFormatException if this type conversion is invalid.
*/ */
public double getDouble(String name) throws JMSException { public double getDouble(String name) throws JMSException {
@ -360,10 +389,10 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
return 0; return 0;
} }
if (value instanceof Double) { if (value instanceof Double) {
return ((Double) value).doubleValue(); return ((Double)value).doubleValue();
} }
if (value instanceof Float) { if (value instanceof Float) {
return ((Float) value).floatValue(); return ((Float)value).floatValue();
} }
if (value instanceof String) { if (value instanceof String) {
return Float.valueOf(value.toString()).floatValue(); return Float.valueOf(value.toString()).floatValue();
@ -374,11 +403,12 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Returns the <CODE>String</CODE> value with the specified name. * Returns the <CODE>String</CODE> value with the specified name.
* *
* @param name the name of the <CODE>String</CODE> * @param name the name of the <CODE>String</CODE>
* @return the <CODE>String</CODE> value with the specified name; if there is no item by this name, a null value is * @return the <CODE>String</CODE> value with the specified name; if there
* returned * is no item by this name, a null value is returned
* @throws JMSException if the JMS provider fails to read the message due to some internal error. * @throws JMSException if the JMS provider fails to read the message due to
* some internal error.
* @throws MessageFormatException if this type conversion is invalid. * @throws MessageFormatException if this type conversion is invalid.
*/ */
public String getString(String name) throws JMSException { public String getString(String name) throws JMSException {
@ -396,34 +426,42 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Returns the byte array value with the specified name. * Returns the byte array value with the specified name.
* *
* @param name the name of the byte array * @param name the name of the byte array
* @return a copy of the byte array value with the specified name; if there is no item by this name, a null value is * @return a copy of the byte array value with the specified name; if there
* returned. * is no item by this name, a null value is returned.
* @throws JMSException if the JMS provider fails to read the message due to some internal error. * @throws JMSException if the JMS provider fails to read the message due to
* some internal error.
* @throws MessageFormatException if this type conversion is invalid. * @throws MessageFormatException if this type conversion is invalid.
*/ */
public byte[] getBytes(String name) throws JMSException { public byte[] getBytes(String name) throws JMSException {
initializeReading(); initializeReading();
Object value = map.get(name); Object value = map.get(name);
if ( value instanceof byte[] ) { if (value instanceof byte[]) {
return (byte[]) value; return (byte[])value;
} else { } else {
throw new MessageFormatException(" cannot read a byte[] from " + value.getClass().getName()); throw new MessageFormatException(" cannot read a byte[] from " + value.getClass().getName());
} }
} }
/** /**
* Returns the value of the object with the specified name. <P> This method can be used to return, in objectified * Returns the value of the object with the specified name.
* format, an object in the Java programming language ("Java object") that had been stored in the Map with the * <P>
* equivalent <CODE>setObject</CODE> method call, or its equivalent primitive <CODE>set <I>type </I></CODE> method. * This method can be used to return, in objectified format, an object in
* <P> Note that byte values are returned as <CODE>byte[]</CODE>, not <CODE>Byte[]</CODE>. * the Java programming language ("Java object") that had been stored in the
* * Map with the equivalent <CODE>setObject</CODE> method call, or its
* equivalent primitive <CODE>set <I>type </I></CODE> method.
* <P>
* Note that byte values are returned as <CODE>byte[]</CODE>, not
* <CODE>Byte[]</CODE>.
*
* @param name the name of the Java object * @param name the name of the Java object
* @return a copy of the Java object value with the specified name, in objectified format (for example, if the * @return a copy of the Java object value with the specified name, in
* object was set as an <CODE>int</CODE>, an <CODE>Integer</CODE> is returned); if there is no item by this * objectified format (for example, if the object was set as an
* name, a null value is returned * <CODE>int</CODE>, an <CODE>Integer</CODE> is returned); if
* @throws JMSException if the JMS provider fails to read the message due to some internal error. * there is no item by this name, a null value is returned
* @throws JMSException if the JMS provider fails to read the message due to
* some internal error.
*/ */
public Object getObject(String name) throws JMSException { public Object getObject(String name) throws JMSException {
initializeReading(); initializeReading();
@ -431,8 +469,9 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
} }
/** /**
* Returns an <CODE>Enumeration</CODE> of all the names in the <CODE>MapMessage</CODE> object. * Returns an <CODE>Enumeration</CODE> of all the names in the
* * <CODE>MapMessage</CODE> object.
*
* @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
*/ */
@ -453,11 +492,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Sets a <CODE>boolean</CODE> value with the specified name into the Map. * Sets a <CODE>boolean</CODE> value with the specified name into the Map.
* *
* @param name the name of the <CODE>boolean</CODE> * @param name the name of the <CODE>boolean</CODE>
* @param value the <CODE>boolean</CODE> value to set in the Map * @param value the <CODE>boolean</CODE> value to set in the Map
* @throws JMSException if the JMS provider fails to write the message due to some internal error. * @throws JMSException if the JMS provider fails to write the message due
* @throws IllegalArgumentException if the name is null or if the name is an empty string. * to some internal error.
* @throws IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode. * @throws MessageNotWriteableException if the message is in read-only mode.
*/ */
public void setBoolean(String name, boolean value) throws JMSException { public void setBoolean(String name, boolean value) throws JMSException {
@ -467,11 +508,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Sets a <CODE>byte</CODE> value with the specified name into the Map. * Sets a <CODE>byte</CODE> value with the specified name into the Map.
* *
* @param name the name of the <CODE>byte</CODE> * @param name the name of the <CODE>byte</CODE>
* @param value the <CODE>byte</CODE> value to set in the Map * @param value the <CODE>byte</CODE> value to set in the Map
* @throws JMSException if the JMS provider fails to write the message due to some internal error. * @throws JMSException if the JMS provider fails to write the message due
* @throws IllegalArgumentException if the name is null or if the name is an empty string. * to some internal error.
* @throws IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode. * @throws MessageNotWriteableException if the message is in read-only mode.
*/ */
public void setByte(String name, byte value) throws JMSException { public void setByte(String name, byte value) throws JMSException {
@ -481,11 +524,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Sets a <CODE>short</CODE> value with the specified name into the Map. * Sets a <CODE>short</CODE> value with the specified name into the Map.
* *
* @param name the name of the <CODE>short</CODE> * @param name the name of the <CODE>short</CODE>
* @param value the <CODE>short</CODE> value to set in the Map * @param value the <CODE>short</CODE> value to set in the Map
* @throws JMSException if the JMS provider fails to write the message due to some internal error. * @throws JMSException if the JMS provider fails to write the message due
* @throws IllegalArgumentException if the name is null or if the name is an empty string. * to some internal error.
* @throws IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode. * @throws MessageNotWriteableException if the message is in read-only mode.
*/ */
public void setShort(String name, short value) throws JMSException { public void setShort(String name, short value) throws JMSException {
@ -495,11 +540,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Sets a Unicode character value with the specified name into the Map. * Sets a Unicode character value with the specified name into the Map.
* *
* @param name the name of the Unicode character * @param name the name of the Unicode character
* @param value the Unicode character value to set in the Map * @param value the Unicode character value to set in the Map
* @throws JMSException if the JMS provider fails to write the message due to some internal error. * @throws JMSException if the JMS provider fails to write the message due
* @throws IllegalArgumentException if the name is null or if the name is an empty string. * to some internal error.
* @throws IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode. * @throws MessageNotWriteableException if the message is in read-only mode.
*/ */
public void setChar(String name, char value) throws JMSException { public void setChar(String name, char value) throws JMSException {
@ -509,11 +556,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Sets an <CODE>int</CODE> value with the specified name into the Map. * Sets an <CODE>int</CODE> value with the specified name into the Map.
* *
* @param name the name of the <CODE>int</CODE> * @param name the name of the <CODE>int</CODE>
* @param value the <CODE>int</CODE> value to set in the Map * @param value the <CODE>int</CODE> value to set in the Map
* @throws JMSException if the JMS provider fails to write the message due to some internal error. * @throws JMSException if the JMS provider fails to write the message due
* @throws IllegalArgumentException if the name is null or if the name is an empty string. * to some internal error.
* @throws IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode. * @throws MessageNotWriteableException if the message is in read-only mode.
*/ */
public void setInt(String name, int value) throws JMSException { public void setInt(String name, int value) throws JMSException {
@ -523,11 +572,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Sets a <CODE>long</CODE> value with the specified name into the Map. * Sets a <CODE>long</CODE> value with the specified name into the Map.
* *
* @param name the name of the <CODE>long</CODE> * @param name the name of the <CODE>long</CODE>
* @param value the <CODE>long</CODE> value to set in the Map * @param value the <CODE>long</CODE> value to set in the Map
* @throws JMSException if the JMS provider fails to write the message due to some internal error. * @throws JMSException if the JMS provider fails to write the message due
* @throws IllegalArgumentException if the name is null or if the name is an empty string. * to some internal error.
* @throws IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode. * @throws MessageNotWriteableException if the message is in read-only mode.
*/ */
public void setLong(String name, long value) throws JMSException { public void setLong(String name, long value) throws JMSException {
@ -537,11 +588,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Sets a <CODE>float</CODE> value with the specified name into the Map. * Sets a <CODE>float</CODE> value with the specified name into the Map.
* *
* @param name the name of the <CODE>float</CODE> * @param name the name of the <CODE>float</CODE>
* @param value the <CODE>float</CODE> value to set in the Map * @param value the <CODE>float</CODE> value to set in the Map
* @throws JMSException if the JMS provider fails to write the message due to some internal error. * @throws JMSException if the JMS provider fails to write the message due
* @throws IllegalArgumentException if the name is null or if the name is an empty string. * to some internal error.
* @throws IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode. * @throws MessageNotWriteableException if the message is in read-only mode.
*/ */
public void setFloat(String name, float value) throws JMSException { public void setFloat(String name, float value) throws JMSException {
@ -551,11 +604,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Sets a <CODE>double</CODE> value with the specified name into the Map. * Sets a <CODE>double</CODE> value with the specified name into the Map.
* *
* @param name the name of the <CODE>double</CODE> * @param name the name of the <CODE>double</CODE>
* @param value the <CODE>double</CODE> value to set in the Map * @param value the <CODE>double</CODE> value to set in the Map
* @throws JMSException if the JMS provider fails to write the message due to some internal error. * @throws JMSException if the JMS provider fails to write the message due
* @throws IllegalArgumentException if the name is null or if the name is an empty string. * to some internal error.
* @throws IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode. * @throws MessageNotWriteableException if the message is in read-only mode.
*/ */
public void setDouble(String name, double value) throws JMSException { public void setDouble(String name, double value) throws JMSException {
@ -565,11 +620,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Sets a <CODE>String</CODE> value with the specified name into the Map. * Sets a <CODE>String</CODE> value with the specified name into the Map.
* *
* @param name the name of the <CODE>String</CODE> * @param name the name of the <CODE>String</CODE>
* @param value the <CODE>String</CODE> value to set in the Map * @param value the <CODE>String</CODE> value to set in the Map
* @throws JMSException if the JMS provider fails to write the message due to some internal error. * @throws JMSException if the JMS provider fails to write the message due
* @throws IllegalArgumentException if the name is null or if the name is an empty string. * to some internal error.
* @throws IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode. * @throws MessageNotWriteableException if the message is in read-only mode.
*/ */
public void setString(String name, String value) throws JMSException { public void setString(String name, String value) throws JMSException {
@ -579,12 +636,15 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/** /**
* Sets a byte array value with the specified name into the Map. * Sets a byte array value with the specified name into the Map.
* *
* @param name the name of the byte array * @param name the name of the byte array
* @param value the byte array value to set in the Map; the array is copied so that the value for <CODE>name </CODE> * @param value the byte array value to set in the Map; the array is copied
* will not be altered by future modifications * so that the value for <CODE>name </CODE> will not be
* @throws JMSException if the JMS provider fails to write the message due to some internal error. * altered by future modifications
* @throws NullPointerException if the name is null, or if the name is an empty string. * @throws JMSException if the JMS provider fails to write the message due
* to some internal error.
* @throws NullPointerException if the name is null, or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode. * @throws MessageNotWriteableException if the message is in read-only mode.
*/ */
public void setBytes(String name, byte[] value) throws JMSException { public void setBytes(String name, byte[] value) throws JMSException {
@ -597,14 +657,17 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
} }
/** /**
* Sets a portion of the byte array value with the specified name into the Map. * Sets a portion of the byte array value with the specified name into the
* * Map.
* @param name the name of the byte array *
* @param value the byte array value to set in the Map * @param name the name of the byte array
* @param value the byte array value to set in the Map
* @param offset the initial offset within the byte array * @param offset the initial offset within the byte array
* @param length the number of bytes to use * @param length the number of bytes to use
* @throws JMSException if the JMS provider fails to write the message due to some internal error. * @throws JMSException if the JMS provider fails to write the message due
* @throws IllegalArgumentException if the name is null or if the name is an empty string. * to some internal error.
* @throws IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode. * @throws MessageNotWriteableException if the message is in read-only mode.
*/ */
public void setBytes(String name, byte[] value, int offset, int length) throws JMSException { public void setBytes(String name, byte[] value, int offset, int length) throws JMSException {
@ -615,15 +678,19 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
} }
/** /**
* Sets an object value with the specified name into the Map. <P> This method works only for the objectified * Sets an object value with the specified name into the Map.
* primitive object types (<code>Integer</code>,<code>Double</code>, <code>Long</code> &nbsp;...), * <P>
* <code>String</code> objects, and byte arrays. * This method works only for the objectified primitive object types (<code>Integer</code>,<code>Double</code>,
* * <code>Long</code> &nbsp;...), <code>String</code> objects, and byte
* @param name the name of the Java object * arrays.
*
* @param name the name of the Java object
* @param value the Java object value to set in the Map * @param value the Java object value to set in the Map
* @throws JMSException if the JMS provider fails to write the message due to some internal error. * @throws JMSException if the JMS provider fails to write the message due
* @throws IllegalArgumentException if the name is null or if the name is an empty string. * to some internal error.
* @throws MessageFormatException if the object is invalid. * @throws IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageFormatException if the object is invalid.
* @throws MessageNotWriteableException if the message is in read-only mode. * @throws MessageNotWriteableException if the message is in read-only mode.
*/ */
public void setObject(String name, Object value) throws JMSException { public void setObject(String name, Object value) throws JMSException {
@ -640,32 +707,32 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
} }
/** /**
* Indicates whether an item exists in this <CODE>MapMessage</CODE> object. * Indicates whether an item exists in this <CODE>MapMessage</CODE>
* * object.
*
* @param name the name of the item to test * @param name the name of the item to test
* @return true if the item exists * @return true if the item exists
* @throws JMSException if the JMS provider fails to determine if the item exists due to some internal error. * @throws JMSException if the JMS provider fails to determine if the item
* exists due to some internal error.
*/ */
public boolean itemExists(String name) throws JMSException { public boolean itemExists(String name) throws JMSException {
initializeReading(); initializeReading();
return map.containsKey(name); return map.containsKey(name);
} }
private void initializeReading() throws JMSException { private void initializeReading() throws JMSException {
loadContent(); loadContent();
} }
private void initializeWriting() throws MessageNotWriteableException { private void initializeWriting() throws MessageNotWriteableException {
checkReadOnlyBody(); checkReadOnlyBody();
setContent(null); setContent(null);
} }
public String toString() { public String toString() {
return super.toString() + " ActiveMQMapMessage{ " + return super.toString() + " ActiveMQMapMessage{ " + "theTable = " + map + " }";
"theTable = " + map +
" }";
} }
public Map getContentMap() throws JMSException { public Map getContentMap() throws JMSException {
initializeReading(); initializeReading();
return map; return map;

View File

@ -17,9 +17,6 @@
package org.apache.activemq.command; package org.apache.activemq.command;
import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.util.ByteArrayInputStream; import org.apache.activemq.util.ByteArrayInputStream;
import org.apache.activemq.util.ByteArrayOutputStream; import org.apache.activemq.util.ByteArrayOutputStream;
@ -40,17 +37,21 @@ import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream; import java.util.zip.InflaterInputStream;
/** /**
* An <CODE>ObjectMessage</CODE> object is used to send a message that contains a serializable object in the Java * An <CODE>ObjectMessage</CODE> object is used to send a message that
* programming language ("Java object"). It inherits from the <CODE>Message</CODE> interface and adds a body containing * contains a serializable object in the Java programming language ("Java
* a single reference to an object. Only <CODE>Serializable</CODE> Java objects can be used. * object"). It inherits from the <CODE>Message</CODE> interface and adds a
* <p/> * body containing a single reference to an object. Only
* <P>If a collection of Java objects must be sent, one of the <CODE>Collection</CODE> classes provided since JDK 1.2 * <CODE>Serializable</CODE> Java objects can be used. <p/>
* can be used. * <P>
* <p/> * If a collection of Java objects must be sent, one of the
* <P>When a client receives an <CODE>ObjectMessage</CODE>, it is in read-only mode. If a client attempts to write to * <CODE>Collection</CODE> classes provided since JDK 1.2 can be used. <p/>
* the message at this point, a <CODE>MessageNotWriteableException</CODE> is thrown. If <CODE>clearBody</CODE> is * <P>
* called, the message can now be both read from and written to. * When a client receives an <CODE>ObjectMessage</CODE>, it is in read-only
* * mode. If a client attempts to write to the message at this point, a
* <CODE>MessageNotWriteableException</CODE> is thrown. If
* <CODE>clearBody</CODE> is called, the message can now be both read from and
* written to.
*
* @openwire:marshaller code="26" * @openwire:marshaller code="26"
* @see javax.jms.Session#createObjectMessage() * @see javax.jms.Session#createObjectMessage()
* @see javax.jms.Session#createObjectMessage(Serializable) * @see javax.jms.Session#createObjectMessage(Serializable)
@ -61,7 +62,9 @@ import java.util.zip.InflaterInputStream;
* @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 classloader static final ClassLoader ACTIVEMQ_CLASSLOADER = ActiveMQObjectMessage.class.getClassLoader(); // TODO
// verify
// classloader
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_OBJECT_MESSAGE; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_OBJECT_MESSAGE;
protected transient Serializable object; protected transient Serializable object;
@ -75,9 +78,9 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess
private void copy(ActiveMQObjectMessage copy) { private void copy(ActiveMQObjectMessage copy) {
storeContent(); storeContent();
super.copy(copy); super.copy(copy);
copy.object=null; copy.object = null;
} }
public void storeContent() { public void storeContent() {
ByteSequence bodyAsBytes = getContent(); ByteSequence bodyAsBytes = getContent();
if (bodyAsBytes == null && object != null) { if (bodyAsBytes == null && object != null) {
@ -85,7 +88,7 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
OutputStream os = bytesOut; OutputStream os = bytesOut;
ActiveMQConnection connection = getConnection(); ActiveMQConnection connection = getConnection();
if (connection!=null && connection.isUseCompression()) { if (connection != null && connection.isUseCompression()) {
compressed = true; compressed = true;
os = new DeflaterOutputStream(os); os = new DeflaterOutputStream(os);
} }
@ -110,14 +113,16 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess
return "jms/object-message"; return "jms/object-message";
} }
/** /**
* Clears out the message body. Clearing a message's body does not clear its header values or property entries. * Clears out the message body. Clearing a message's body does not clear its
* <p/> * header values or property entries. <p/>
* <P>If this message body was read-only, calling this method leaves the message body in the same state as an empty * <P>
* body in a newly created message. * If this message body was read-only, calling this method leaves the
* * message body in the same state as an empty body in a newly created
* @throws JMSException if the JMS provider fails to clear the message body due to some internal error. * message.
*
* @throws JMSException if the JMS provider fails to clear the message body
* due to some internal error.
*/ */
public void clearBody() throws JMSException { public void clearBody() throws JMSException {
@ -126,16 +131,18 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess
} }
/** /**
* Sets the serializable object containing this message's data. It is important to note that an * Sets the serializable object containing this message's data. It is
* <CODE>ObjectMessage</CODE> contains a snapshot of the object at the time <CODE>setObject()</CODE> is called; * important to note that an <CODE>ObjectMessage</CODE> contains a
* subsequent modifications of the object will have no effect on the <CODE>ObjectMessage</CODE> body. * snapshot of the object at the time <CODE>setObject()</CODE> is called;
* * subsequent modifications of the object will have no effect on the
* <CODE>ObjectMessage</CODE> body.
*
* @param newObject the message's data * @param newObject the message's data
* @throws JMSException if the JMS provider fails to set the object due to some internal error. * @throws JMSException if the JMS provider fails to set the object due to
* @throws javax.jms.MessageFormatException * some internal error.
* if object serialization fails. * @throws javax.jms.MessageFormatException if object serialization fails.
* @throws javax.jms.MessageNotWriteableException * @throws javax.jms.MessageNotWriteableException if the message is in
* if the message is in read-only mode. * read-only mode.
*/ */
public void setObject(Serializable newObject) throws JMSException { public void setObject(Serializable newObject) throws JMSException {
@ -143,30 +150,30 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess
this.object = newObject; this.object = newObject;
setContent(null); setContent(null);
ActiveMQConnection connection = getConnection(); ActiveMQConnection connection = getConnection();
if( connection==null || !connection.isObjectMessageSerializationDefered() ) { if (connection == null || !connection.isObjectMessageSerializationDefered()) {
storeContent(); storeContent();
} }
} }
/** /**
* Gets the serializable object containing this message's data. The default value is null. * Gets the serializable object containing this message's data. The default
* * value is null.
*
* @return the serializable object containing this message's data * @return the serializable object containing this message's data
* @throws JMSException * @throws JMSException
*/ */
public Serializable getObject() throws JMSException { public Serializable getObject() throws JMSException {
if (object == null && getContent()!=null ) { if (object == null && getContent() != null) {
try { try {
ByteSequence content = getContent(); ByteSequence content = getContent();
InputStream is = new ByteArrayInputStream(content); InputStream is = new ByteArrayInputStream(content);
if( isCompressed() ) { if (isCompressed()) {
is = new InflaterInputStream(is); is = new InflaterInputStream(is);
} }
DataInputStream dataIn = new DataInputStream(is); DataInputStream dataIn = new DataInputStream(is);
ClassLoadingAwareObjectInputStream objIn = new ClassLoadingAwareObjectInputStream(dataIn); ClassLoadingAwareObjectInputStream objIn = new ClassLoadingAwareObjectInputStream(dataIn);
try { try {
object = (Serializable) objIn.readObject(); object = (Serializable)objIn.readObject();
} catch (ClassNotFoundException ce) { } catch (ClassNotFoundException ce) {
throw new IOException(ce.getMessage()); throw new IOException(ce.getMessage());
} }
@ -180,8 +187,9 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess
public void onMessageRolledBack() { public void onMessageRolledBack() {
super.onMessageRolledBack(); super.onMessageRolledBack();
// lets force the object to be deserialized again - as we could have changed the object // lets force the object to be deserialized again - as we could have
// changed the object
object = null; object = null;
} }

View File

@ -21,15 +21,16 @@ import javax.jms.Queue;
/** /**
* *
* @org.apache.xbean.XBean element="queue" description="An ActiveMQ Queue Destination" * @org.apache.xbean.XBean element="queue" description="An ActiveMQ Queue
* * Destination"
*
* @openwire:marshaller code="100" * @openwire:marshaller code="100"
* @version $Revision: 1.5 $ * @version $Revision: 1.5 $
*/ */
public class ActiveMQQueue extends ActiveMQDestination implements Queue { public class ActiveMQQueue extends ActiveMQDestination implements Queue {
private static final long serialVersionUID = -3885260014960795889L; 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;
public ActiveMQQueue() { public ActiveMQQueue() {
} }

View File

@ -1130,8 +1130,9 @@ public class ActiveMQStreamMessage extends ActiveMQMessage implements StreamMess
checkWriteOnlyBody(); checkWriteOnlyBody();
if (this.dataIn == null) { if (this.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()) {
is = new InflaterInputStream(is); is = new InflaterInputStream(is);

View File

@ -26,20 +26,19 @@ import javax.jms.TemporaryTopic;
public class ActiveMQTempTopic extends ActiveMQTempDestination implements TemporaryTopic { public class ActiveMQTempTopic extends ActiveMQTempDestination implements TemporaryTopic {
private static final long serialVersionUID = -4325596784597300253L; 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;
public ActiveMQTempTopic() { public ActiveMQTempTopic() {
} }
public ActiveMQTempTopic(String name) { public ActiveMQTempTopic(String name) {
super(name); super(name);
} }
public ActiveMQTempTopic(ConnectionId connectionId, long sequenceId) { public ActiveMQTempTopic(ConnectionId connectionId, long sequenceId) {
super(connectionId.getValue(), sequenceId); super(connectionId.getValue(), sequenceId);
} }
public byte getDataStructureType() { public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE; return DATA_STRUCTURE_TYPE;
} }

View File

@ -138,8 +138,9 @@ public class ActiveMQTextMessage extends ActiveMQMessage implements TextMessage
public int getSize() { public int getSize() {
if (size == 0 && content == null && text != null) { if (size == 0 && content == null && text != null) {
size = AVERAGE_MESSAGE_SIZE_OVERHEAD; size = AVERAGE_MESSAGE_SIZE_OVERHEAD;
if (marshalledProperties != null) if (marshalledProperties != null) {
size += marshalledProperties.getLength(); size += marshalledProperties.getLength();
}
size = text.length() * 2; size = text.length() * 2;
} }
return super.getSize(); return super.getSize();

View File

@ -37,10 +37,12 @@ public class BrokerId 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() != BrokerId.class) }
if (o == null || o.getClass() != BrokerId.class) {
return false; return false;
}
BrokerId id = (BrokerId)o; BrokerId id = (BrokerId)o;
return value.equals(id.value); return value.equals(id.value);
} }

View File

@ -18,7 +18,6 @@ package org.apache.activemq.command;
import org.apache.activemq.state.CommandVisitor; import org.apache.activemq.state.CommandVisitor;
/** /**
* *
* @openwire:marshaller code="16" * @openwire:marshaller code="16"
@ -26,38 +25,39 @@ import org.apache.activemq.state.CommandVisitor;
*/ */
public class ConnectionError extends BaseCommand { 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; protected ConnectionId connectionId;
Throwable exception; Throwable exception;
public byte getDataStructureType() { public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE; return DATA_STRUCTURE_TYPE;
} }
public Response visit(CommandVisitor visitor) throws Exception { public Response visit(CommandVisitor visitor) throws Exception {
return visitor.processConnectionError(this); return visitor.processConnectionError(this);
} }
/** /**
* @openwire:property version=1 * @openwire:property version=1
*/ */
public Throwable getException() { public Throwable getException() {
return exception; return exception;
} }
public void setException(Throwable exception) { public void setException(Throwable exception) {
this.exception = exception; this.exception = exception;
} }
/** /**
* @openwire:property version=1 * @openwire:property version=1
*/ */
public ConnectionId getConnectionId() { public ConnectionId getConnectionId() {
return connectionId; return connectionId;
} }
public void setConnectionId(ConnectionId connectionId) { public void setConnectionId(ConnectionId connectionId) {
this.connectionId = connectionId; this.connectionId = connectionId;
} }
} }

View File

@ -18,16 +18,15 @@ package org.apache.activemq.command;
import org.apache.activemq.state.CommandVisitor; import org.apache.activemq.state.CommandVisitor;
/** /**
* *
* @openwire:marshaller code="3" * @openwire:marshaller code="3"
* @version $Revision: 1.11 $ * @version $Revision: 1.11 $
*/ */
public class ConnectionInfo extends BaseCommand { public class ConnectionInfo extends BaseCommand {
public static final byte DATA_STRUCTURE_TYPE=CommandTypes.CONNECTION_INFO; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.CONNECTION_INFO;
protected ConnectionId connectionId; protected ConnectionId connectionId;
protected String clientId; protected String clientId;
protected String userName; protected String userName;
@ -35,19 +34,20 @@ public class ConnectionInfo extends BaseCommand {
protected BrokerId[] brokerPath; protected BrokerId[] brokerPath;
protected boolean brokerMasterConnector; protected boolean brokerMasterConnector;
protected boolean manageable; protected boolean manageable;
protected boolean clientMaster=true; protected boolean clientMaster = true;
protected transient Object transportContext; protected transient Object transportContext;
public ConnectionInfo() { public ConnectionInfo() {
}
public ConnectionInfo(ConnectionId connectionId) {
this.connectionId=connectionId;
} }
public ConnectionInfo(ConnectionId connectionId) {
this.connectionId = connectionId;
}
public byte getDataStructureType() { public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE; return DATA_STRUCTURE_TYPE;
} }
public void copy(ConnectionInfo copy) { public void copy(ConnectionInfo copy) {
super.copy(copy); super.copy(copy);
copy.clientId = clientId; copy.clientId = clientId;
@ -56,7 +56,7 @@ public class ConnectionInfo extends BaseCommand {
copy.brokerPath = brokerPath; copy.brokerPath = brokerPath;
copy.brokerMasterConnector = brokerMasterConnector; copy.brokerMasterConnector = brokerMasterConnector;
copy.manageable = manageable; copy.manageable = manageable;
} }
/** /**
* @openwire:property version=1 cache=true * @openwire:property version=1 cache=true
@ -64,20 +64,22 @@ public class ConnectionInfo extends BaseCommand {
public ConnectionId getConnectionId() { public ConnectionId getConnectionId() {
return connectionId; return connectionId;
} }
public void setConnectionId(ConnectionId connectionId) { public void setConnectionId(ConnectionId connectionId) {
this.connectionId = connectionId; this.connectionId = connectionId;
} }
/** /**
* @openwire:property version=1 * @openwire:property version=1
*/ */
public String getClientId() { public String getClientId() {
return clientId; return clientId;
} }
public void setClientId(String clientId) { public void setClientId(String clientId) {
this.clientId = clientId; this.clientId = clientId;
} }
public RemoveInfo createRemoveCommand() { public RemoveInfo createRemoveCommand() {
RemoveInfo command = new RemoveInfo(getConnectionId()); RemoveInfo command = new RemoveInfo(getConnectionId());
command.setResponseRequired(isResponseRequired()); command.setResponseRequired(isResponseRequired());
@ -90,6 +92,7 @@ public class ConnectionInfo extends BaseCommand {
public String getPassword() { public String getPassword() {
return password; return password;
} }
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
@ -100,85 +103,91 @@ public class ConnectionInfo extends BaseCommand {
public String getUserName() { public String getUserName() {
return userName; return userName;
} }
public void setUserName(String userName) { public void setUserName(String userName) {
this.userName = userName; this.userName = userName;
} }
/** /**
* The route of brokers the command has moved through. * The route of brokers the command has moved through.
* *
* @openwire:property version=1 cache=true * @openwire:property version=1 cache=true
*/ */
public BrokerId[] getBrokerPath() { public BrokerId[] getBrokerPath() {
return brokerPath; return brokerPath;
} }
public void setBrokerPath(BrokerId[] brokerPath) { public void setBrokerPath(BrokerId[] brokerPath) {
this.brokerPath = brokerPath; this.brokerPath = brokerPath;
} }
public Response visit(CommandVisitor visitor) throws Exception { public Response visit(CommandVisitor visitor) throws Exception {
return visitor.processAddConnection( this ); return visitor.processAddConnection(this);
} }
/** /**
* @openwire:property version=1 * @openwire:property version=1
*/ */
public boolean isBrokerMasterConnector(){ public boolean isBrokerMasterConnector() {
return brokerMasterConnector; return brokerMasterConnector;
} }
/** /**
* @param brokerMasterConnector The brokerMasterConnector to set. * @param brokerMasterConnector The brokerMasterConnector to set.
*/ */
public void setBrokerMasterConnector(boolean slaveBroker){ public void setBrokerMasterConnector(boolean slaveBroker) {
this.brokerMasterConnector=slaveBroker; this.brokerMasterConnector = slaveBroker;
} }
/** /**
* @openwire:property version=1 * @openwire:property version=1
*/ */
public boolean isManageable(){ public boolean isManageable() {
return manageable; return manageable;
} }
/** /**
* @param manageable The manageable to set. * @param manageable The manageable to set.
*/ */
public void setManageable(boolean manageable){ public void setManageable(boolean manageable) {
this.manageable=manageable; this.manageable = manageable;
} }
/** /**
* Transports may wish to associate additional data with the connection. For * Transports may wish to associate additional data with the connection. For
* example, an SSL transport may use this field to attach the client certificates * example, an SSL transport may use this field to attach the client
* used when the conection was established. * certificates used when the conection was established.
* *
* @return the transport context. * @return the transport context.
*/ */
public Object getTransportContext() { public Object getTransportContext() {
return transportContext; return transportContext;
} }
/** /**
* Transports may wish to associate additional data with the connection. For * Transports may wish to associate additional data with the connection. For
* example, an SSL transport may use this field to attach the client certificates * example, an SSL transport may use this field to attach the client
* used when the conection was established. * certificates used when the conection was established.
* *
* @param transportContext value used to set the transport context * @param transportContext value used to set the transport context
*/ */
public void setTransportContext(Object transportContext) { public void setTransportContext(Object transportContext) {
this.transportContext = transportContext; this.transportContext = transportContext;
} }
/** /**
* @openwire:property version=2 * @openwire:property version=2
* @return the clientMaster * @return the clientMaster
*/ */
public boolean isClientMaster(){ public boolean isClientMaster() {
return this.clientMaster; return this.clientMaster;
} }
/** /**
* @param clientMaster the clientMaster to set * @param clientMaster the clientMaster to set
*/ */
public void setClientMaster(boolean clientMaster){ public void setClientMaster(boolean clientMaster) {
this.clientMaster=clientMaster; this.clientMaster = clientMaster;
} }
} }

View File

@ -46,14 +46,17 @@ public class ConsumerInfo extends BaseCommand {
protected byte priority; protected byte priority;
protected BrokerId[] brokerPath; protected BrokerId[] brokerPath;
protected boolean optimizedAcknowledge; protected boolean optimizedAcknowledge;
protected transient int currentPrefetchSize;// used by the broker // used by the broker
protected boolean noRangeAcks; // if true, the consumer will not send range protected transient int currentPrefetchSize;
// acks. // if true, the consumer will not send range
protected boolean noRangeAcks;
// acks.
protected BooleanExpression additionalPredicate; protected BooleanExpression additionalPredicate;
protected transient boolean networkSubscription; // this subscription protected transient boolean networkSubscription; // this subscription
// originated from a
// network connection // originated from a
// network connection
public ConsumerInfo() { public ConsumerInfo() {
} }

View File

@ -22,15 +22,16 @@ package org.apache.activemq.command;
* @version $Revision$ * @version $Revision$
*/ */
public class DataResponse extends Response { public class DataResponse extends Response {
DataStructure data; DataStructure data;
public static final byte DATA_STRUCTURE_TYPE=CommandTypes.DATA_RESPONSE; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.DATA_RESPONSE;
public DataResponse() { public DataResponse() {
} }
public DataResponse(DataStructure data) { public DataResponse(DataStructure data) {
this.data=data; this.data = data;
} }
public byte getDataStructureType() { public byte getDataStructureType() {
@ -39,12 +40,13 @@ public class DataResponse extends Response {
/** /**
* @openwire:property version=1 * @openwire:property version=1
*/ */
public DataStructure getData() { public DataStructure getData() {
return data; return data;
} }
public void setData(DataStructure data) { public void setData(DataStructure data) {
this.data = data; this.data = data;
} }
} }

View File

@ -18,7 +18,6 @@ package org.apache.activemq.command;
import org.apache.activemq.state.CommandVisitor; import org.apache.activemq.state.CommandVisitor;
/** /**
* *
* @openwire:marshaller code="21" * @openwire:marshaller code="21"
@ -26,7 +25,7 @@ import org.apache.activemq.state.CommandVisitor;
*/ */
public class MessageDispatch extends BaseCommand { public class MessageDispatch extends BaseCommand {
public static final byte DATA_STRUCTURE_TYPE=CommandTypes.MESSAGE_DISPATCH; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.MESSAGE_DISPATCH;
protected ConsumerId consumerId; protected ConsumerId consumerId;
protected ActiveMQDestination destination; protected ActiveMQDestination destination;
@ -36,11 +35,11 @@ public class MessageDispatch extends BaseCommand {
transient protected long deliverySequenceId; transient protected long deliverySequenceId;
transient protected Object consumer; transient protected Object consumer;
transient protected Runnable transmitCallback; transient protected Runnable transmitCallback;
public byte getDataStructureType() { public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE; return DATA_STRUCTURE_TYPE;
} }
public boolean isMessageDispatch() { public boolean isMessageDispatch() {
return true; return true;
} }
@ -51,6 +50,7 @@ public class MessageDispatch extends BaseCommand {
public ConsumerId getConsumerId() { public ConsumerId getConsumerId() {
return consumerId; return consumerId;
} }
public void setConsumerId(ConsumerId consumerId) { public void setConsumerId(ConsumerId consumerId) {
this.consumerId = consumerId; this.consumerId = consumerId;
} }
@ -61,16 +61,18 @@ public class MessageDispatch extends BaseCommand {
public ActiveMQDestination getDestination() { public ActiveMQDestination getDestination() {
return destination; return destination;
} }
public void setDestination(ActiveMQDestination destination) { public void setDestination(ActiveMQDestination destination) {
this.destination = destination; this.destination = destination;
} }
/** /**
* @openwire:property version=1 * @openwire:property version=1
*/ */
public Message getMessage() { public Message getMessage() {
return message; return message;
} }
public void setMessage(Message message) { public void setMessage(Message message) {
this.message = message; this.message = message;
} }
@ -78,16 +80,18 @@ public class MessageDispatch extends BaseCommand {
public long getDeliverySequenceId() { public long getDeliverySequenceId() {
return deliverySequenceId; return deliverySequenceId;
} }
public void setDeliverySequenceId(long deliverySequenceId) { public void setDeliverySequenceId(long deliverySequenceId) {
this.deliverySequenceId = deliverySequenceId; this.deliverySequenceId = deliverySequenceId;
} }
/** /**
* @openwire:property version=1 * @openwire:property version=1
*/ */
public int getRedeliveryCounter() { public int getRedeliveryCounter() {
return redeliveryCounter; return redeliveryCounter;
} }
public void setRedeliveryCounter(int deliveryCounter) { public void setRedeliveryCounter(int deliveryCounter) {
this.redeliveryCounter = deliveryCounter; this.redeliveryCounter = deliveryCounter;
} }
@ -104,12 +108,12 @@ public class MessageDispatch extends BaseCommand {
return visitor.processMessageDispatch(this); return visitor.processMessageDispatch(this);
} }
public Runnable getTransmitCallback() { public Runnable getTransmitCallback() {
return transmitCallback; return transmitCallback;
} }
public void setTransmitCallback(Runnable transmitCallback) {
this.transmitCallback = transmitCallback;
}
public void setTransmitCallback(Runnable transmitCallback) {
this.transmitCallback = transmitCallback;
}
} }

View File

@ -25,14 +25,14 @@ import org.apache.activemq.state.CommandVisitor;
*/ */
public class ProducerInfo extends BaseCommand { public class ProducerInfo extends BaseCommand {
public static final byte DATA_STRUCTURE_TYPE=CommandTypes.PRODUCER_INFO; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.PRODUCER_INFO;
protected ProducerId producerId; protected ProducerId producerId;
protected ActiveMQDestination destination; protected ActiveMQDestination destination;
protected BrokerId[] brokerPath; protected BrokerId[] brokerPath;
protected boolean dispatchAsync; protected boolean dispatchAsync;
protected int windowSize; protected int windowSize;
public ProducerInfo() { public ProducerInfo() {
} }
@ -59,77 +59,80 @@ public class ProducerInfo extends BaseCommand {
public byte getDataStructureType() { public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE; return DATA_STRUCTURE_TYPE;
} }
/** /**
* @openwire:property version=1 cache=true * @openwire:property version=1 cache=true
*/ */
public ProducerId getProducerId() { public ProducerId getProducerId() {
return producerId; return producerId;
} }
public void setProducerId(ProducerId producerId) { public void setProducerId(ProducerId producerId) {
this.producerId = producerId; this.producerId = producerId;
} }
/** /**
* @openwire:property version=1 cache=true * @openwire:property version=1 cache=true
*/ */
public ActiveMQDestination getDestination() { public ActiveMQDestination getDestination() {
return destination; return destination;
} }
public void setDestination(ActiveMQDestination destination) { public void setDestination(ActiveMQDestination destination) {
this.destination = destination; this.destination = destination;
} }
public RemoveInfo createRemoveCommand() { public RemoveInfo createRemoveCommand() {
RemoveInfo command = new RemoveInfo(getProducerId()); RemoveInfo command = new RemoveInfo(getProducerId());
command.setResponseRequired(isResponseRequired()); command.setResponseRequired(isResponseRequired());
return command; return command;
} }
/** /**
* The route of brokers the command has moved through. * The route of brokers the command has moved through.
* *
* @openwire:property version=1 cache=true * @openwire:property version=1 cache=true
*/ */
public BrokerId[] getBrokerPath() { public BrokerId[] getBrokerPath() {
return brokerPath; return brokerPath;
} }
public void setBrokerPath(BrokerId[] brokerPath) { public void setBrokerPath(BrokerId[] brokerPath) {
this.brokerPath = brokerPath; this.brokerPath = brokerPath;
} }
public Response visit(CommandVisitor visitor) throws Exception { public Response visit(CommandVisitor visitor) throws Exception {
return visitor.processAddProducer( this ); return visitor.processAddProducer(this);
} }
/** /**
* If the broker should dispatch messages from this producer async. Since sync * If the broker should dispatch messages from this producer async. Since
* dispatch could potentally block the producer thread, this could be an important * sync dispatch could potentally block the producer thread, this could be
* setting for the producer. * an important setting for the producer.
* *
* @openwire:property version=2 * @openwire:property version=2
*/ */
public boolean isDispatchAsync() { public boolean isDispatchAsync() {
return dispatchAsync; return dispatchAsync;
} }
public void setDispatchAsync(boolean dispatchAsync) { public void setDispatchAsync(boolean dispatchAsync) {
this.dispatchAsync = dispatchAsync; this.dispatchAsync = dispatchAsync;
} }
/** /**
* Used to configure the producer window size. A producer will * Used to configure the producer window size. A producer will send up to
* send up to the configured window size worth of payload data to * the configured window size worth of payload data to the broker before
* the broker before waiting for an Ack that allows him to send more. * waiting for an Ack that allows him to send more.
* *
* @openwire:property version=3 * @openwire:property version=3
*/ */
public int getWindowSize() { public int getWindowSize() {
return windowSize; return windowSize;
} }
public void setWindowSize(int windowSize) { public void setWindowSize(int windowSize) {
this.windowSize = windowSize; this.windowSize = windowSize;
} }
} }

View File

@ -22,26 +22,27 @@ import org.apache.activemq.state.CommandVisitor;
/** /**
* Removes a consumer, producer, session or connection. * Removes a consumer, producer, session or connection.
* *
* @openwire:marshaller code="12" * @openwire:marshaller code="12"
* @version $Revision$ * @version $Revision$
*/ */
public class RemoveInfo extends BaseCommand { public class RemoveInfo extends BaseCommand {
public static final byte DATA_STRUCTURE_TYPE=CommandTypes.REMOVE_INFO; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.REMOVE_INFO;
protected DataStructure objectId; protected DataStructure objectId;
public byte getDataStructureType() { public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE; return DATA_STRUCTURE_TYPE;
} }
public RemoveInfo() { public RemoveInfo() {
} }
public RemoveInfo(DataStructure objectId) { public RemoveInfo(DataStructure objectId) {
this.objectId=objectId; this.objectId = objectId;
} }
/** /**
* @openwire:property version=1 cache=true * @openwire:property version=1 cache=true
*/ */
@ -56,32 +57,32 @@ public class RemoveInfo extends BaseCommand {
public Response visit(CommandVisitor visitor) throws Exception { public Response visit(CommandVisitor visitor) throws Exception {
switch (objectId.getDataStructureType()) { switch (objectId.getDataStructureType()) {
case ConnectionId.DATA_STRUCTURE_TYPE: case ConnectionId.DATA_STRUCTURE_TYPE:
return visitor.processRemoveConnection((ConnectionId) objectId); return visitor.processRemoveConnection((ConnectionId)objectId);
case SessionId.DATA_STRUCTURE_TYPE: case SessionId.DATA_STRUCTURE_TYPE:
return visitor.processRemoveSession((SessionId) objectId); return visitor.processRemoveSession((SessionId)objectId);
case ConsumerId.DATA_STRUCTURE_TYPE: case ConsumerId.DATA_STRUCTURE_TYPE:
return visitor.processRemoveConsumer((ConsumerId) objectId); return visitor.processRemoveConsumer((ConsumerId)objectId);
case ProducerId.DATA_STRUCTURE_TYPE: case ProducerId.DATA_STRUCTURE_TYPE:
return visitor.processRemoveProducer((ProducerId) objectId); return visitor.processRemoveProducer((ProducerId)objectId);
default: default:
throw new IOException("Unknown remove command type: "+ objectId.getDataStructureType()); throw new IOException("Unknown remove command type: " + objectId.getDataStructureType());
} }
} }
/** /**
* Returns true if this event is for a removed connection * Returns true if this event is for a removed connection
*/ */
public boolean isConnectionRemove() { public boolean isConnectionRemove() {
return objectId.getDataStructureType() == ConnectionId.DATA_STRUCTURE_TYPE; return objectId.getDataStructureType() == ConnectionId.DATA_STRUCTURE_TYPE;
} }
/** /**
* Returns true if this event is for a removed session * Returns true if this event is for a removed session
*/ */
public boolean isSessionRemove() { public boolean isSessionRemove() {
return objectId.getDataStructureType() == SessionId.DATA_STRUCTURE_TYPE; return objectId.getDataStructureType() == SessionId.DATA_STRUCTURE_TYPE;
} }
/** /**
* Returns true if this event is for a removed consumer * Returns true if this event is for a removed consumer
*/ */

View File

@ -21,62 +21,61 @@ package org.apache.activemq.command;
* @openwire:marshaller code="121" * @openwire:marshaller code="121"
* @version $Revision$ * @version $Revision$
*/ */
public class SessionId implements DataStructure { public class SessionId implements DataStructure {
public static final byte DATA_STRUCTURE_TYPE=CommandTypes.SESSION_ID; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.SESSION_ID;
protected String connectionId; protected String connectionId;
protected long value; protected long value;
protected transient int hashCode; protected transient int hashCode;
protected transient String key; protected transient String key;
protected transient ConnectionId parentId; protected transient ConnectionId parentId;
public SessionId() { public SessionId() {
} }
public SessionId(ConnectionId connectionId, long sessionId) { public SessionId(ConnectionId connectionId, long sessionId) {
this.connectionId = connectionId.getValue(); this.connectionId = connectionId.getValue();
this.value=sessionId; this.value = sessionId;
} }
public SessionId(SessionId id) { public SessionId(SessionId id) {
this.connectionId = id.getConnectionId(); this.connectionId = id.getConnectionId();
this.value=id.getValue(); this.value = id.getValue();
} }
public SessionId(ProducerId id) { public SessionId(ProducerId id) {
this.connectionId = id.getConnectionId(); this.connectionId = id.getConnectionId();
this.value=id.getSessionId(); this.value = id.getSessionId();
} }
public SessionId(ConsumerId id) { public SessionId(ConsumerId id) {
this.connectionId = id.getConnectionId(); this.connectionId = id.getConnectionId();
this.value=id.getSessionId(); this.value = id.getSessionId();
} }
public ConnectionId getParentId() { public ConnectionId getParentId() {
if( parentId == null ) { if (parentId == null) {
parentId = new ConnectionId(this); parentId = new ConnectionId(this);
} }
return parentId; return parentId;
} }
public int hashCode() { public int hashCode() {
if( hashCode == 0 ) { if (hashCode == 0) {
hashCode = connectionId.hashCode() ^ (int)value; hashCode = connectionId.hashCode() ^ (int)value;
} }
return hashCode; return hashCode;
} }
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 return value == id.value && connectionId.equals(id.connectionId);
&& connectionId.equals(id.connectionId);
} }
public byte getDataStructureType() { public byte getDataStructureType() {
@ -88,7 +87,8 @@ public class SessionId implements DataStructure {
*/ */
public String getConnectionId() { public String getConnectionId() {
return connectionId; return connectionId;
} }
public void setConnectionId(String connectionId) { public void setConnectionId(String connectionId) {
this.connectionId = connectionId; this.connectionId = connectionId;
} }
@ -99,13 +99,14 @@ public class SessionId implements DataStructure {
public long getValue() { public long getValue() {
return value; return value;
} }
public void setValue(long sessionId) { public void setValue(long sessionId) {
this.value = sessionId; this.value = sessionId;
} }
public String toString() { public String toString() {
if( key==null ) { if (key == null) {
key = connectionId+":"+value; key = connectionId + ":" + value;
} }
return key; return key;
} }

View File

@ -25,22 +25,22 @@ import org.apache.activemq.state.CommandVisitor;
*/ */
public class SessionInfo extends BaseCommand { public class SessionInfo extends BaseCommand {
public static final byte DATA_STRUCTURE_TYPE=CommandTypes.SESSION_INFO; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.SESSION_INFO;
protected SessionId sessionId; protected SessionId sessionId;
public SessionInfo() { public SessionInfo() {
sessionId = new SessionId(); sessionId = new SessionId();
} }
public SessionInfo(ConnectionInfo connectionInfo, long sessionId) { public SessionInfo(ConnectionInfo connectionInfo, long sessionId) {
this.sessionId = new SessionId(connectionInfo.getConnectionId(), sessionId); this.sessionId = new SessionId(connectionInfo.getConnectionId(), sessionId);
} }
public SessionInfo(SessionId sessionId) { public SessionInfo(SessionId sessionId) {
this.sessionId = sessionId; this.sessionId = sessionId;
} }
public byte getDataStructureType() { public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE; return DATA_STRUCTURE_TYPE;
} }
@ -50,11 +50,12 @@ public class SessionInfo extends BaseCommand {
*/ */
public SessionId getSessionId() { public SessionId getSessionId() {
return sessionId; return sessionId;
} }
public void setSessionId(SessionId sessionId) { public void setSessionId(SessionId sessionId) {
this.sessionId = sessionId; this.sessionId = sessionId;
} }
public RemoveInfo createRemoveCommand() { public RemoveInfo createRemoveCommand() {
RemoveInfo command = new RemoveInfo(getSessionId()); RemoveInfo command = new RemoveInfo(getSessionId());
command.setResponseRequired(isResponseRequired()); command.setResponseRequired(isResponseRequired());
@ -62,7 +63,7 @@ public class SessionInfo extends BaseCommand {
} }
public Response visit(CommandVisitor visitor) throws Exception { public Response visit(CommandVisitor visitor) throws Exception {
return visitor.processAddSession( this); return visitor.processAddSession(this);
} }
} }

View File

@ -25,19 +25,18 @@ import org.apache.activemq.state.CommandVisitor;
*/ */
public class ShutdownInfo extends BaseCommand { public class ShutdownInfo extends BaseCommand {
public static final byte DATA_STRUCTURE_TYPE=CommandTypes.SHUTDOWN_INFO; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.SHUTDOWN_INFO;
public byte getDataStructureType() { public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE; return DATA_STRUCTURE_TYPE;
} }
public Response visit(CommandVisitor visitor) throws Exception { public Response visit(CommandVisitor visitor) throws Exception {
return visitor.processShutdown( this ); return visitor.processShutdown(this);
} }
public boolean isShutdownInfo(){ public boolean isShutdownInfo() {
return true; return true;
} }
} }

View File

@ -18,7 +18,6 @@ package org.apache.activemq.command;
import org.apache.activemq.util.IntrospectionSupport; import org.apache.activemq.util.IntrospectionSupport;
/** /**
* Used to represent a durable subscription. * Used to represent a durable subscription.
* *
@ -27,14 +26,14 @@ import org.apache.activemq.util.IntrospectionSupport;
*/ */
public class SubscriptionInfo implements DataStructure { public class SubscriptionInfo implements DataStructure {
public static final byte DATA_STRUCTURE_TYPE=CommandTypes.DURABLE_SUBSCRIPTION_INFO; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.DURABLE_SUBSCRIPTION_INFO;
protected ActiveMQDestination subscribedDestination; protected ActiveMQDestination subscribedDestination;
protected ActiveMQDestination destination; protected ActiveMQDestination destination;
protected String clientId; protected String clientId;
protected String subscriptionName; protected String subscriptionName;
protected String selector; protected String selector;
public byte getDataStructureType() { public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE; return DATA_STRUCTURE_TYPE;
} }
@ -51,8 +50,8 @@ public class SubscriptionInfo implements DataStructure {
} }
/** /**
* This is the a resolved destination that the subscription is receiving messages from. * This is the a resolved destination that the subscription is receiving
* This will never be a pattern or a composite destination. * messages from. This will never be a pattern or a composite destination.
* *
* @openwire:property version=1 cache=true * @openwire:property version=1 cache=true
*/ */
@ -84,13 +83,13 @@ public class SubscriptionInfo implements DataStructure {
} }
/** /**
* @param subscriptionName * @param subscriptionName *
* * @deprecated * @deprecated
*/ */
public void setSubcriptionName(String subscriptionName) { public void setSubcriptionName(String subscriptionName) {
this.subscriptionName = subscriptionName; this.subscriptionName = subscriptionName;
} }
public String getSubscriptionName() { public String getSubscriptionName() {
return subscriptionName; return subscriptionName;
} }
@ -102,46 +101,51 @@ public class SubscriptionInfo implements DataStructure {
public boolean isMarshallAware() { public boolean isMarshallAware() {
return false; return false;
} }
public String toString() { public String toString() {
return IntrospectionSupport.toString(this); return IntrospectionSupport.toString(this);
} }
public int hashCode() { public int hashCode() {
int h1 = clientId != null ? clientId.hashCode():-1; int h1 = clientId != null ? clientId.hashCode() : -1;
int h2 = subscriptionName != null ? subscriptionName.hashCode():-1; int h2 = subscriptionName != null ? subscriptionName.hashCode() : -1;
return h1 ^ h2; return h1 ^ h2;
} }
public boolean equals(Object obj){ public boolean equals(Object obj) {
boolean result=false; boolean result = false;
if(obj instanceof SubscriptionInfo){ if (obj instanceof SubscriptionInfo) {
SubscriptionInfo other=(SubscriptionInfo)obj; SubscriptionInfo other = (SubscriptionInfo)obj;
result=(clientId==null&&other.clientId==null||clientId!=null&&other.clientId!=null result = (clientId == null && other.clientId == null || clientId != null
&&clientId.equals(other.clientId)) && other.clientId != null
&&(subscriptionName==null&&other.subscriptionName==null||subscriptionName!=null && clientId.equals(other.clientId))
&&other.subscriptionName!=null&&subscriptionName.equals(other.subscriptionName)); && (subscriptionName == null && other.subscriptionName == null || subscriptionName != null
&& other.subscriptionName != null
&& subscriptionName
.equals(other.subscriptionName));
} }
return result; return result;
} }
/** /**
* The destination the client originally subscribed to.. This may not match the {@see getDestination} method * The destination the client originally subscribed to.. This may not match
* if the subscribed destination uses patterns or composites. * the {@see getDestination} method if the subscribed destination uses
* * patterns or composites.
* If the subscribed destinationis not set, this just ruturns the desitination. *
* * If the subscribed destinationis not set, this just ruturns the
* desitination.
*
* @openwire:property version=3 * @openwire:property version=3
*/ */
public ActiveMQDestination getSubscribedDestination() { public ActiveMQDestination getSubscribedDestination() {
if( subscribedDestination == null ) { if (subscribedDestination == null) {
return getDestination(); return getDestination();
} }
return subscribedDestination; return subscribedDestination;
} }
public void setSubscribedDestination(ActiveMQDestination subscribedDestination) { public void setSubscribedDestination(ActiveMQDestination subscribedDestination) {
this.subscribedDestination = subscribedDestination; this.subscribedDestination = subscribedDestination;
} }
} }

View File

@ -27,29 +27,28 @@ import org.apache.activemq.state.CommandVisitor;
*/ */
public class TransactionInfo extends BaseCommand { public class TransactionInfo extends BaseCommand {
public static final byte DATA_STRUCTURE_TYPE=CommandTypes.TRANSACTION_INFO; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.TRANSACTION_INFO;
public static final byte BEGIN = 0; public static final byte BEGIN = 0;
public static final byte PREPARE=1; public static final byte PREPARE = 1;
public static final byte COMMIT_ONE_PHASE=2; public static final byte COMMIT_ONE_PHASE = 2;
public static final byte COMMIT_TWO_PHASE=3; public static final byte COMMIT_TWO_PHASE = 3;
public static final byte ROLLBACK=4; public static final byte ROLLBACK = 4;
public static final byte RECOVER=5; public static final byte RECOVER = 5;
public static final byte FORGET=6; public static final byte FORGET = 6;
public static final byte END=7; public static final byte END = 7;
protected byte type; protected byte type;
protected ConnectionId connectionId; protected ConnectionId connectionId;
protected TransactionId transactionId; protected TransactionId transactionId;
public TransactionInfo() { public TransactionInfo() {
} }
public TransactionInfo(ConnectionId connectionId, TransactionId transactionId, byte type) { public TransactionInfo(ConnectionId connectionId, TransactionId transactionId, byte type) {
this.connectionId=connectionId; this.connectionId = connectionId;
this.transactionId=transactionId; this.transactionId = transactionId;
this.type=type; this.type = type;
} }
public byte getDataStructureType() { public byte getDataStructureType() {
@ -58,20 +57,22 @@ public class TransactionInfo extends BaseCommand {
/** /**
* @openwire:property version=1 cache=true * @openwire:property version=1 cache=true
*/ */
public ConnectionId getConnectionId() { public ConnectionId getConnectionId() {
return connectionId; return connectionId;
} }
public void setConnectionId(ConnectionId connectionId) { public void setConnectionId(ConnectionId connectionId) {
this.connectionId = connectionId; this.connectionId = connectionId;
} }
/** /**
* @openwire:property version=1 cache=true * @openwire:property version=1 cache=true
*/ */
public TransactionId getTransactionId() { public TransactionId getTransactionId() {
return transactionId; return transactionId;
} }
public void setTransactionId(TransactionId transactionId) { public void setTransactionId(TransactionId transactionId) {
this.transactionId = transactionId; this.transactionId = transactionId;
} }
@ -81,13 +82,14 @@ public class TransactionInfo extends BaseCommand {
*/ */
public byte getType() { public byte getType() {
return type; return type;
} }
public void setType(byte type) { public void setType(byte type) {
this.type = type; this.type = type;
} }
public Response visit(CommandVisitor visitor) throws Exception { public Response visit(CommandVisitor visitor) throws Exception {
switch( type ) { switch (type) {
case TransactionInfo.BEGIN: case TransactionInfo.BEGIN:
return visitor.processBeginTransaction(this); return visitor.processBeginTransaction(this);
case TransactionInfo.END: case TransactionInfo.END:
@ -105,7 +107,7 @@ public class TransactionInfo extends BaseCommand {
case TransactionInfo.FORGET: case TransactionInfo.FORGET:
return visitor.processForgetTransaction(this); return visitor.processForgetTransaction(this);
default: default:
throw new IOException("Transaction info type unknown: "+type); throw new IOException("Transaction info type unknown: " + type);
} }
} }

View File

@ -38,14 +38,14 @@ import org.apache.activemq.wireformat.WireFormat;
*/ */
public class WireFormatInfo implements Command, MarshallAware { public class WireFormatInfo implements Command, MarshallAware {
private static final int MAX_PROPERTY_SIZE = 1024*4; 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;
static final private byte MAGIC[] = new byte[] { 'A', 'c', 't', 'i', 'v', 'e', 'M', 'Q' }; static final private 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 properties;
private transient Endpoint from; private transient Endpoint from;
private transient Endpoint to; private transient Endpoint to;
@ -68,6 +68,7 @@ public class WireFormatInfo implements Command, MarshallAware {
public byte[] getMagic() { public byte[] getMagic() {
return magic; return magic;
} }
public void setMagic(byte[] magic) { public void setMagic(byte[] magic) {
this.magic = magic; this.magic = magic;
} }
@ -78,16 +79,18 @@ public class WireFormatInfo implements Command, MarshallAware {
public int getVersion() { public int getVersion() {
return version; return version;
} }
public void setVersion(int version) { public void setVersion(int version) {
this.version = version; this.version = version;
} }
/** /**
* @openwire:property version=1 * @openwire:property version=1
*/ */
public ByteSequence getMarshalledProperties() { public ByteSequence getMarshalledProperties() {
return marshalledProperties; return marshalledProperties;
} }
public void setMarshalledProperties(ByteSequence marshalledProperties) { public void setMarshalledProperties(ByteSequence marshalledProperties) {
this.marshalledProperties = marshalledProperties; this.marshalledProperties = marshalledProperties;
} }
@ -104,7 +107,8 @@ public class WireFormatInfo implements Command, MarshallAware {
} }
/** /**
* 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.
*/ */
public Endpoint getTo() { public Endpoint getTo() {
return to; return to;
@ -113,34 +117,34 @@ public class WireFormatInfo implements Command, MarshallAware {
public void setTo(Endpoint to) { public void setTo(Endpoint to) {
this.to = to; this.to = to;
} }
////////////////////// // ////////////////////
// //
// Implementation Methods. // Implementation Methods.
// //
////////////////////// // ////////////////////
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 { public Map 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);
} }
public void clearProperties() { public void clearProperties() {
marshalledProperties = null; marshalledProperties = null;
properties=null; properties = null;
} }
public void setProperty(String name, Object value) throws IOException { public void setProperty(String name, Object value) throws IOException {
@ -149,8 +153,8 @@ 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();
} else { } else {
properties = unmarsallProperties(marshalledProperties); properties = unmarsallProperties(marshalledProperties);
@ -158,14 +162,16 @@ public class WireFormatInfo implements Command, MarshallAware {
} }
} }
} }
private Map unmarsallProperties(ByteSequence marshalledProperties) throws IOException { private Map unmarsallProperties(ByteSequence marshalledProperties) throws IOException {
return MarshallingSupport.unmarshalPrimitiveMap(new DataInputStream(new ByteArrayInputStream(marshalledProperties)), MAX_PROPERTY_SIZE); return MarshallingSupport
.unmarshalPrimitiveMap(new DataInputStream(new ByteArrayInputStream(marshalledProperties)),
MAX_PROPERTY_SIZE);
} }
public void beforeMarshall(WireFormat wireFormat) throws IOException { public void beforeMarshall(WireFormat wireFormat) throws IOException {
// Need to marshal the properties. // Need to marshal the properties.
if( marshalledProperties==null && properties!=null ) { if (marshalledProperties == null && properties != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream os = new DataOutputStream(baos); DataOutputStream os = new DataOutputStream(baos);
MarshallingSupport.marshalPrimitiveMap(properties, os); MarshallingSupport.marshalPrimitiveMap(properties, os);
@ -183,7 +189,6 @@ public class WireFormatInfo implements Command, MarshallAware {
public void afterUnmarshall(WireFormat wireFormat) throws IOException { public void afterUnmarshall(WireFormat wireFormat) throws IOException {
} }
public boolean isValid() { public boolean isValid() {
return magic != null && Arrays.equals(magic, MAGIC); return magic != null && Arrays.equals(magic, MAGIC);
} }
@ -192,141 +197,159 @@ public class WireFormatInfo implements Command, MarshallAware {
} }
/** /**
* @throws IOException * @throws IOException
*/ */
public boolean isCacheEnabled() throws IOException { public boolean isCacheEnabled() throws IOException {
return Boolean.TRUE == getProperty("CacheEnabled"); return Boolean.TRUE == getProperty("CacheEnabled");
} }
public void setCacheEnabled(boolean cacheEnabled) throws IOException { public void setCacheEnabled(boolean cacheEnabled) throws IOException {
setProperty("CacheEnabled", cacheEnabled ? Boolean.TRUE : Boolean.FALSE); setProperty("CacheEnabled", cacheEnabled ? Boolean.TRUE : Boolean.FALSE);
} }
/** /**
* @throws IOException * @throws IOException
*/ */
public boolean isStackTraceEnabled() throws IOException { public boolean isStackTraceEnabled() throws IOException {
return Boolean.TRUE == getProperty("StackTraceEnabled"); return Boolean.TRUE == getProperty("StackTraceEnabled");
} }
public void setStackTraceEnabled(boolean stackTraceEnabled) throws IOException { public void setStackTraceEnabled(boolean stackTraceEnabled) throws IOException {
setProperty("StackTraceEnabled", stackTraceEnabled ? Boolean.TRUE : Boolean.FALSE); setProperty("StackTraceEnabled", stackTraceEnabled ? Boolean.TRUE : Boolean.FALSE);
} }
/** /**
* @throws IOException * @throws IOException
*/ */
public boolean isTcpNoDelayEnabled() throws IOException { public boolean isTcpNoDelayEnabled() throws IOException {
return Boolean.TRUE == getProperty("TcpNoDelayEnabled"); return Boolean.TRUE == getProperty("TcpNoDelayEnabled");
} }
public void setTcpNoDelayEnabled(boolean tcpNoDelayEnabled) throws IOException { public void setTcpNoDelayEnabled(boolean tcpNoDelayEnabled) throws IOException {
setProperty("TcpNoDelayEnabled", tcpNoDelayEnabled ? Boolean.TRUE : Boolean.FALSE); setProperty("TcpNoDelayEnabled", tcpNoDelayEnabled ? Boolean.TRUE : Boolean.FALSE);
} }
/** /**
* @throws IOException * @throws IOException
*/ */
public boolean isSizePrefixDisabled() throws IOException { public boolean isSizePrefixDisabled() throws IOException {
return Boolean.TRUE == getProperty("SizePrefixDisabled"); return Boolean.TRUE == getProperty("SizePrefixDisabled");
} }
public void setSizePrefixDisabled(boolean prefixPacketSize) throws IOException { public void setSizePrefixDisabled(boolean prefixPacketSize) throws IOException {
setProperty("SizePrefixDisabled", prefixPacketSize ? Boolean.TRUE : Boolean.FALSE); setProperty("SizePrefixDisabled", prefixPacketSize ? Boolean.TRUE : Boolean.FALSE);
} }
/** /**
* @throws IOException * @throws IOException
*/ */
public boolean isTightEncodingEnabled() throws IOException { public boolean isTightEncodingEnabled() throws IOException {
return Boolean.TRUE == getProperty("TightEncodingEnabled"); return Boolean.TRUE == getProperty("TightEncodingEnabled");
} }
public void setTightEncodingEnabled(boolean tightEncodingEnabled) throws IOException { public void setTightEncodingEnabled(boolean tightEncodingEnabled) throws IOException {
setProperty("TightEncodingEnabled", tightEncodingEnabled ? Boolean.TRUE : Boolean.FALSE); setProperty("TightEncodingEnabled", tightEncodingEnabled ? Boolean.TRUE : Boolean.FALSE);
} }
/** /**
* @throws IOException * @throws IOException
*/ */
public long getMaxInactivityDuration() throws IOException { public long getMaxInactivityDuration() throws IOException {
Long l = (Long) getProperty("MaxInactivityDuration"); Long l = (Long)getProperty("MaxInactivityDuration");
return l == null ? 0 : l.longValue(); return l == null ? 0 : l.longValue();
} }
public void seMaxInactivityDuration(long maxInactivityDuration) throws IOException { public void seMaxInactivityDuration(long maxInactivityDuration) throws IOException {
setProperty("MaxInactivityDuration", new Long(maxInactivityDuration)); setProperty("MaxInactivityDuration", new Long(maxInactivityDuration));
} }
/** /**
* @throws IOException * @throws IOException
*/ */
public int getCacheSize() throws IOException { public int getCacheSize() throws IOException {
Integer i = (Integer) getProperty("CacheSize"); Integer i = (Integer)getProperty("CacheSize");
return i == null ? 0 : i.intValue(); return i == null ? 0 : i.intValue();
} }
public void setCacheSize(int cacheSize) throws IOException { public void setCacheSize(int cacheSize) throws IOException {
setProperty("CacheSize", new Integer(cacheSize)); setProperty("CacheSize", new Integer(cacheSize));
} }
public Response visit(CommandVisitor visitor) throws Exception { public Response visit(CommandVisitor visitor) throws Exception {
return visitor.processWireFormat(this); return visitor.processWireFormat(this);
} }
public String toString() { public String toString() {
Map p=null; Map p = null;
try { try {
p = getProperties(); p = getProperties();
} catch (IOException e) { } catch (IOException e) {
} }
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) {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
sb.append('['); sb.append('[');
for (int i = 0; i < data.length; i++) { for (int i = 0; i < data.length; i++) {
if( i != 0 ) { if (i != 0) {
sb.append(','); sb.append(',');
} }
sb.append((char)data[i]); sb.append((char)data[i]);
} }
sb.append(']'); sb.append(']');
return sb.toString(); return sb.toString();
} }
/////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////
// //
// This are not implemented. // This are not implemented.
// //
/////////////////////////////////////////////////////////////// // /////////////////////////////////////////////////////////////
public void setCommandId(int value) { public void setCommandId(int value) {
} }
public int getCommandId() { public int getCommandId() {
return 0; return 0;
} }
public boolean isResponseRequired() { public boolean isResponseRequired() {
return false; return false;
} }
public boolean isResponse() { public boolean isResponse() {
return false; return false;
} }
public boolean isBrokerInfo() { public boolean isBrokerInfo() {
return false; return false;
} }
public boolean isMessageDispatch() { public boolean isMessageDispatch() {
return false; return false;
} }
public boolean isMessage() { public boolean isMessage() {
return false; return false;
} }
public boolean isMessageAck() { public boolean isMessageAck() {
return false; return false;
} }
public boolean isMessageDispatchNotification(){
public boolean isMessageDispatchNotification() {
return false; return false;
} }
public boolean isShutdownInfo(){
public boolean isShutdownInfo() {
return false; return false;
} }
public void setCachedMarshalledForm(WireFormat wireFormat, ByteSequence data) { public void setCachedMarshalledForm(WireFormat wireFormat, ByteSequence data) {
} }
public ByteSequence getCachedMarshalledForm(WireFormat wireFormat) { public ByteSequence getCachedMarshalledForm(WireFormat wireFormat) {
return null; return null;
} }

View File

@ -20,39 +20,38 @@ import java.util.Arrays;
import javax.transaction.xa.Xid; import javax.transaction.xa.Xid;
import org.apache.activemq.util.HexSupport; import org.apache.activemq.util.HexSupport;
/** /**
* @openwire:marshaller code="112" * @openwire:marshaller code="112"
* @version $Revision: 1.6 $ * @version $Revision: 1.6 $
*/ */
public class XATransactionId extends TransactionId implements Xid, Comparable{ public class XATransactionId extends TransactionId implements Xid, Comparable {
public static final byte DATA_STRUCTURE_TYPE=CommandTypes.ACTIVEMQ_XA_TRANSACTION_ID; public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_XA_TRANSACTION_ID;
private int formatId; private int formatId;
private byte[] branchQualifier; private byte[] branchQualifier;
private byte[] globalTransactionId; private byte[] globalTransactionId;
private transient int hash; private transient int hash;
private transient String transactionKey; private transient String transactionKey;
public XATransactionId() { public XATransactionId() {
} }
public XATransactionId(Xid xid) { public XATransactionId(Xid xid) {
this.formatId = xid.getFormatId(); this.formatId = xid.getFormatId();
this.globalTransactionId = xid.getGlobalTransactionId(); this.globalTransactionId = xid.getGlobalTransactionId();
this.branchQualifier = xid.getBranchQualifier(); this.branchQualifier = xid.getBranchQualifier();
} }
public byte getDataStructureType() { public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE; return DATA_STRUCTURE_TYPE;
} }
public synchronized String getTransactionKey(){ public synchronized String getTransactionKey() {
if(transactionKey==null){ if (transactionKey == null) {
transactionKey="XID:"+formatId+":"+HexSupport.toHexFromBytes(globalTransactionId)+":" transactionKey = "XID:" + formatId + ":" + HexSupport.toHexFromBytes(globalTransactionId) + ":"
+HexSupport.toHexFromBytes(branchQualifier); + HexSupport.toHexFromBytes(branchQualifier);
} }
return transactionKey; return transactionKey;
} }
@ -60,7 +59,7 @@ public class XATransactionId extends TransactionId implements Xid, Comparable{
public String toString() { public String toString() {
return getTransactionKey(); return getTransactionKey();
} }
public boolean isXATransaction() { public boolean isXATransaction() {
return true; return true;
} }
@ -92,21 +91,21 @@ public class XATransactionId extends TransactionId implements Xid, Comparable{
public void setBranchQualifier(byte[] branchQualifier) { public void setBranchQualifier(byte[] branchQualifier) {
this.branchQualifier = branchQualifier; this.branchQualifier = branchQualifier;
this.hash=0; this.hash = 0;
} }
public void setFormatId(int formatId) { public void setFormatId(int formatId) {
this.formatId = formatId; this.formatId = formatId;
this.hash=0; this.hash = 0;
} }
public void setGlobalTransactionId(byte[] globalTransactionId) { public void setGlobalTransactionId(byte[] globalTransactionId) {
this.globalTransactionId = globalTransactionId; this.globalTransactionId = globalTransactionId;
this.hash=0; this.hash = 0;
} }
public int hashCode() { public int hashCode() {
if( hash==0 ) { if (hash == 0) {
hash = formatId; hash = formatId;
hash = hash(globalTransactionId, hash); hash = hash(globalTransactionId, hash);
hash = hash(branchQualifier, hash); hash = hash(branchQualifier, hash);
@ -123,20 +122,20 @@ public class XATransactionId extends TransactionId implements Xid, Comparable{
} }
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

@ -41,12 +41,11 @@ public abstract class ArithmeticExpression extends BinaryExpression {
return new ArithmeticExpression(left, right) { return new ArithmeticExpression(left, right) {
protected Object evaluate(Object lvalue, Object rvalue) { protected Object evaluate(Object lvalue, Object rvalue) {
if (lvalue instanceof String) { if (lvalue instanceof String) {
String text = (String) lvalue; String text = (String)lvalue;
String answer = text + rvalue; String answer = text + rvalue;
return answer; return answer;
} } else if (lvalue instanceof Number) {
else if (lvalue instanceof Number) { return plus((Number)lvalue, asNumber(rvalue));
return plus((Number) lvalue, asNumber(rvalue));
} }
throw new RuntimeException("Cannot call plus operation on: " + lvalue + " and: " + rvalue); throw new RuntimeException("Cannot call plus operation on: " + lvalue + " and: " + rvalue);
} }
@ -61,7 +60,7 @@ public abstract class ArithmeticExpression extends BinaryExpression {
return new ArithmeticExpression(left, right) { return new ArithmeticExpression(left, right) {
protected Object evaluate(Object lvalue, Object rvalue) { protected Object evaluate(Object lvalue, Object rvalue) {
if (lvalue instanceof Number) { if (lvalue instanceof Number) {
return minus((Number) lvalue, asNumber(rvalue)); return minus((Number)lvalue, asNumber(rvalue));
} }
throw new RuntimeException("Cannot call minus operation on: " + lvalue + " and: " + rvalue); throw new RuntimeException("Cannot call minus operation on: " + lvalue + " and: " + rvalue);
} }
@ -77,7 +76,7 @@ public abstract class ArithmeticExpression extends BinaryExpression {
protected Object evaluate(Object lvalue, Object rvalue) { protected Object evaluate(Object lvalue, Object rvalue) {
if (lvalue instanceof Number) { if (lvalue instanceof Number) {
return multiply((Number) lvalue, asNumber(rvalue)); return multiply((Number)lvalue, asNumber(rvalue));
} }
throw new RuntimeException("Cannot call multiply operation on: " + lvalue + " and: " + rvalue); throw new RuntimeException("Cannot call multiply operation on: " + lvalue + " and: " + rvalue);
} }
@ -93,7 +92,7 @@ public abstract class ArithmeticExpression extends BinaryExpression {
protected Object evaluate(Object lvalue, Object rvalue) { protected Object evaluate(Object lvalue, Object rvalue) {
if (lvalue instanceof Number) { if (lvalue instanceof Number) {
return divide((Number) lvalue, asNumber(rvalue)); return divide((Number)lvalue, asNumber(rvalue));
} }
throw new RuntimeException("Cannot call divide operation on: " + lvalue + " and: " + rvalue); throw new RuntimeException("Cannot call divide operation on: " + lvalue + " and: " + rvalue);
} }
@ -109,7 +108,7 @@ public abstract class ArithmeticExpression extends BinaryExpression {
protected Object evaluate(Object lvalue, Object rvalue) { protected Object evaluate(Object lvalue, Object rvalue) {
if (lvalue instanceof Number) { if (lvalue instanceof Number) {
return mod((Number) lvalue, asNumber(rvalue)); return mod((Number)lvalue, asNumber(rvalue));
} }
throw new RuntimeException("Cannot call mod operation on: " + lvalue + " and: " + rvalue); throw new RuntimeException("Cannot call mod operation on: " + lvalue + " and: " + rvalue);
} }
@ -122,34 +121,34 @@ public abstract class ArithmeticExpression extends BinaryExpression {
protected Number plus(Number left, Number right) { protected Number plus(Number left, Number right) {
switch (numberType(left, right)) { switch (numberType(left, right)) {
case INTEGER: case INTEGER:
return new Integer(left.intValue() + right.intValue()); return new Integer(left.intValue() + right.intValue());
case LONG: case LONG:
return new Long(left.longValue() + right.longValue()); return new Long(left.longValue() + right.longValue());
default: default:
return new Double(left.doubleValue() + right.doubleValue()); return new Double(left.doubleValue() + right.doubleValue());
} }
} }
protected Number minus(Number left, Number right) { protected Number minus(Number left, Number right) {
switch (numberType(left, right)) { switch (numberType(left, right)) {
case INTEGER: case INTEGER:
return new Integer(left.intValue() - right.intValue()); return new Integer(left.intValue() - right.intValue());
case LONG: case LONG:
return new Long(left.longValue() - right.longValue()); return new Long(left.longValue() - right.longValue());
default: default:
return new Double(left.doubleValue() - right.doubleValue()); return new Double(left.doubleValue() - right.doubleValue());
} }
} }
protected Number multiply(Number left, Number right) { protected Number multiply(Number left, Number right) {
switch (numberType(left, right)) { switch (numberType(left, right)) {
case INTEGER: case INTEGER:
return new Integer(left.intValue() * right.intValue()); return new Integer(left.intValue() * right.intValue());
case LONG: case LONG:
return new Long(left.longValue() * right.longValue()); return new Long(left.longValue() * right.longValue());
default: default:
return new Double(left.doubleValue() * right.doubleValue()); return new Double(left.doubleValue() * right.doubleValue());
} }
} }
@ -164,11 +163,9 @@ public abstract class ArithmeticExpression extends BinaryExpression {
private int numberType(Number left, Number right) { private int numberType(Number left, Number right) {
if (isDouble(left) || isDouble(right)) { if (isDouble(left) || isDouble(right)) {
return DOUBLE; return DOUBLE;
} } else if (left instanceof Long || right instanceof Long) {
else if (left instanceof Long || right instanceof Long) {
return LONG; return LONG;
} } else {
else {
return INTEGER; return INTEGER;
} }
} }
@ -179,9 +176,8 @@ public abstract class ArithmeticExpression extends BinaryExpression {
protected Number asNumber(Object value) { protected Number asNumber(Object value) {
if (value instanceof Number) { if (value instanceof Number) {
return (Number) value; return (Number)value;
} } else {
else {
throw new RuntimeException("Cannot convert value: " + value + " into a number"); throw new RuntimeException("Cannot convert value: " + value + " into a number");
} }
} }
@ -198,7 +194,6 @@ public abstract class ArithmeticExpression extends BinaryExpression {
return evaluate(lvalue, rvalue); return evaluate(lvalue, rvalue);
} }
/** /**
* @param lvalue * @param lvalue
* @param rvalue * @param rvalue

View File

@ -30,7 +30,8 @@ import javax.jms.JMSException;
public abstract class ComparisonExpression extends BinaryExpression implements BooleanExpression { public abstract class ComparisonExpression extends BinaryExpression implements BooleanExpression {
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, right)); return LogicExpression.createAND(createGreaterThanEqual(value, left), createLessThanEqual(value,
right));
} }
public static BooleanExpression createNotBetween(Expression value, Expression left, Expression right) { public static BooleanExpression createNotBetween(Expression value, Expression left, Expression right) {
@ -86,18 +87,14 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
char t = like.charAt(i); char t = like.charAt(i);
regexp.append("\\x"); regexp.append("\\x");
regexp.append(Integer.toHexString(0xFFFF & t)); regexp.append(Integer.toHexString(0xFFFF & t));
} } else if (c == '%') {
else if (c == '%') { regexp.append(".*?"); // Do a non-greedy match
regexp.append(".*?"); // Do a non-greedy match } else if (c == '_') {
} regexp.append("."); // match one
else if (c == '_') { } else if (REGEXP_CONTROL_CHARS.contains(new Character(c))) {
regexp.append("."); // match one
}
else if (REGEXP_CONTROL_CHARS.contains(new Character(c))) {
regexp.append("\\x"); regexp.append("\\x");
regexp.append(Integer.toHexString(0xFFFF & c)); regexp.append(Integer.toHexString(0xFFFF & c));
} } else {
else {
regexp.append(c); regexp.append(c);
} }
} }
@ -125,22 +122,25 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
} }
if (!(rv instanceof String)) { if (!(rv instanceof String)) {
return Boolean.FALSE; return Boolean.FALSE;
//throw new RuntimeException("LIKE can only operate on String identifiers. LIKE attemped on: '" + rv.getClass()); // throw new RuntimeException("LIKE can only operate on String
// identifiers. LIKE attemped on: '" + rv.getClass());
} }
return likePattern.matcher((String) rv).matches() ? Boolean.TRUE : Boolean.FALSE; return likePattern.matcher((String)rv).matches() ? Boolean.TRUE : Boolean.FALSE;
} }
public boolean matches(MessageEvaluationContext message) throws JMSException { public boolean matches(MessageEvaluationContext message) throws JMSException {
Object object = evaluate(message); Object object = evaluate(message);
return object!=null && object==Boolean.TRUE; return object != null && object == Boolean.TRUE;
} }
} }
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("The ESCAPE string litteral is invalid. It can only be one character. Litteral used: " + escape); throw new RuntimeException(
"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) {
@ -152,21 +152,21 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
public static BooleanExpression createNotLike(Expression left, String right, String escape) { public static BooleanExpression createNotLike(Expression left, String right, String escape) {
return UnaryExpression.createNOT(createLike(left, right, escape)); return UnaryExpression.createNOT(createLike(left, right, escape));
} }
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);
} }
@ -183,27 +183,27 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
} }
public static BooleanExpression createEqual(Expression left, Expression right) { public static BooleanExpression createEqual(Expression left, Expression right) {
checkEqualOperand(left); checkEqualOperand(left);
checkEqualOperand(right); checkEqualOperand(right);
checkEqualOperandCompatability(left, right); checkEqualOperandCompatability(left, right);
return doCreateEqual(left, right); return doCreateEqual(left, right);
} }
private static BooleanExpression doCreateEqual(Expression left, Expression right) { private static BooleanExpression doCreateEqual(Expression left, Expression right) {
return new ComparisonExpression(left, right) { return new ComparisonExpression(left, right) {
public Object evaluate(MessageEvaluationContext message) throws JMSException { public Object evaluate(MessageEvaluationContext message) throws JMSException {
Object lv = left.evaluate(message); Object lv = left.evaluate(message);
Object rv = right.evaluate(message); Object rv = right.evaluate(message);
// Iff one of the values is null // Iff one of the values is null
if (lv == null ^ rv == null) { if (lv == null ^ rv == null) {
return Boolean.FALSE; return Boolean.FALSE;
} }
if (lv == rv || lv.equals(rv)) { if (lv == rv || lv.equals(rv)) {
return Boolean.TRUE; return Boolean.TRUE;
} }
if( lv instanceof Comparable && rv instanceof Comparable ) { if (lv instanceof Comparable && rv instanceof Comparable) {
return compare((Comparable)lv, (Comparable)rv); return compare((Comparable)lv, (Comparable)rv);
} }
return Boolean.FALSE; return Boolean.FALSE;
@ -220,8 +220,8 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
} }
public static BooleanExpression createGreaterThan(final Expression left, final Expression right) { public static BooleanExpression createGreaterThan(final Expression left, final Expression right) {
checkLessThanOperand(left); checkLessThanOperand(left);
checkLessThanOperand(right); checkLessThanOperand(right);
return new ComparisonExpression(left, right) { return new ComparisonExpression(left, right) {
protected boolean asBoolean(int answer) { protected boolean asBoolean(int answer) {
return answer > 0; return answer > 0;
@ -234,8 +234,8 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
} }
public static BooleanExpression createGreaterThanEqual(final Expression left, final Expression right) { public static BooleanExpression createGreaterThanEqual(final Expression left, final Expression right) {
checkLessThanOperand(left); checkLessThanOperand(left);
checkLessThanOperand(right); checkLessThanOperand(right);
return new ComparisonExpression(left, right) { return new ComparisonExpression(left, right) {
protected boolean asBoolean(int answer) { protected boolean asBoolean(int answer) {
return answer >= 0; return answer >= 0;
@ -248,8 +248,8 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
} }
public static BooleanExpression createLessThan(final Expression left, final Expression right) { public static BooleanExpression createLessThan(final Expression left, final Expression right) {
checkLessThanOperand(left); checkLessThanOperand(left);
checkLessThanOperand(right); checkLessThanOperand(right);
return new ComparisonExpression(left, right) { return new ComparisonExpression(left, right) {
protected boolean asBoolean(int answer) { protected boolean asBoolean(int answer) {
@ -263,9 +263,9 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
}; };
} }
public static BooleanExpression createLessThanEqual(final Expression left, final Expression right) { public static BooleanExpression createLessThanEqual(final Expression left, final Expression right) {
checkLessThanOperand(left); checkLessThanOperand(left);
checkLessThanOperand(right); checkLessThanOperand(right);
return new ComparisonExpression(left, right) { return new ComparisonExpression(left, right) {
protected boolean asBoolean(int answer) { protected boolean asBoolean(int answer) {
@ -278,53 +278,51 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
}; };
} }
/** /**
* Only Numeric expressions can be used in >, >=, < or <= expressions.s * Only Numeric expressions can be used in >, >=, < or <= expressions.s
* *
* @param expr * @param expr
*/ */
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..
throw new RuntimeException("Value '"+expr+"' cannot be compared.");
}
if( expr instanceof BooleanExpression ) {
throw new RuntimeException("Value '"+expr+"' cannot be compared.");
}
}
/** // Else it's boolean or a String..
* Validates that the expression can be used in == or <> expression. throw new RuntimeException("Value '" + expr + "' cannot be compared.");
* Cannot not be NULL TRUE or FALSE litterals. }
if (expr instanceof BooleanExpression) {
throw new RuntimeException("Value '" + expr + "' cannot be compared.");
}
}
/**
* Validates that the expression can be used in == or <> expression. Cannot
* not be NULL TRUE or FALSE litterals.
* *
* @param expr * @param expr
*/ */
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 left
* @param right * @param right
@ -334,11 +332,11 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
} }
public Object evaluate(MessageEvaluationContext message) throws JMSException { public Object evaluate(MessageEvaluationContext message) throws JMSException {
Comparable lv = (Comparable) left.evaluate(message); Comparable lv = (Comparable)left.evaluate(message);
if (lv == null) { if (lv == null) {
return null; return null;
} }
Comparable rv = (Comparable) right.evaluate(message); Comparable rv = (Comparable)right.evaluate(message);
if (rv == null) { if (rv == null) {
return null; return null;
} }
@ -353,106 +351,81 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
if (lc != rc) { if (lc != rc) {
if (lc == Byte.class) { if (lc == Byte.class) {
if (rc == Short.class) { if (rc == Short.class) {
lv = Short.valueOf(((Number) lv).shortValue()); lv = Short.valueOf(((Number)lv).shortValue());
} } else if (rc == Integer.class) {
else if (rc == Integer.class) { lv = Integer.valueOf(((Number)lv).intValue());
lv = Integer.valueOf(((Number) lv).intValue()); } else if (rc == Long.class) {
} lv = Long.valueOf(((Number)lv).longValue());
else if (rc == Long.class) { } else if (rc == Float.class) {
lv = Long.valueOf(((Number) lv).longValue()); lv = new Float(((Number)lv).floatValue());
} } else if (rc == Double.class) {
else if (rc == Float.class) { lv = new Double(((Number)lv).doubleValue());
lv = new Float(((Number) lv).floatValue()); } else {
}
else if (rc == Double.class) {
lv = new Double(((Number) lv).doubleValue());
}
else {
return Boolean.FALSE; return Boolean.FALSE;
} }
} else if (lc == Short.class) { } else if (lc == Short.class) {
if (rc == Integer.class) { if (rc == Integer.class) {
lv = Integer.valueOf(((Number) lv).intValue()); lv = Integer.valueOf(((Number)lv).intValue());
} } else if (rc == Long.class) {
else if (rc == Long.class) { lv = Long.valueOf(((Number)lv).longValue());
lv = Long.valueOf(((Number) lv).longValue()); } else if (rc == Float.class) {
} lv = new Float(((Number)lv).floatValue());
else if (rc == Float.class) { } else if (rc == Double.class) {
lv = new Float(((Number) lv).floatValue()); lv = new Double(((Number)lv).doubleValue());
} } else {
else if (rc == Double.class) {
lv = new Double(((Number) lv).doubleValue());
}
else {
return Boolean.FALSE; return Boolean.FALSE;
} }
} else if (lc == Integer.class) { } else if (lc == Integer.class) {
if (rc == Long.class) { if (rc == Long.class) {
lv = Long.valueOf(((Number) lv).longValue()); lv = Long.valueOf(((Number)lv).longValue());
} } else if (rc == Float.class) {
else if (rc == Float.class) { lv = new Float(((Number)lv).floatValue());
lv = new Float(((Number) lv).floatValue()); } else if (rc == Double.class) {
} lv = new Double(((Number)lv).doubleValue());
else if (rc == Double.class) { } else {
lv = new Double(((Number) lv).doubleValue());
}
else {
return Boolean.FALSE; return Boolean.FALSE;
} }
} } else if (lc == Long.class) {
else if (lc == Long.class) {
if (rc == Integer.class) { if (rc == Integer.class) {
rv = Long.valueOf(((Number) rv).longValue()); rv = Long.valueOf(((Number)rv).longValue());
} } else if (rc == Float.class) {
else if (rc == Float.class) { lv = new Float(((Number)lv).floatValue());
lv = new Float(((Number) lv).floatValue()); } else if (rc == Double.class) {
} lv = new Double(((Number)lv).doubleValue());
else if (rc == Double.class) { } else {
lv = new Double(((Number) lv).doubleValue());
}
else {
return Boolean.FALSE; return Boolean.FALSE;
} }
} } else if (lc == Float.class) {
else if (lc == Float.class) {
if (rc == Integer.class) { if (rc == Integer.class) {
rv = new Float(((Number) rv).floatValue()); rv = new Float(((Number)rv).floatValue());
} } else if (rc == Long.class) {
else if (rc == Long.class) { rv = new Float(((Number)rv).floatValue());
rv = new Float(((Number) rv).floatValue()); } else if (rc == Double.class) {
} lv = new Double(((Number)lv).doubleValue());
else if (rc == Double.class) { } else {
lv = new Double(((Number) lv).doubleValue());
}
else {
return Boolean.FALSE; return Boolean.FALSE;
} }
} } else if (lc == Double.class) {
else if (lc == Double.class) {
if (rc == Integer.class) { if (rc == Integer.class) {
rv = new Double(((Number) rv).doubleValue()); rv = new Double(((Number)rv).doubleValue());
} } else if (rc == Long.class) {
else if (rc == Long.class) { rv = new Double(((Number)rv).doubleValue());
rv = new Double(((Number) rv).doubleValue()); } else if (rc == Float.class) {
} rv = new Float(((Number)rv).doubleValue());
else if (rc == Float.class) { } else {
rv = new Float(((Number) rv).doubleValue());
}
else {
return Boolean.FALSE; return Boolean.FALSE;
} }
} } else
else
return Boolean.FALSE; return Boolean.FALSE;
} }
return asBoolean(lv.compareTo(rv)) ? Boolean.TRUE : Boolean.FALSE; return asBoolean(lv.compareTo(rv)) ? Boolean.TRUE : Boolean.FALSE;
} }
protected abstract boolean asBoolean(int answer); protected abstract boolean asBoolean(int answer);
public boolean matches(MessageEvaluationContext message) throws JMSException { public boolean matches(MessageEvaluationContext message) throws JMSException {
Object object = evaluate(message); Object object = evaluate(message);
return object!=null && object==Boolean.TRUE; return object != null && object == Boolean.TRUE;
} }
} }

View File

@ -31,10 +31,11 @@ public class ConstantExpression implements Expression {
public BooleanConstantExpression(Object value) { public BooleanConstantExpression(Object value) {
super(value); super(value);
} }
public boolean matches(MessageEvaluationContext message) throws JMSException { public boolean matches(MessageEvaluationContext message) throws JMSException {
Object object = evaluate(message); Object object = evaluate(message);
return object!=null && object==Boolean.TRUE; return object != null && object == Boolean.TRUE;
} }
} }
public static final BooleanConstantExpression NULL = new BooleanConstantExpression(null); public static final BooleanConstantExpression NULL = new BooleanConstantExpression(null);
@ -44,19 +45,19 @@ public class ConstantExpression implements Expression {
private Object value; private Object value;
public static ConstantExpression createFromDecimal(String text) { public static ConstantExpression createFromDecimal(String text) {
// Strip off the 'l' or 'L' if needed.
if( text.endsWith("l") || text.endsWith("L") )
text = text.substring(0, text.length()-1);
Number value; // Strip off the 'l' or 'L' if needed.
try { if (text.endsWith("l") || text.endsWith("L"))
value = new Long(text); text = text.substring(0, text.length() - 1);
} catch ( NumberFormatException e) {
// The number may be too big to fit in a long. Number value;
value = new BigDecimal(text); try {
} value = new Long(text);
} catch (NumberFormatException e) {
// The number may be too big to fit in a long.
value = new BigDecimal(text);
}
long l = value.longValue(); long l = value.longValue();
if (Integer.MIN_VALUE <= l && l <= Integer.MAX_VALUE) { if (Integer.MIN_VALUE <= l && l <= Integer.MAX_VALUE) {
value = Integer.valueOf(value.intValue()); value = Integer.valueOf(value.intValue());
@ -97,7 +98,7 @@ public class ConstantExpression implements Expression {
public Object getValue() { public Object getValue() {
return value; return value;
} }
/** /**
* @see java.lang.Object#toString() * @see java.lang.Object#toString()
@ -107,17 +108,17 @@ public class ConstantExpression implements Expression {
return "NULL"; return "NULL";
} }
if (value instanceof Boolean) { if (value instanceof Boolean) {
return ((Boolean) value).booleanValue() ? "TRUE" : "FALSE"; return ((Boolean)value).booleanValue() ? "TRUE" : "FALSE";
} }
if (value instanceof String) { if (value instanceof String) {
return encodeString((String) value); return encodeString((String)value);
} }
return value.toString(); return value.toString();
} }
/** /**
* TODO: more efficient hashCode() * TODO: more efficient hashCode()
* *
* @see java.lang.Object#hashCode() * @see java.lang.Object#hashCode()
*/ */
public int hashCode() { public int hashCode() {
@ -126,7 +127,7 @@ public class ConstantExpression implements Expression {
/** /**
* TODO: more efficient hashCode() * TODO: more efficient hashCode()
* *
* @see java.lang.Object#equals(java.lang.Object) * @see java.lang.Object#equals(java.lang.Object)
*/ */
public boolean equals(Object o) { public boolean equals(Object o) {
@ -138,11 +139,10 @@ public class ConstantExpression implements Expression {
} }
/** /**
* Encodes the value of string so that it looks like it would look like * Encodes the value of string so that it looks like it would look like when
* when it was provided in a selector. * it was provided in a selector.
* *
* @param string * @param string
* @return * @return
*/ */
@ -159,5 +159,5 @@ public class ConstantExpression implements Expression {
b.append('\''); b.append('\'');
return b.toString(); return b.toString();
} }
} }

View File

@ -24,24 +24,23 @@ import javax.jms.JMSException;
import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.util.JMSExceptionSupport; import org.apache.activemq.util.JMSExceptionSupport;
/** /**
* Represents a filter which only operates on Destinations * Represents a filter which only operates on Destinations
* *
* @version $Revision: 1.3 $ * @version $Revision: 1.3 $
*/ */
public abstract class DestinationFilter implements BooleanExpression { public abstract class DestinationFilter implements BooleanExpression {
public static final String ANY_DESCENDENT = ">"; public static final String ANY_DESCENDENT = ">";
public static final String ANY_CHILD = "*"; public static final String ANY_CHILD = "*";
public Object evaluate(MessageEvaluationContext message) throws JMSException { public Object evaluate(MessageEvaluationContext message) throws JMSException {
return matches(message) ? Boolean.TRUE : Boolean.FALSE; return matches(message) ? Boolean.TRUE : Boolean.FALSE;
} }
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) {
@ -61,8 +60,7 @@ public abstract class DestinationFilter implements BooleanExpression {
String lastPath = paths[idx]; String lastPath = paths[idx];
if (lastPath.equals(ANY_DESCENDENT)) { if (lastPath.equals(ANY_DESCENDENT)) {
return new PrefixDestinationFilter(paths); return new PrefixDestinationFilter(paths);
} } else {
else {
while (idx >= 0) { while (idx >= 0) {
lastPath = paths[idx--]; lastPath = paths[idx--];
if (lastPath.equals(ANY_CHILD)) { if (lastPath.equals(ANY_CHILD)) {

View File

@ -39,15 +39,14 @@ public class DestinationMapNode implements DestinationNode {
private List values = new ArrayList(); private List values = new ArrayList();
private Map childNodes = new HashMap(); private Map childNodes = new HashMap();
private String path = "Root"; private String path = "Root";
// private DestinationMapNode anyChild; // private DestinationMapNode anyChild;
private int pathLength; private int pathLength;
public DestinationMapNode(DestinationMapNode parent) { public DestinationMapNode(DestinationMapNode parent) {
this.parent = parent; this.parent = parent;
if (parent == null) { if (parent == null) {
pathLength = 0; pathLength = 0;
} } else {
else {
pathLength = parent.pathLength + 1; pathLength = parent.pathLength + 1;
} }
} }
@ -57,7 +56,7 @@ public class DestinationMapNode implements DestinationNode {
* exist * exist
*/ */
public DestinationMapNode getChild(String path) { public DestinationMapNode getChild(String path) {
return (DestinationMapNode) childNodes.get(path); return (DestinationMapNode)childNodes.get(path);
} }
/** /**
@ -66,7 +65,7 @@ public class DestinationMapNode implements DestinationNode {
public Collection getChildren() { public Collection getChildren() {
return childNodes.values(); return childNodes.values();
} }
public int getChildCount() { public int getChildCount() {
return childNodes.size(); return childNodes.size();
} }
@ -76,7 +75,7 @@ public class DestinationMapNode implements DestinationNode {
* it does not yet exist * it does not yet exist
*/ */
public DestinationMapNode getChildOrCreate(String path) { public DestinationMapNode getChildOrCreate(String path) {
DestinationMapNode answer = (DestinationMapNode) childNodes.get(path); DestinationMapNode answer = (DestinationMapNode)childNodes.get(path);
if (answer == null) { if (answer == null) {
answer = createChildNode(); answer = createChildNode();
answer.path = path; answer.path = path;
@ -88,13 +87,12 @@ public class DestinationMapNode implements DestinationNode {
/** /**
* Returns the node which represents all children (i.e. the * node) * Returns the node which represents all children (i.e. the * node)
*/ */
// public DestinationMapNode getAnyChildNode() { // public DestinationMapNode getAnyChildNode() {
// if (anyChild == null) { // if (anyChild == null) {
// anyChild = createChildNode(); // anyChild = createChildNode();
// } // }
// return anyChild; // return anyChild;
// } // }
/** /**
* Returns a mutable List of the values available at this node in the tree * Returns a mutable List of the values available at this node in the tree
*/ */
@ -106,24 +104,23 @@ public class DestinationMapNode implements DestinationNode {
* Returns a mutable List of the values available at this node in the tree * Returns a mutable List of the values available at this node in the tree
*/ */
public List removeValues() { public List removeValues() {
ArrayList v = new ArrayList(values); ArrayList v = new ArrayList(values);
// parent.getAnyChildNode().getValues().removeAll(v); // parent.getAnyChildNode().getValues().removeAll(v);
values.clear(); values.clear();
pruneIfEmpty(); pruneIfEmpty();
return v; return v;
} }
public Set removeDesendentValues() { public Set removeDesendentValues() {
Set answer = new HashSet(); Set answer = new HashSet();
removeDesendentValues(answer); removeDesendentValues(answer);
return answer; return answer;
} }
protected void removeDesendentValues(Set answer) { protected void removeDesendentValues(Set answer) {
// if (anyChild != null) { // if (anyChild != null) {
// anyChild.removeDesendentValues(answer); // anyChild.removeDesendentValues(answer);
// } // }
answer.addAll(removeValues()); answer.addAll(removeValues());
} }
@ -139,14 +136,13 @@ public class DestinationMapNode implements DestinationNode {
public void add(String[] paths, int idx, Object value) { public void add(String[] paths, int idx, Object value) {
if (idx >= paths.length) { if (idx >= paths.length) {
values.add(value); values.add(value);
} } else {
else { // if (idx == paths.length - 1) {
// if (idx == paths.length - 1) { // getAnyChildNode().getValues().add(value);
// getAnyChildNode().getValues().add(value); // }
// } // else {
// else { // getAnyChildNode().add(paths, idx + 1, value);
// getAnyChildNode().add(paths, idx + 1, value); // }
// }
getChildOrCreate(paths[idx]).add(paths, idx + 1, value); getChildOrCreate(paths[idx]).add(paths, idx + 1, value);
} }
} }
@ -155,14 +151,13 @@ public class DestinationMapNode implements DestinationNode {
if (idx >= paths.length) { if (idx >= paths.length) {
values.remove(value); values.remove(value);
pruneIfEmpty(); pruneIfEmpty();
} } else {
else { // if (idx == paths.length - 1) {
// if (idx == paths.length - 1) { // getAnyChildNode().getValues().remove(value);
// getAnyChildNode().getValues().remove(value); // }
// } // else {
// else { // getAnyChildNode().remove(paths, idx + 1, value);
// getAnyChildNode().remove(paths, idx + 1, value); // }
// }
getChildOrCreate(paths[idx]).remove(paths, ++idx, value); getChildOrCreate(paths[idx]).remove(paths, ++idx, value);
} }
} }
@ -171,7 +166,7 @@ public class DestinationMapNode implements DestinationNode {
DestinationNode node = this; DestinationNode node = this;
for (int i = startIndex, size = paths.length; i < size && node != null; i++) { for (int i = startIndex, size = paths.length; i < size && node != null; i++) {
String path = paths[i]; String path = paths[i];
if (path.equals(ANY_DESCENDENT)) { if (path.equals(ANY_DESCENDENT)) {
answer.addAll(node.removeDesendentValues()); answer.addAll(node.removeDesendentValues());
break; break;
@ -179,19 +174,17 @@ public class DestinationMapNode implements DestinationNode {
node.appendMatchingWildcards(answer, paths, i); node.appendMatchingWildcards(answer, paths, i);
if (path.equals(ANY_CHILD)) { if (path.equals(ANY_CHILD)) {
//node = node.getAnyChildNode(); // node = node.getAnyChildNode();
node = new AnyChildDestinationNode(node); node = new AnyChildDestinationNode(node);
} } else {
else {
node = node.getChild(path); node = node.getChild(path);
} }
} }
if (node != null) { if (node != null) {
answer.addAll(node.removeValues()); answer.addAll(node.removeValues());
} }
} }
public void appendDescendantValues(Set answer) { public void appendDescendantValues(Set answer) {
@ -200,14 +193,14 @@ public class DestinationMapNode implements DestinationNode {
// lets add all the children too // lets add all the children too
Iterator iter = childNodes.values().iterator(); Iterator iter = childNodes.values().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
DestinationNode child = (DestinationNode) iter.next(); DestinationNode child = (DestinationNode)iter.next();
child.appendDescendantValues(answer); child.appendDescendantValues(answer);
} }
// TODO??? // TODO???
// if (anyChild != null) { // if (anyChild != null) {
// anyChild.appendDescendantValues(answer); // anyChild.appendDescendantValues(answer);
// } // }
} }
/** /**
@ -226,7 +219,7 @@ public class DestinationMapNode implements DestinationNode {
} }
DestinationMapNode wildCardNode = getChild(ANY_CHILD); DestinationMapNode wildCardNode = getChild(ANY_CHILD);
if (wildCardNode != null) { if (wildCardNode != null) {
wildCardNode.appendMatchingValues(answer, paths, idx+1); wildCardNode.appendMatchingValues(answer, paths, idx + 1);
} }
wildCardNode = getChild(ANY_DESCENDENT); wildCardNode = getChild(ANY_DESCENDENT);
if (wildCardNode != null) { if (wildCardNode != null) {
@ -247,11 +240,9 @@ public class DestinationMapNode implements DestinationNode {
node.appendMatchingWildcards(answer, paths, i); node.appendMatchingWildcards(answer, paths, i);
if (path.equals(ANY_CHILD)) { if (path.equals(ANY_CHILD)) {
node = new AnyChildDestinationNode(node); node = new AnyChildDestinationNode(node);
} } else {
else {
node = node.getChild(path); node = node.getChild(path);
} }
} }

View File

@ -29,7 +29,7 @@ import org.apache.activemq.command.TransactionId;
import org.apache.activemq.util.JMSExceptionSupport; import org.apache.activemq.util.JMSExceptionSupport;
/** /**
* Represents a property expression * Represents a property expression
* *
* @version $Revision: 1.5 $ * @version $Revision: 1.5 $
*/ */
@ -38,149 +38,151 @@ public class PropertyExpression implements Expression {
interface SubExpression { interface SubExpression {
public Object evaluate(Message message); public Object evaluate(Message message);
} }
static final private HashMap JMS_PROPERTY_EXPRESSIONS = new HashMap();
static{
JMS_PROPERTY_EXPRESSIONS.put("JMSDestination",new SubExpression(){
public Object evaluate(Message message){ static final private HashMap JMS_PROPERTY_EXPRESSIONS = new HashMap();
ActiveMQDestination dest=message.getOriginalDestination(); static {
if(dest==null) JMS_PROPERTY_EXPRESSIONS.put("JMSDestination", new SubExpression() {
dest=message.getDestination();
if(dest==null) public Object evaluate(Message message) {
ActiveMQDestination dest = message.getOriginalDestination();
if (dest == null)
dest = message.getDestination();
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();
} }
}); });
JMS_PROPERTY_EXPRESSIONS.put("JMSType",new SubExpression(){ JMS_PROPERTY_EXPRESSIONS.put("JMSType", new SubExpression() {
public Object evaluate(Message message){ public Object evaluate(Message message) {
return message.getType(); return message.getType();
} }
}); });
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()?DeliveryMode.PERSISTENT:DeliveryMode.NON_PERSISTENT); return Integer.valueOf(message.isPersistent()
? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
} }
}); });
JMS_PROPERTY_EXPRESSIONS.put("JMSPriority",new SubExpression(){ JMS_PROPERTY_EXPRESSIONS.put("JMSPriority", new SubExpression() {
public Object evaluate(Message message){ public Object evaluate(Message message) {
return Integer.valueOf(message.getPriority()); return Integer.valueOf(message.getPriority());
} }
}); });
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();
} }
}); });
JMS_PROPERTY_EXPRESSIONS.put("JMSTimestamp",new SubExpression(){ JMS_PROPERTY_EXPRESSIONS.put("JMSTimestamp", new SubExpression() {
public Object evaluate(Message message){ public Object evaluate(Message message) {
return Long.valueOf(message.getTimestamp()); return Long.valueOf(message.getTimestamp());
} }
}); });
JMS_PROPERTY_EXPRESSIONS.put("JMSCorrelationID",new SubExpression(){ JMS_PROPERTY_EXPRESSIONS.put("JMSCorrelationID", new SubExpression() {
public Object evaluate(Message message){ public Object evaluate(Message message) {
return message.getCorrelationId(); return message.getCorrelationId();
} }
}); });
JMS_PROPERTY_EXPRESSIONS.put("JMSExpiration",new SubExpression(){ JMS_PROPERTY_EXPRESSIONS.put("JMSExpiration", new SubExpression() {
public Object evaluate(Message message){ public Object evaluate(Message message) {
return Long.valueOf(message.getExpiration()); return Long.valueOf(message.getExpiration());
} }
}); });
JMS_PROPERTY_EXPRESSIONS.put("JMSRedelivered",new SubExpression(){ JMS_PROPERTY_EXPRESSIONS.put("JMSRedelivered", new SubExpression() {
public Object evaluate(Message message){ public Object evaluate(Message message) {
return Boolean.valueOf(message.isRedelivered()); return Boolean.valueOf(message.isRedelivered());
} }
}); });
JMS_PROPERTY_EXPRESSIONS.put("JMSXDeliveryCount",new SubExpression(){ JMS_PROPERTY_EXPRESSIONS.put("JMSXDeliveryCount", new SubExpression() {
public Object evaluate(Message message){ public Object evaluate(Message message) {
return Integer.valueOf(message.getRedeliveryCounter()+1); return Integer.valueOf(message.getRedeliveryCounter() + 1);
} }
}); });
JMS_PROPERTY_EXPRESSIONS.put("JMSXGroupID",new SubExpression(){ JMS_PROPERTY_EXPRESSIONS.put("JMSXGroupID", new SubExpression() {
public Object evaluate(Message message){ public Object evaluate(Message message) {
return message.getGroupID(); return message.getGroupID();
} }
}); });
JMS_PROPERTY_EXPRESSIONS.put("JMSXGroupSeq",new SubExpression(){ JMS_PROPERTY_EXPRESSIONS.put("JMSXGroupSeq", new SubExpression() {
public Object evaluate(Message message){ public Object evaluate(Message message) {
return new Integer(message.getGroupSequence()); return new Integer(message.getGroupSequence());
} }
}); });
JMS_PROPERTY_EXPRESSIONS.put("JMSXProducerTXID",new SubExpression(){ JMS_PROPERTY_EXPRESSIONS.put("JMSXProducerTXID", new SubExpression() {
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());
} }
}); });
JMS_PROPERTY_EXPRESSIONS.put("JMSActiveMQBrokerInTime",new SubExpression(){ JMS_PROPERTY_EXPRESSIONS.put("JMSActiveMQBrokerInTime", new SubExpression() {
public Object evaluate(Message message){ public Object evaluate(Message message) {
return Long.valueOf(message.getBrokerInTime()); return Long.valueOf(message.getBrokerInTime());
} }
}); });
JMS_PROPERTY_EXPRESSIONS.put("JMSActiveMQBrokerOutTime",new SubExpression(){ JMS_PROPERTY_EXPRESSIONS.put("JMSActiveMQBrokerOutTime", new SubExpression() {
public Object evaluate(Message message){ public Object evaluate(Message message) {
return Long.valueOf(message.getBrokerOutTime()); return Long.valueOf(message.getBrokerOutTime());
} }
}); });
} }
private final String name; private final String name;
private final SubExpression jmsPropertyExpression; private final SubExpression jmsPropertyExpression;
public PropertyExpression(String name) { public PropertyExpression(String name) {
this.name = name; this.name = name;
jmsPropertyExpression = (SubExpression) JMS_PROPERTY_EXPRESSIONS.get(name); jmsPropertyExpression = (SubExpression)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: "+ioe.getMessage(), ioe); throw JMSExceptionSupport.create("Could not get property: " + name + " reason: "
+ ioe.getMessage(), ioe);
} }
} catch (IOException e) { } catch (IOException e) {
throw JMSExceptionSupport.create(e); throw JMSExceptionSupport.create(e);
} }
} }
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);
@ -193,7 +195,6 @@ public class PropertyExpression implements Expression {
return name; return name;
} }
/** /**
* @see java.lang.Object#toString() * @see java.lang.Object#toString()
*/ */
@ -216,7 +217,7 @@ public class PropertyExpression implements Expression {
if (o == null || !this.getClass().equals(o.getClass())) { if (o == null || !this.getClass().equals(o.getClass())) {
return false; return false;
} }
return name.equals(((PropertyExpression) o).name); return name.equals(((PropertyExpression)o).name);
} }

View File

@ -42,7 +42,7 @@ public abstract class UnaryExpression implements Expression {
return null; return null;
} }
if (rvalue instanceof Number) { if (rvalue instanceof Number) {
return negate((Number) rvalue); return negate((Number)rvalue);
} }
return null; return null;
} }
@ -53,83 +53,83 @@ public abstract class UnaryExpression implements Expression {
}; };
} }
public static BooleanExpression createInExpression(PropertyExpression right, List elements, final boolean not) { public static BooleanExpression createInExpression(PropertyExpression right, List elements,
final boolean not) {
// Use a HashSet if there are many elements.
Collection t; // Use a HashSet if there are many elements.
if( elements.size()==0 ) Collection t;
t=null; if (elements.size() == 0)
else if( elements.size() < 5 ) t = null;
t = elements; else if (elements.size() < 5)
else { t = elements;
t = new HashSet(elements); else {
} t = new HashSet(elements);
final Collection inList = t; }
final Collection inList = t;
return new BooleanUnaryExpression(right) { return new BooleanUnaryExpression(right) {
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()!=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;
} else { } else {
return Boolean.FALSE; return Boolean.FALSE;
} }
} }
public String toString() { public String toString() {
StringBuffer answer = new StringBuffer(); StringBuffer answer = new StringBuffer();
answer.append(right); answer.append(right);
answer.append(" "); answer.append(" ");
answer.append(getExpressionSymbol()); answer.append(getExpressionSymbol());
answer.append(" ( "); answer.append(" ( ");
int count=0; int count = 0;
for (Iterator i = inList.iterator(); i.hasNext();) { for (Iterator i = inList.iterator(); i.hasNext();) {
Object o = (Object) i.next(); Object o = (Object)i.next();
if( count!=0 ) { if (count != 0) {
answer.append(", "); answer.append(", ");
} }
answer.append(o); answer.append(o);
count++; count++;
} }
answer.append(" )"); answer.append(" )");
return answer.toString(); return answer.toString();
} }
public String getExpressionSymbol() { public String getExpressionSymbol() {
if( not ) if (not)
return "NOT IN"; return "NOT IN";
else else
return "IN"; return "IN";
} }
}; };
} }
abstract static class BooleanUnaryExpression extends UnaryExpression implements BooleanExpression { abstract static class BooleanUnaryExpression extends UnaryExpression implements BooleanExpression {
public BooleanUnaryExpression(Expression left) { public BooleanUnaryExpression(Expression left) {
super(left); super(left);
} }
public boolean matches(MessageEvaluationContext message) throws JMSException { public boolean matches(MessageEvaluationContext message) throws JMSException {
Object object = evaluate(message); Object object = evaluate(message);
return object!=null && object==Boolean.TRUE; return object != null && object == Boolean.TRUE;
} }
}; };
public static BooleanExpression createNOT(BooleanExpression left) { public static BooleanExpression createNOT(BooleanExpression left) {
return new BooleanUnaryExpression(left) { return new BooleanUnaryExpression(left) {
public Object evaluate(MessageEvaluationContext message) throws JMSException { public Object evaluate(MessageEvaluationContext message) throws JMSException {
Boolean lvalue = (Boolean) right.evaluate(message); Boolean lvalue = (Boolean)right.evaluate(message);
if (lvalue == null) { if (lvalue == null) {
return null; return null;
} }
@ -141,7 +141,7 @@ public abstract class UnaryExpression implements Expression {
} }
}; };
} }
public static BooleanExpression createXPath(final String xpath) { public static BooleanExpression createXPath(final String xpath) {
return new XPathExpression(xpath); return new XPathExpression(xpath);
} }
@ -154,9 +154,9 @@ 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;
} }
@ -172,34 +172,32 @@ public abstract class UnaryExpression implements Expression {
} }
private static Number negate(Number left) { private static Number negate(Number left) {
Class clazz = left.getClass(); Class clazz = left.getClass();
if (clazz == Integer.class) { if (clazz == Integer.class) {
return new Integer(-left.intValue()); return new Integer(-left.intValue());
} } else if (clazz == Long.class) {
else if (clazz == Long.class) {
return new Long(-left.longValue()); return new Long(-left.longValue());
} } else if (clazz == Float.class) {
else if (clazz == Float.class) {
return new Float(-left.floatValue()); return new Float(-left.floatValue());
} } else if (clazz == Double.class) {
else if (clazz == Double.class) {
return new Double(-left.doubleValue()); return new Double(-left.doubleValue());
} } else if (clazz == BigDecimal.class) {
else if (clazz == BigDecimal.class) { // We ussually get a big deciamal when we have Long.MIN_VALUE
// We ussually get a big deciamal when we have Long.MIN_VALUE constant in the // constant in the
// Selector. Long.MIN_VALUE is too big to store in a Long as a positive so we store it // Selector. Long.MIN_VALUE is too big to store in a Long as a
// as a Big decimal. But it gets Negated right away.. to here we try to covert it back // positive so we store it
// to a Long. // as a Big decimal. But it gets Negated right away.. to here we try
BigDecimal bd = (BigDecimal)left; // to covert it back
bd = bd.negate(); // to a Long.
BigDecimal bd = (BigDecimal)left;
if( BD_LONG_MIN_VALUE.compareTo(bd)==0 ) { bd = bd.negate();
return Long.valueOf(Long.MIN_VALUE);
} if (BD_LONG_MIN_VALUE.compareTo(bd) == 0) {
return Long.valueOf(Long.MIN_VALUE);
}
return bd; return bd;
} } else {
else { throw new RuntimeException("Don't know how to negate: " + left);
throw new RuntimeException("Don't know how to negate: "+left);
} }
} }
@ -224,7 +222,7 @@ public abstract class UnaryExpression implements Expression {
/** /**
* TODO: more efficient hashCode() * TODO: more efficient hashCode()
* *
* @see java.lang.Object#hashCode() * @see java.lang.Object#hashCode()
*/ */
public int hashCode() { public int hashCode() {
@ -233,7 +231,7 @@ public abstract class UnaryExpression implements Expression {
/** /**
* TODO: more efficient hashCode() * TODO: more efficient hashCode()
* *
* @see java.lang.Object#equals(java.lang.Object) * @see java.lang.Object#equals(java.lang.Object)
*/ */
public boolean equals(Object o) { public boolean equals(Object o) {
@ -246,9 +244,9 @@ public abstract class UnaryExpression implements Expression {
} }
/** /**
* Returns the symbol that represents this binary expression. For example, addition is * Returns the symbol that represents this binary expression. For example,
* represented by "+" * addition is represented by "+"
* *
* @return * @return
*/ */
abstract public String getExpressionSymbol(); abstract public String getExpressionSymbol();

View File

@ -34,23 +34,24 @@ public final class XPathExpression implements BooleanExpression {
private static final Log log = LogFactory.getLog(XPathExpression.class); private static final Log log = LogFactory.getLog(XPathExpression.class);
private static final String EVALUATOR_SYSTEM_PROPERTY = "org.apache.activemq.XPathEvaluatorClassName"; private static final String EVALUATOR_SYSTEM_PROPERTY = "org.apache.activemq.XPathEvaluatorClassName";
private static final String DEFAULT_EVALUATOR_CLASS_NAME=XalanXPathEvaluator.class.getName(); private static final String DEFAULT_EVALUATOR_CLASS_NAME = XalanXPathEvaluator.class.getName();
private static final Constructor EVALUATOR_CONSTRUCTOR; private static final Constructor EVALUATOR_CONSTRUCTOR;
static { static {
String cn = System.getProperty(EVALUATOR_SYSTEM_PROPERTY, DEFAULT_EVALUATOR_CLASS_NAME); String cn = System.getProperty(EVALUATOR_SYSTEM_PROPERTY, DEFAULT_EVALUATOR_CLASS_NAME);
Constructor m = null; Constructor m = null;
try { try {
try { try {
m = getXPathEvaluatorConstructor(cn); m = getXPathEvaluatorConstructor(cn);
} catch (Throwable e) { } catch (Throwable e) {
log.warn("Invalid "+XPathEvaluator.class.getName()+" implementation: "+cn+", reason: "+e,e); log.warn("Invalid " + XPathEvaluator.class.getName() + " implementation: " + cn
+ ", reason: " + e, e);
cn = DEFAULT_EVALUATOR_CLASS_NAME; cn = DEFAULT_EVALUATOR_CLASS_NAME;
try { try {
m = getXPathEvaluatorConstructor(cn); m = getXPathEvaluatorConstructor(cn);
} catch (Throwable e2) { } catch (Throwable e2) {
log.error("Default XPath evaluator could not be loaded",e); log.error("Default XPath evaluator could not be loaded", e);
} }
} }
} finally { } finally {
@ -58,21 +59,22 @@ public final class XPathExpression implements BooleanExpression {
} }
} }
private static Constructor getXPathEvaluatorConstructor(String cn) throws ClassNotFoundException, SecurityException, NoSuchMethodException { private static Constructor getXPathEvaluatorConstructor(String cn) throws ClassNotFoundException,
SecurityException, NoSuchMethodException {
Class c = XPathExpression.class.getClassLoader().loadClass(cn); Class c = XPathExpression.class.getClassLoader().loadClass(cn);
if( !XPathEvaluator.class.isAssignableFrom(c) ) { if (!XPathEvaluator.class.isAssignableFrom(c)) {
throw new ClassCastException(""+c+" is not an instance of "+XPathEvaluator.class); throw new ClassCastException("" + c + " is not an instance of " + XPathEvaluator.class);
} }
return c.getConstructor(new Class[]{String.class}); return c.getConstructor(new Class[] {String.class});
} }
private final String xpath; private final String xpath;
private final XPathEvaluator evaluator; private final XPathEvaluator evaluator;
static public interface XPathEvaluator { static public interface XPathEvaluator {
public boolean evaluate(Message message) throws JMSException; public boolean evaluate(Message message) throws JMSException;
} }
XPathExpression(String xpath) { XPathExpression(String xpath) {
this.xpath = xpath; this.xpath = xpath;
this.evaluator = createEvaluator(xpath); this.evaluator = createEvaluator(xpath);
@ -80,21 +82,21 @@ public final class XPathExpression implements BooleanExpression {
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});
} catch (InvocationTargetException e) { } catch (InvocationTargetException e) {
Throwable cause = e.getCause(); Throwable cause = e.getCause();
if( cause instanceof RuntimeException ) { if (cause instanceof RuntimeException) {
throw (RuntimeException)cause; throw (RuntimeException)cause;
} }
throw new RuntimeException("Invalid XPath Expression: "+xpath+" reason: "+e.getMessage(), e); throw new RuntimeException("Invalid XPath Expression: " + xpath + " reason: " + e.getMessage(), e);
} catch (Throwable e) { } catch (Throwable e) {
throw new RuntimeException("Invalid XPath Expression: "+xpath+" reason: "+e.getMessage(), e); throw new RuntimeException("Invalid XPath Expression: " + xpath + " reason: " + e.getMessage(), e);
} }
} }
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) {
@ -104,9 +106,9 @@ public final class XPathExpression implements BooleanExpression {
} }
public String toString() { public String toString() {
return "XPATH "+ConstantExpression.encodeString(xpath); return "XPATH " + ConstantExpression.encodeString(xpath);
} }
/** /**
* @param message * @param message
* @return true if the expression evaluates to Boolean.TRUE. * @return true if the expression evaluates to Boolean.TRUE.
@ -114,7 +116,7 @@ public final class XPathExpression implements BooleanExpression {
*/ */
public boolean matches(MessageEvaluationContext message) throws JMSException { public boolean matches(MessageEvaluationContext message) throws JMSException {
Object object = evaluate(message); Object object = evaluate(message);
return object!=null && object==Boolean.TRUE; return object != null && object == Boolean.TRUE;
} }
} }

View File

@ -34,9 +34,9 @@ public final class XQueryExpression implements BooleanExpression {
} }
public String toString() { public String toString() {
return "XQUERY "+ConstantExpression.encodeString(xpath); return "XQUERY " + ConstantExpression.encodeString(xpath);
} }
/** /**
* @param message * @param message
* @return true if the expression evaluates to Boolean.TRUE. * @return true if the expression evaluates to Boolean.TRUE.
@ -44,7 +44,7 @@ public final class XQueryExpression implements BooleanExpression {
*/ */
public boolean matches(MessageEvaluationContext message) throws JMSException { public boolean matches(MessageEvaluationContext message) throws JMSException {
Object object = evaluate(message); Object object = evaluate(message);
return object!=null && object==Boolean.TRUE; return object != null && object == Boolean.TRUE;
} }
} }

View File

@ -33,40 +33,40 @@ import org.w3c.dom.traversal.NodeIterator;
import org.xml.sax.InputSource; import org.xml.sax.InputSource;
public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator { public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator {
private final String xpath; private final String xpath;
public XalanXPathEvaluator(String xpath) { public XalanXPathEvaluator(String xpath) {
this.xpath = xpath; this.xpath = xpath;
} }
public boolean evaluate(Message m) throws JMSException { public boolean evaluate(Message m) throws JMSException {
if( m instanceof TextMessage ) { if (m instanceof TextMessage) {
String text = ((TextMessage)m).getText(); String text = ((TextMessage)m).getText();
return evaluate(text); return evaluate(text);
} else if ( m instanceof BytesMessage ) { } else if (m instanceof BytesMessage) {
BytesMessage bm = (BytesMessage) m; BytesMessage bm = (BytesMessage)m;
byte data[] = new byte[(int) bm.getBodyLength()]; byte data[] = new byte[(int)bm.getBodyLength()];
bm.readBytes(data); bm.readBytes(data);
return evaluate(data); return evaluate(data);
} }
return false; return false;
} }
private boolean evaluate(byte[] data) { private boolean evaluate(byte[] data) {
try { try {
InputSource inputSource = new InputSource(new ByteArrayInputStream(data)); InputSource inputSource = new InputSource(new ByteArrayInputStream(data));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); factory.setNamespaceAware(true);
DocumentBuilder dbuilder = factory.newDocumentBuilder(); DocumentBuilder dbuilder = factory.newDocumentBuilder();
Document doc = dbuilder.parse(inputSource); Document doc = dbuilder.parse(inputSource);
CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); CachedXPathAPI cachedXPathAPI = new CachedXPathAPI();
NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc,xpath); NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc, xpath);
return iterator.nextNode()!=null; return iterator.nextNode() != null;
} catch (Throwable e) { } catch (Throwable e) {
return false; return false;
} }
@ -75,17 +75,18 @@ public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator {
private boolean evaluate(String text) { private boolean evaluate(String text) {
try { try {
InputSource inputSource = new InputSource(new StringReader(text)); InputSource inputSource = new InputSource(new StringReader(text));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); factory.setNamespaceAware(true);
DocumentBuilder dbuilder = factory.newDocumentBuilder(); DocumentBuilder dbuilder = factory.newDocumentBuilder();
Document doc = dbuilder.parse(inputSource); Document doc = dbuilder.parse(inputSource);
// We should associated the cachedXPathAPI object with the message being evaluated // We should associated the cachedXPathAPI object with the message
// being evaluated
// since that should speedup subsequent xpath expressions. // since that should speedup subsequent xpath expressions.
CachedXPathAPI cachedXPathAPI = new CachedXPathAPI(); CachedXPathAPI cachedXPathAPI = new CachedXPathAPI();
NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc,xpath); NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc, xpath);
return iterator.nextNode()!=null; return iterator.nextNode() != null;
} catch (Throwable e) { } catch (Throwable e) {
return false; return false;
} }

View File

@ -40,18 +40,19 @@ import org.apache.activemq.command.ActiveMQTopic;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
/** /**
* A factory of the ActiveMQ InitialContext which contains {@link ConnectionFactory} * A factory of the ActiveMQ InitialContext which contains
* instances as well as a child context called <i>destinations</i> which contain all of the * {@link ConnectionFactory} instances as well as a child context called
* current active destinations, in child context depending on the QoS such as * <i>destinations</i> which contain all of the current active destinations, in
* transient or durable and queue or topic. * child context depending on the QoS such as transient or durable and queue or
* * topic.
*
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public class ActiveMQInitialContextFactory implements InitialContextFactory { public class ActiveMQInitialContextFactory implements InitialContextFactory {
private static final String[] defaultConnectionFactoryNames = { private static final String[] defaultConnectionFactoryNames = {"ConnectionFactory",
"ConnectionFactory", "QueueConnectionFactory", "TopicConnectionFactory" "QueueConnectionFactory",
}; "TopicConnectionFactory"};
private String connectionPrefix = "connection."; private String connectionPrefix = "connection.";
private String queuePrefix = "queue."; private String queuePrefix = "queue.";
@ -62,34 +63,29 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory {
Map data = new ConcurrentHashMap(); Map data = new ConcurrentHashMap();
String[] names = getConnectionFactoryNames(environment); String[] names = getConnectionFactoryNames(environment);
for (int i = 0; i < names.length; i++) { for (int i = 0; i < names.length; i++) {
ActiveMQConnectionFactory factory =null; ActiveMQConnectionFactory factory = null;
String name = names[i]; String name = names[i];
try{ try {
factory = createConnectionFactory(name, environment); factory = createConnectionFactory(name, environment);
}catch(Exception e){ } catch (Exception e) {
throw new NamingException("Invalid broker URL"); throw new NamingException("Invalid broker URL");
} }
/* if( broker==null ) { /*
try { * if( broker==null ) { try { broker = factory.getEmbeddedBroker(); }
broker = factory.getEmbeddedBroker(); * catch (JMSException e) { log.warn("Failed to get embedded
} * broker", e); } }
catch (JMSException e) { */
log.warn("Failed to get embedded broker", e); data.put(name, factory);
}
}
*/
data.put(name,factory);
} }
createQueues(data, environment); createQueues(data, environment);
createTopics(data, environment); createTopics(data, environment);
/* /*
if (broker != null) { * if (broker != null) { data.put("destinations",
data.put("destinations", broker.getDestinationContext(environment)); * broker.getDestinationContext(environment)); }
} */
*/
data.put("dynamicQueues", new LazyCreateContext() { data.put("dynamicQueues", new LazyCreateContext() {
private static final long serialVersionUID = 6503881346214855588L; private static final long serialVersionUID = 6503881346214855588L;
@ -109,7 +105,7 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory {
} }
// Properties // Properties
//------------------------------------------------------------------------- // -------------------------------------------------------------------------
public String getTopicPrefix() { public String getTopicPrefix() {
return topicPrefix; return topicPrefix;
} }
@ -127,19 +123,20 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory {
} }
// Implementation methods // Implementation methods
//------------------------------------------------------------------------- // -------------------------------------------------------------------------
protected ReadOnlyContext createContext(Hashtable environment, Map data) { protected ReadOnlyContext createContext(Hashtable environment, Map data) {
return new ReadOnlyContext(environment, data); return new ReadOnlyContext(environment, data);
} }
protected ActiveMQConnectionFactory createConnectionFactory(String name, Hashtable environment) throws URISyntaxException { protected ActiveMQConnectionFactory createConnectionFactory(String name, Hashtable environment)
throws URISyntaxException {
Hashtable temp = new Hashtable(environment); Hashtable temp = new Hashtable(environment);
String prefix = connectionPrefix+name+"."; String prefix = connectionPrefix + name + ".";
for (Iterator iter = environment.entrySet().iterator(); iter.hasNext();) { for (Iterator iter = environment.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next(); Map.Entry entry = (Map.Entry)iter.next();
String key = (String) entry.getKey(); String key = (String)entry.getKey();
if( key.startsWith(prefix) ) { if (key.startsWith(prefix)) {
// Rename the key... // Rename the key...
temp.remove(key); temp.remove(key);
key = key.substring(prefix.length()); key = key.substring(prefix.length());
@ -150,10 +147,11 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory {
} }
protected String[] getConnectionFactoryNames(Map environment) { protected String[] getConnectionFactoryNames(Map environment) {
String factoryNames = (String) environment.get("connectionFactoryNames"); String factoryNames = (String)environment.get("connectionFactoryNames");
if (factoryNames != null) { if (factoryNames != null) {
List list = new ArrayList(); List list = new ArrayList();
for (StringTokenizer enumeration = new StringTokenizer(factoryNames, ","); enumeration.hasMoreTokens();) { for (StringTokenizer enumeration = new StringTokenizer(factoryNames, ","); enumeration
.hasMoreTokens();) {
list.add(enumeration.nextToken().trim()); list.add(enumeration.nextToken().trim());
} }
int size = list.size(); int size = list.size();
@ -168,7 +166,7 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory {
protected void createQueues(Map data, Hashtable environment) { protected void createQueues(Map data, Hashtable environment) {
for (Iterator iter = environment.entrySet().iterator(); iter.hasNext();) { for (Iterator iter = environment.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next(); Map.Entry entry = (Map.Entry)iter.next();
String key = entry.getKey().toString(); String key = entry.getKey().toString();
if (key.startsWith(queuePrefix)) { if (key.startsWith(queuePrefix)) {
String jndiName = key.substring(queuePrefix.length()); String jndiName = key.substring(queuePrefix.length());
@ -179,7 +177,7 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory {
protected void createTopics(Map data, Hashtable environment) { protected void createTopics(Map data, Hashtable environment) {
for (Iterator iter = environment.entrySet().iterator(); iter.hasNext();) { for (Iterator iter = environment.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next(); Map.Entry entry = (Map.Entry)iter.next();
String key = entry.getKey().toString(); String key = entry.getKey().toString();
if (key.startsWith(topicPrefix)) { if (key.startsWith(topicPrefix)) {
String jndiName = key.substring(topicPrefix.length()); String jndiName = key.substring(topicPrefix.length());
@ -201,11 +199,13 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory {
protected Topic createTopic(String name) { protected Topic createTopic(String name) {
return new ActiveMQTopic(name); return new ActiveMQTopic(name);
} }
/** /**
* Factory method to create a new connection factory from the given environment * Factory method to create a new connection factory from the given
* environment
*/ */
protected ActiveMQConnectionFactory createConnectionFactory(Hashtable environment) throws URISyntaxException { protected ActiveMQConnectionFactory createConnectionFactory(Hashtable environment)
throws URISyntaxException {
ActiveMQConnectionFactory answer = new ActiveMQConnectionFactory(); ActiveMQConnectionFactory answer = new ActiveMQConnectionFactory();
Properties properties = new Properties(); Properties properties = new Properties();
properties.putAll(environment); properties.putAll(environment);
@ -216,10 +216,9 @@ public class ActiveMQInitialContextFactory implements InitialContextFactory {
public String getConnectionPrefix() { public String getConnectionPrefix() {
return connectionPrefix; return connectionPrefix;
} }
public void setConnectionPrefix(String connectionPrefix) { public void setConnectionPrefix(String connectionPrefix) {
this.connectionPrefix = connectionPrefix; this.connectionPrefix = connectionPrefix;
} }
} }

View File

@ -19,12 +19,13 @@ package org.apache.activemq.kaha;
import java.io.DataInput; import java.io.DataInput;
import java.io.DataOutput; import java.io.DataOutput;
import java.io.IOException; import java.io.IOException;
/** /**
* Implementation of a Marshaller for byte arrays * Implementation of a Marshaller for byte arrays
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public class BytesMarshaller implements Marshaller{ public class BytesMarshaller implements Marshaller {
/** /**
* Write the payload of this entry to the RawContainer * Write the payload of this entry to the RawContainer
* *
@ -32,8 +33,8 @@ public class BytesMarshaller implements Marshaller{
* @param dataOut * @param dataOut
* @throws IOException * @throws IOException
*/ */
public void writePayload(Object object,DataOutput dataOut) throws IOException{ public void writePayload(Object object, DataOutput dataOut) throws IOException {
byte[] data=(byte[]) object; byte[] data = (byte[])object;
dataOut.writeInt(data.length); dataOut.writeInt(data.length);
dataOut.write(data); dataOut.write(data);
} }
@ -45,9 +46,9 @@ public class BytesMarshaller implements Marshaller{
* @return unmarshalled object * @return unmarshalled object
* @throws IOException * @throws IOException
*/ */
public Object readPayload(DataInput dataIn) throws IOException{ public Object readPayload(DataInput dataIn) throws IOException {
int size=dataIn.readInt(); int size = dataIn.readInt();
byte[] data=new byte[size]; byte[] data = new byte[size];
dataIn.readFully(data); dataIn.readFully(data);
return data; return data;
} }

View File

@ -20,77 +20,77 @@ import java.io.Externalizable;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectInput; import java.io.ObjectInput;
import java.io.ObjectOutput; import java.io.ObjectOutput;
/** /**
* Used by RootContainers * Used by RootContainers
* *
* @version $Revision: 1.1.1.1 $ * @version $Revision: 1.1.1.1 $
*/ */
public class ContainerId implements Externalizable{ public class ContainerId implements Externalizable {
private static final long serialVersionUID=-8883779541021821943L; private static final long serialVersionUID = -8883779541021821943L;
private Object key; private Object key;
private String dataContainerName; private String dataContainerName;
public ContainerId() { public ContainerId() {
} }
public ContainerId(Object key,String dataContainerName) { public ContainerId(Object key, String dataContainerName) {
this.key=key; this.key = key;
this.dataContainerName=dataContainerName; this.dataContainerName = dataContainerName;
} }
/** /**
* @return Returns the dataContainerPrefix. * @return Returns the dataContainerPrefix.
*/ */
public String getDataContainerName(){ public String getDataContainerName() {
return dataContainerName; return dataContainerName;
} }
/** /**
* @param dataContainerName The dataContainerPrefix to set. * @param dataContainerName The dataContainerPrefix to set.
*/ */
public void setDataContainerName(String dataContainerName){ public void setDataContainerName(String dataContainerName) {
this.dataContainerName=dataContainerName; this.dataContainerName = dataContainerName;
} }
/** /**
* @return Returns the key. * @return Returns the key.
*/ */
public Object getKey(){ public Object getKey() {
return key; return key;
} }
/** /**
* @param key The key to set. * @param key The key to set.
*/ */
public void setKey(Object key){ public void setKey(Object key) {
this.key=key; this.key = key;
} }
public int hashCode(){ public int hashCode() {
return key.hashCode(); return key.hashCode();
} }
public boolean equals(Object obj){ public boolean equals(Object obj) {
boolean result = false; boolean result = false;
if (obj != null && obj instanceof ContainerId){ if (obj != null && obj instanceof ContainerId) {
ContainerId other = (ContainerId) obj; ContainerId other = (ContainerId)obj;
result = other.key.equals(this.key); result = other.key.equals(this.key);
} }
return result; return result;
} }
public void writeExternal(ObjectOutput out) throws IOException{ public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(getDataContainerName()); out.writeUTF(getDataContainerName());
out.writeObject(key); out.writeObject(key);
} }
public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException{ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
dataContainerName=in.readUTF(); dataContainerName = in.readUTF();
key=in.readObject(); key = in.readObject();
} }
public String toString(){ public String toString() {
return "CID{"+dataContainerName + ":" + key + "}"; return "CID{" + dataContainerName + ":" + key + "}";
} }
} }

View File

@ -18,16 +18,17 @@ import java.util.List;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
/** /**
* Represents a container of persistent objects in the store Acts as a map, but values can be retrieved in insertion * Represents a container of persistent objects in the store Acts as a map, but
* order * values can be retrieved in insertion order
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public interface ListContainer<V> extends List<V>{ public interface ListContainer<V> extends List<V> {
/** /**
* The container is created or retrieved in an unloaded state. load populates the container will all the indexes * The container is created or retrieved in an unloaded state. load
* used etc and should be called before any operations on the container * populates the container will all the indexes used etc and should be
* called before any operations on the container
*/ */
public void load(); public void load();
@ -43,7 +44,8 @@ public interface ListContainer<V> extends List<V>{
public boolean isLoaded(); public boolean isLoaded();
/** /**
* For homogenous containers can set a custom marshaller for loading values The default uses Object serialization * For homogenous containers can set a custom marshaller for loading values
* The default uses Object serialization
* *
* @param marshaller * @param marshaller
*/ */
@ -67,8 +69,8 @@ public interface ListContainer<V> extends List<V>{
public void addFirst(V o); public void addFirst(V o);
/** /**
* Appends the given element to the end of this list. (Identical in function to the <tt>add</tt> method; included * Appends the given element to the end of this list. (Identical in function
* only for consistency.) * to the <tt>add</tt> method; included only for consistency.)
* *
* @param o the element to be inserted at the end of this list. * @param o the element to be inserted at the end of this list.
*/ */
@ -91,7 +93,8 @@ public interface ListContainer<V> extends List<V>{
public V removeLast(); public V removeLast();
/** /**
* remove an objecr from the list without retrieving the old value from the store * remove an objecr from the list without retrieving the old value from the
* store
* *
* @param position * @param position
* @return true if successful * @return true if successful
@ -107,7 +110,8 @@ public interface ListContainer<V> extends List<V>{
public StoreEntry placeLast(V object); public StoreEntry placeLast(V object);
/** /**
* insert an Object in first position int the list but get a StoreEntry of its position * insert an Object in first position int the list but get a StoreEntry of
* its position
* *
* @param object * @param object
* @return the location in the Store * @return the location in the Store
@ -115,12 +119,13 @@ public interface ListContainer<V> extends List<V>{
public StoreEntry placeFirst(V object); public StoreEntry placeFirst(V object);
/** /**
* Advanced feature = must ensure the object written doesn't overwrite other objects in the container * Advanced feature = must ensure the object written doesn't overwrite other
* objects in the container
* *
* @param entry * @param entry
* @param object * @param object
*/ */
public void update(StoreEntry entry,V object); public void update(StoreEntry entry, V object);
/** /**
* Retrieve an Object from the Store by its location * Retrieve an Object from the Store by its location
@ -167,10 +172,11 @@ public interface ListContainer<V> extends List<V>{
* @return true if successful * @return true if successful
*/ */
public boolean remove(StoreEntry entry); public boolean remove(StoreEntry entry);
/** /**
* It's possible that a StoreEntry could be come stale * It's possible that a StoreEntry could be come stale this will return an
* this will return an upto date entry for the StoreEntry position * upto date entry for the StoreEntry position
*
* @param entry old entry * @param entry old entry
* @return a refreshed StoreEntry * @return a refreshed StoreEntry
*/ */

View File

@ -21,47 +21,48 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
/** /**
*Represents a container of persistent objects in the store * Represents a container of persistent objects in the store Acts as a map, but
*Acts as a map, but values can be retrieved in insertion order * values can be retrieved in insertion order
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public interface MapContainer<K, V> extends Map<K, V>{ public interface MapContainer<K, V> extends Map<K, V> {
/** /**
* The container is created or retrieved in * The container is created or retrieved in an unloaded state. load
* an unloaded state. * populates the container will all the indexes used etc and should be
* load populates the container will all the indexes used etc * called before any operations on the container
* and should be called before any operations on the container
*/ */
public void load(); public void load();
/** /**
* unload indexes from the container * unload indexes from the container
* *
*/ */
public void unload(); public void unload();
/** /**
* @return true if the indexes are loaded * @return true if the indexes are loaded
*/ */
public boolean isLoaded(); public boolean isLoaded();
/** /**
* For homogenous containers can set a custom marshaller for loading keys * For homogenous containers can set a custom marshaller for loading keys
* The default uses Object serialization * The default uses Object serialization
*
* @param keyMarshaller * @param keyMarshaller
*/ */
public void setKeyMarshaller(Marshaller<K> keyMarshaller); public void setKeyMarshaller(Marshaller<K> keyMarshaller);
/** /**
* For homogenous containers can set a custom marshaller for loading values * For homogenous containers can set a custom marshaller for loading values
* The default uses Object serialization * The default uses Object serialization
* @param valueMarshaller *
* @param valueMarshaller
*
*/ */
public void setValueMarshaller(Marshaller<V> valueMarshaller); public void setValueMarshaller(Marshaller<V> valueMarshaller);
/** /**
* @return the id the MapContainer was create with * @return the id the MapContainer was create with
*/ */
@ -78,30 +79,31 @@ public interface MapContainer<K, V> extends Map<K, V>{
public boolean isEmpty(); public boolean isEmpty();
/** /**
* @param key * @param key
* @return true if the container contains the key * @return true if the container contains the key
*/ */
public boolean containsKey(K key); public boolean containsKey(K key);
/** /**
* Get the value associated with the key * Get the value associated with the key
* @param key *
* @param key
* @return the value associated with the key from the store * @return the value associated with the key from the store
*/ */
public V get(K key); public V get(K key);
/** /**
* @param o * @param o
* @return true if the MapContainer contains the value o * @return true if the MapContainer contains the value o
*/ */
public boolean containsValue(K o); public boolean containsValue(K o);
/** /**
* Add add entries in the supplied Map * Add add entries in the supplied Map
*
* @param map * @param map
*/ */
public void putAll(Map<K,V> map); public void putAll(Map<K, V> map);
/** /**
* @return a Set of all the keys * @return a Set of all the keys
@ -109,30 +111,30 @@ public interface MapContainer<K, V> extends Map<K, V>{
public Set<K> keySet(); public Set<K> keySet();
/** /**
* @return a collection of all the values - the values will be lazily pulled out of the * @return a collection of all the values - the values will be lazily pulled
* store if iterated etc. * out of the store if iterated etc.
*/ */
public Collection<V> values(); public Collection<V> values();
/** /**
* @return a Set of all the Map.Entry instances - the values will be lazily pulled out of the * @return a Set of all the Map.Entry instances - the values will be lazily
* store if iterated etc. * pulled out of the store if iterated etc.
*/ */
public Set<Map.Entry<K,V>> entrySet(); public Set<Map.Entry<K, V>> entrySet();
/** /**
* Add an entry * Add an entry
*
* @param key * @param key
* @param value * @param value
* @return the old value for the key * @return the old value for the key
*/ */
public V put(K key,V value); public V put(K key, V value);
/** /**
* remove an entry associated with the key * remove an entry associated with the key
* @param key *
* @param key
* @return the old value assocaited with the key or null * @return the old value assocaited with the key or null
*/ */
public V remove(K key); public V remove(K key);
@ -141,77 +143,83 @@ public interface MapContainer<K, V> extends Map<K, V>{
* empty the container * empty the container
*/ */
public void clear(); public void clear();
/** /**
* Add an entry to the Store Map * Add an entry to the Store Map
*
* @param key * @param key
* @param Value * @param Value
* @return the StoreEntry associated with the entry * @return the StoreEntry associated with the entry
*/ */
public StoreEntry place(K key, V Value); public StoreEntry place(K key, V Value);
/** /**
* Remove an Entry from ther Map * Remove an Entry from ther Map
*
* @param entry * @param entry
*/ */
public void remove(StoreEntry entry); public void remove(StoreEntry entry);
/** /**
* Get the Key object from it's location * Get the Key object from it's location
*
* @param keyLocation * @param keyLocation
* @return the key for the entry * @return the key for the entry
*/ */
public K getKey(StoreEntry keyLocation); public K getKey(StoreEntry keyLocation);
/** /**
* Get the value from it's location * Get the value from it's location
*
* @param Valuelocation * @param Valuelocation
* @return the Object * @return the Object
*/ */
public V getValue(StoreEntry Valuelocation); public V getValue(StoreEntry Valuelocation);
/** Get the StoreEntry for the first value in the Map
*
* @return the first StoreEntry or null if the map is empty
*/
public StoreEntry getFirst();
/** /**
* Get the StoreEntry for the last value item of the Map * Get the StoreEntry for the first value in the Map
* *
* @return the last StoreEntry or null if the list is empty * @return the first StoreEntry or null if the map is empty
*/ */
public StoreEntry getLast(); public StoreEntry getFirst();
/** /**
* Get the next StoreEntry value from the map * Get the StoreEntry for the last value item of the Map
* *
* @param entry * @return the last StoreEntry or null if the list is empty
* @return the next StoreEntry or null */
*/ public StoreEntry getLast();
public StoreEntry getNext(StoreEntry entry);
/** /**
* Get the previous StoreEntry from the map * Get the next StoreEntry value from the map
* *
* @param entry * @param entry
* @return the previous store entry or null * @return the next StoreEntry or null
*/ */
public StoreEntry getPrevious(StoreEntry entry); public StoreEntry getNext(StoreEntry entry);
/**
/** * Get the previous StoreEntry from the map
* It's possible that a StoreEntry could be come stale *
* this will return an upto date entry for the StoreEntry position * @param entry
* @param entry old entry * @return the previous store entry or null
* @return a refreshed StoreEntry */
*/ public StoreEntry getPrevious(StoreEntry entry);
public StoreEntry refresh(StoreEntry entry);
/**
/** * It's possible that a StoreEntry could be come stale this will return an
* Get the StoreEntry associated with the key * upto date entry for the StoreEntry position
* @param key *
* @return the StoreEntry * @param entry old entry
*/ * @return a refreshed StoreEntry
public StoreEntry getEntry(K key); */
public StoreEntry refresh(StoreEntry entry);
/**
* Get the StoreEntry associated with the key
*
* @param key
* @return the StoreEntry
*/
public StoreEntry getEntry(K key);
} }

View File

@ -20,6 +20,7 @@ import java.io.DataInput;
import java.io.DataOutput; import java.io.DataOutput;
import java.io.IOException; import java.io.IOException;
import org.apache.activemq.command.MessageId; import org.apache.activemq.command.MessageId;
/** /**
* Implementation of a Marshaller for MessageIds * Implementation of a Marshaller for MessageIds
* *
@ -33,7 +34,7 @@ public class MessageIdMarshaller implements Marshaller<MessageId> {
* @param dataOut * @param dataOut
* @throws IOException * @throws IOException
*/ */
public void writePayload(MessageId object,DataOutput dataOut) throws IOException{ public void writePayload(MessageId object, DataOutput dataOut) throws IOException {
dataOut.writeUTF(object.toString()); dataOut.writeUTF(object.toString());
} }
@ -44,7 +45,7 @@ public class MessageIdMarshaller implements Marshaller<MessageId> {
* @return unmarshalled object * @return unmarshalled object
* @throws IOException * @throws IOException
*/ */
public MessageId readPayload(DataInput dataIn) throws IOException{ public MessageId readPayload(DataInput dataIn) throws IOException {
return new MessageId(dataIn.readUTF()); return new MessageId(dataIn.readUTF());
} }
} }

View File

@ -27,7 +27,7 @@ import java.io.ObjectOutputStream;
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public class ObjectMarshaller implements Marshaller{ public class ObjectMarshaller implements Marshaller {
/** /**
* Write the payload of this entry to the RawContainer * Write the payload of this entry to the RawContainer
@ -36,12 +36,12 @@ public class ObjectMarshaller implements Marshaller{
* @param dataOut * @param dataOut
* @throws IOException * @throws IOException
*/ */
public void writePayload(Object object,DataOutput dataOut) throws IOException{ public void writePayload(Object object, DataOutput dataOut) throws IOException {
ByteArrayOutputStream bytesOut=new ByteArrayOutputStream(); ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
ObjectOutputStream objectOut=new ObjectOutputStream(bytesOut); ObjectOutputStream objectOut = new ObjectOutputStream(bytesOut);
objectOut.writeObject(object); objectOut.writeObject(object);
objectOut.close(); objectOut.close();
byte[] data=bytesOut.toByteArray(); byte[] data = bytesOut.toByteArray();
dataOut.writeInt(data.length); dataOut.writeInt(data.length);
dataOut.write(data); dataOut.write(data);
} }
@ -53,15 +53,15 @@ public class ObjectMarshaller implements Marshaller{
* @return unmarshalled object * @return unmarshalled object
* @throws IOException * @throws IOException
*/ */
public Object readPayload(DataInput dataIn) throws IOException{ public Object readPayload(DataInput dataIn) throws IOException {
int size=dataIn.readInt(); int size = dataIn.readInt();
byte[] data=new byte[size]; byte[] data = new byte[size];
dataIn.readFully(data); dataIn.readFully(data);
ByteArrayInputStream bytesIn=new ByteArrayInputStream(data); ByteArrayInputStream bytesIn = new ByteArrayInputStream(data);
ObjectInputStream objectIn=new ObjectInputStream(bytesIn); ObjectInputStream objectIn = new ObjectInputStream(bytesIn);
try{ try {
return objectIn.readObject(); return objectIn.readObject();
}catch(ClassNotFoundException e){ } catch (ClassNotFoundException e) {
throw new IOException(e.getMessage()); throw new IOException(e.getMessage());
} }
} }

View File

@ -16,47 +16,48 @@
*/ */
package org.apache.activemq.kaha; package org.apache.activemq.kaha;
/** /**
*Runtime exception for the Store * Runtime exception for the Store
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public class RuntimeStoreException extends RuntimeException{ public class RuntimeStoreException extends RuntimeException {
private static final long serialVersionUID = 8807084681372365173L;
private static final long serialVersionUID=8807084681372365173L;
/** /**
* Constructor * Constructor
*/ */
public RuntimeStoreException(){ public RuntimeStoreException() {
super(); super();
} }
/** /**
* Constructor * Constructor
*
* @param message * @param message
*/ */
public RuntimeStoreException(String message){ public RuntimeStoreException(String message) {
super(message); super(message);
} }
/** /**
* Constructor * Constructor
*
* @param message * @param message
* @param cause * @param cause
*/ */
public RuntimeStoreException(String message,Throwable cause){ public RuntimeStoreException(String message, Throwable cause) {
super(message,cause); super(message, cause);
} }
/** /**
* Constructor * Constructor
*
* @param cause * @param cause
*/ */
public RuntimeStoreException(Throwable cause){ public RuntimeStoreException(Throwable cause) {
super(cause); super(cause);
} }
} }

View File

@ -18,37 +18,38 @@ package org.apache.activemq.kaha;
import java.io.IOException; import java.io.IOException;
import java.util.Set; import java.util.Set;
/** /**
* A Store is holds persistent containers * A Store is holds persistent containers
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public interface Store{ public interface Store {
/** /**
* Defauly container name * Defauly container name
*/ */
public static final String DEFAULT_CONTAINER_NAME="kaha"; public static final String DEFAULT_CONTAINER_NAME = "kaha";
/** /**
* Byte Marshaller * Byte Marshaller
*/ */
public final static Marshaller BytesMarshaller = new BytesMarshaller(); public final static Marshaller BytesMarshaller = new BytesMarshaller();
/** /**
* Object Marshaller * Object Marshaller
*/ */
public final static Marshaller ObjectMarshaller = new ObjectMarshaller(); public final static Marshaller ObjectMarshaller = new ObjectMarshaller();
/** /**
* String Marshaller * String Marshaller
*/ */
public final static Marshaller StringMarshaller = new StringMarshaller(); public final static Marshaller StringMarshaller = new StringMarshaller();
/** /**
* Command Marshaller * Command Marshaller
*/ */
public final static Marshaller CommandMarshaller = new CommandMarshaller(); public final static Marshaller CommandMarshaller = new CommandMarshaller();
/** /**
* close the store * close the store
* *
@ -86,46 +87,50 @@ public interface Store{
* @throws IOException * @throws IOException
*/ */
public boolean doesMapContainerExist(Object id) throws IOException; public boolean doesMapContainerExist(Object id) throws IOException;
/** /**
* Checks if a MapContainer exists in the named container * Checks if a MapContainer exists in the named container
* *
* @param id * @param id
* @param containerName * @param containerName
* @return new MapContainer * @return new MapContainer
* @throws IOException * @throws IOException
*/ */
public boolean doesMapContainerExist(Object id,String containerName) throws IOException; public boolean doesMapContainerExist(Object id, String containerName) throws IOException;
/** /**
* Get a MapContainer with the given id - the MapContainer is created if needed * Get a MapContainer with the given id - the MapContainer is created if
* needed
* *
* @param id * @param id
* @return container for the associated id or null if it doesn't exist * @return container for the associated id or null if it doesn't exist
* @throws IOException * @throws IOException
*/ */
public MapContainer getMapContainer(Object id) throws IOException; public MapContainer getMapContainer(Object id) throws IOException;
/** /**
* Get a MapContainer with the given id - the MapContainer is created if needed * Get a MapContainer with the given id - the MapContainer is created if
* needed
* *
* @param id * @param id
* @param containerName * @param containerName
* @return container for the associated id or null if it doesn't exist * @return container for the associated id or null if it doesn't exist
* @throws IOException * @throws IOException
*/ */
public MapContainer getMapContainer(Object id,String containerName) throws IOException; public MapContainer getMapContainer(Object id, String containerName) throws IOException;
/** /**
* Get a MapContainer with the given id - the MapContainer is created if needed * Get a MapContainer with the given id - the MapContainer is created if
* needed
* *
* @param id * @param id
* @param containerName * @param containerName
* @param persistentIndex * @param persistentIndex
* @return container for the associated id or null if it doesn't exist * @return container for the associated id or null if it doesn't exist
* @throws IOException * @throws IOException
*/ */
public MapContainer getMapContainer(Object id,String containerName,boolean persistentIndex) throws IOException; public MapContainer getMapContainer(Object id, String containerName, boolean persistentIndex)
throws IOException;
/** /**
* delete a container from the default container * delete a container from the default container
@ -134,18 +139,19 @@ public interface Store{
* @throws IOException * @throws IOException
*/ */
public void deleteMapContainer(Object id) throws IOException; public void deleteMapContainer(Object id) throws IOException;
/** /**
* delete a MapContainer from the name container * delete a MapContainer from the name container
* *
* @param id * @param id
* @param containerName * @param containerName
* @throws IOException * @throws IOException
*/ */
public void deleteMapContainer(Object id,String containerName) throws IOException; public void deleteMapContainer(Object id, String containerName) throws IOException;
/** /**
* Delete Map container * Delete Map container
*
* @param id * @param id
* @throws IOException * @throws IOException
*/ */
@ -167,16 +173,16 @@ public interface Store{
* @throws IOException * @throws IOException
*/ */
public boolean doesListContainerExist(Object id) throws IOException; public boolean doesListContainerExist(Object id) throws IOException;
/** /**
* Checks if a ListContainer exists in the named container * Checks if a ListContainer exists in the named container
* *
* @param id * @param id
* @param containerName * @param containerName
* @return new MapContainer * @return new MapContainer
* @throws IOException * @throws IOException
*/ */
public boolean doesListContainerExist(Object id,String containerName) throws IOException; public boolean doesListContainerExist(Object id, String containerName) throws IOException;
/** /**
* Get a ListContainer with the given id and creates it if it doesn't exist * Get a ListContainer with the given id and creates it if it doesn't exist
@ -185,7 +191,7 @@ public interface Store{
* @return container for the associated id or null if it doesn't exist * @return container for the associated id or null if it doesn't exist
* @throws IOException * @throws IOException
*/ */
public ListContainer getListContainer(Object id) throws IOException; public ListContainer getListContainer(Object id) throws IOException;
/** /**
* Get a ListContainer with the given id and creates it if it doesn't exist * Get a ListContainer with the given id and creates it if it doesn't exist
@ -195,18 +201,19 @@ public interface Store{
* @return container for the associated id or null if it doesn't exist * @return container for the associated id or null if it doesn't exist
* @throws IOException * @throws IOException
*/ */
public ListContainer getListContainer(Object id,String containerName) throws IOException; public ListContainer getListContainer(Object id, String containerName) throws IOException;
/** /**
* Get a ListContainer with the given id and creates it if it doesn't exist * Get a ListContainer with the given id and creates it if it doesn't exist
* *
* @param id * @param id
* @param containerName * @param containerName
* @param persistentIndex * @param persistentIndex
* @return container for the associated id or null if it doesn't exist * @return container for the associated id or null if it doesn't exist
* @throws IOException * @throws IOException
*/ */
public ListContainer getListContainer(Object id,String containerName,boolean persistentIndex) throws IOException; public ListContainer getListContainer(Object id, String containerName, boolean persistentIndex)
throws IOException;
/** /**
* delete a ListContainer from the default container * delete a ListContainer from the default container
@ -215,18 +222,19 @@ public interface Store{
* @throws IOException * @throws IOException
*/ */
public void deleteListContainer(Object id) throws IOException; public void deleteListContainer(Object id) throws IOException;
/** /**
* delete a ListContainer from the named container * delete a ListContainer from the named container
* *
* @param id * @param id
* @param containerName * @param containerName
* @throws IOException * @throws IOException
*/ */
public void deleteListContainer(Object id,String containerName) throws IOException; public void deleteListContainer(Object id, String containerName) throws IOException;
/** /**
* delete a list container * delete a list container
*
* @param id * @param id
* @throws IOException * @throws IOException
*/ */
@ -239,7 +247,7 @@ public interface Store{
* @throws IOException * @throws IOException
*/ */
public Set<ContainerId> getListContainerIds() throws IOException; public Set<ContainerId> getListContainerIds() throws IOException;
/** /**
* @return the maxDataFileLength * @return the maxDataFileLength
*/ */
@ -249,20 +257,21 @@ public interface Store{
* @param maxDataFileLength the maxDataFileLength to set * @param maxDataFileLength the maxDataFileLength to set
*/ */
public void setMaxDataFileLength(long maxDataFileLength); public void setMaxDataFileLength(long maxDataFileLength);
/** /**
* @see org.apache.activemq.kaha.IndexTypes * @see org.apache.activemq.kaha.IndexTypes
* @return the default index type * @return the default index type
*/ */
public String getIndexTypeAsString(); public String getIndexTypeAsString();
/** /**
* Set the default index type * Set the default index type
*
* @param type * @param type
* @see org.apache.activemq.kaha.IndexTypes * @see org.apache.activemq.kaha.IndexTypes
*/ */
public void setIndexTypeAsString(String type); public void setIndexTypeAsString(String type);
/** /**
* @return true if the store has been initialized * @return true if the store has been initialized
*/ */

View File

@ -25,28 +25,29 @@ import org.apache.activemq.kaha.impl.KahaStore;
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public class StoreFactory{ public class StoreFactory {
/** /**
* open or create a Store * open or create a Store
*
* @param name * @param name
* @param mode * @param mode
* @return the opened/created store * @return the opened/created store
* @throws IOException * @throws IOException
*/ */
public static Store open(String name,String mode) throws IOException{ public static Store open(String name, String mode) throws IOException {
return new KahaStore(name,mode); return new KahaStore(name, mode);
} }
/** /**
* Delete a database * Delete a database
*
* @param name of the database * @param name of the database
* @return true if successful * @return true if successful
* @throws IOException * @throws IOException
*/ */
public static boolean delete(String name) throws IOException{ public static boolean delete(String name) throws IOException {
KahaStore store = new KahaStore(name,"rw"); KahaStore store = new KahaStore(name, "rw");
return store.delete(); return store.delete();
} }
} }

View File

@ -19,6 +19,7 @@ package org.apache.activemq.kaha;
import java.io.DataInput; import java.io.DataInput;
import java.io.DataOutput; import java.io.DataOutput;
import java.io.IOException; import java.io.IOException;
/** /**
* Implementation of a Marshaller for Strings * Implementation of a Marshaller for Strings
* *
@ -32,7 +33,7 @@ public class StringMarshaller implements Marshaller<String> {
* @param dataOut * @param dataOut
* @throws IOException * @throws IOException
*/ */
public void writePayload(String object,DataOutput dataOut) throws IOException{ public void writePayload(String object, DataOutput dataOut) throws IOException {
dataOut.writeUTF(object); dataOut.writeUTF(object);
} }
@ -43,7 +44,7 @@ public class StringMarshaller implements Marshaller<String> {
* @return unmarshalled object * @return unmarshalled object
* @throws IOException * @throws IOException
*/ */
public String readPayload(DataInput dataIn) throws IOException{ public String readPayload(DataInput dataIn) throws IOException {
return dataIn.readUTF(); return dataIn.readUTF();
} }
} }

View File

@ -8,35 +8,32 @@ import org.apache.activemq.kaha.impl.data.RedoListener;
public interface DataManager { public interface DataManager {
String getName(); String getName();
Object readItem(Marshaller marshaller, StoreLocation item) Object readItem(Marshaller marshaller, StoreLocation item) throws IOException;
throws IOException;
StoreLocation storeDataItem(Marshaller marshaller, Object payload) StoreLocation storeDataItem(Marshaller marshaller, Object payload) throws IOException;
throws IOException;
StoreLocation storeRedoItem(Object payload) throws IOException; StoreLocation storeRedoItem(Object payload) throws IOException;
void updateItem(StoreLocation location, Marshaller marshaller, void updateItem(StoreLocation location, Marshaller marshaller, Object payload) throws IOException;
Object payload) throws IOException;
void recoverRedoItems(RedoListener listener) throws IOException; void recoverRedoItems(RedoListener listener) throws IOException;
void close() throws IOException; void close() throws IOException;
void force() throws IOException; void force() throws IOException;
boolean delete() throws IOException; boolean delete() throws IOException;
void addInterestInFile(int file) throws IOException; void addInterestInFile(int file) throws IOException;
void removeInterestInFile(int file) throws IOException; void removeInterestInFile(int file) throws IOException;
void consolidateDataFiles() throws IOException; void consolidateDataFiles() throws IOException;
Marshaller getRedoMarshaller(); Marshaller getRedoMarshaller();
void setRedoMarshaller(Marshaller redoMarshaller); void setRedoMarshaller(Marshaller redoMarshaller);
} }

View File

@ -35,58 +35,55 @@ import org.apache.commons.logging.LogFactory;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
/** /**
* A container of roots for other Containers * A container of roots for other Containers
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
class IndexRootContainer { class IndexRootContainer {
private static final Log log=LogFactory.getLog(IndexRootContainer.class); private static final Log log = LogFactory.getLog(IndexRootContainer.class);
protected static final Marshaller rootMarshaller = Store.ObjectMarshaller; protected static final Marshaller rootMarshaller = Store.ObjectMarshaller;
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 map = new ConcurrentHashMap();
protected LinkedList list = new LinkedList(); protected LinkedList list = new LinkedList();
IndexRootContainer(IndexItem root, IndexManager im, DataManager dfm) throws IOException {
IndexRootContainer(IndexItem root,IndexManager im,DataManager dfm) throws IOException{ this.root = root;
this.root=root; this.indexManager = im;
this.indexManager=im; this.dataManager = dfm;
this.dataManager=dfm; long nextItem = root.getNextItem();
long nextItem=root.getNextItem(); while (nextItem != Item.POSITION_NOT_SET) {
while(nextItem!=Item.POSITION_NOT_SET){ StoreEntry item = indexManager.getIndex(nextItem);
StoreEntry item=indexManager.getIndex(nextItem); StoreLocation data = item.getKeyDataItem();
StoreLocation data=item.getKeyDataItem(); Object key = dataManager.readItem(rootMarshaller, data);
Object key = dataManager.readItem(rootMarshaller,data); map.put(key, item);
map.put(key,item);
list.add(item); list.add(item);
nextItem=item.getNextItem(); nextItem = item.getNextItem();
dataManager.addInterestInFile(item.getKeyFile()); dataManager.addInterestInFile(item.getKeyFile());
} }
} }
Set getKeys(){ Set getKeys() {
return map.keySet(); return map.keySet();
} }
IndexItem addRoot(IndexManager containerIndexManager, ContainerId key) throws IOException {
if (map.containsKey(key)) {
IndexItem addRoot(IndexManager containerIndexManager,ContainerId key) throws IOException{ removeRoot(containerIndexManager, key);
if (map.containsKey(key)){
removeRoot(containerIndexManager,key);
} }
StoreLocation data = dataManager.storeDataItem(rootMarshaller, key); StoreLocation data = dataManager.storeDataItem(rootMarshaller, key);
IndexItem newRoot = indexManager.createNewIndex(); IndexItem newRoot = indexManager.createNewIndex();
newRoot.setKeyData(data); newRoot.setKeyData(data);
IndexItem containerRoot = containerIndexManager.createNewIndex(); IndexItem containerRoot = containerIndexManager.createNewIndex();
containerIndexManager.storeIndex(containerRoot); containerIndexManager.storeIndex(containerRoot);
newRoot.setValueOffset(containerRoot.getOffset()); newRoot.setValueOffset(containerRoot.getOffset());
IndexItem last=list.isEmpty()?null:(IndexItem) list.getLast(); IndexItem last = list.isEmpty() ? null : (IndexItem)list.getLast();
last=last==null?root:last; last = last == null ? root : last;
long prev=last.getOffset(); long prev = last.getOffset();
newRoot.setPreviousItem(prev); newRoot.setPreviousItem(prev);
indexManager.storeIndex(newRoot); indexManager.storeIndex(newRoot);
last.setNextItem(newRoot.getOffset()); last.setNextItem(newRoot.getOffset());
@ -95,25 +92,25 @@ class IndexRootContainer {
list.add(newRoot); list.add(newRoot);
return containerRoot; return containerRoot;
} }
void removeRoot(IndexManager containerIndexManager,ContainerId key) throws IOException{ void removeRoot(IndexManager containerIndexManager, ContainerId key) throws IOException {
StoreEntry oldRoot=(StoreEntry)map.remove(key); StoreEntry oldRoot = (StoreEntry)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
IndexItem containerRoot=containerIndexManager.getIndex(oldRoot.getValueOffset()); IndexItem containerRoot = containerIndexManager.getIndex(oldRoot.getValueOffset());
if(containerRoot!=null){ if (containerRoot != null) {
containerIndexManager.freeIndex(containerRoot); containerIndexManager.freeIndex(containerRoot);
} }
int index=list.indexOf(oldRoot); int index = list.indexOf(oldRoot);
IndexItem prev=index>0?(IndexItem)list.get(index-1):root; IndexItem prev = index > 0 ? (IndexItem)list.get(index - 1) : root;
prev=prev==null?root:prev; prev = prev == null ? root : prev;
IndexItem next=index<(list.size()-1)?(IndexItem)list.get(index+1):null; IndexItem next = index < (list.size() - 1) ? (IndexItem)list.get(index + 1) : null;
if(next!=null){ if (next != null) {
prev.setNextItem(next.getOffset()); prev.setNextItem(next.getOffset());
next.setPreviousItem(prev.getOffset()); next.setPreviousItem(prev.getOffset());
indexManager.updateIndexes(next); indexManager.updateIndexes(next);
}else{ } else {
prev.setNextItem(Item.POSITION_NOT_SET); prev.setNextItem(Item.POSITION_NOT_SET);
} }
indexManager.updateIndexes(prev); indexManager.updateIndexes(prev);
@ -121,19 +118,17 @@ class IndexRootContainer {
indexManager.freeIndex((IndexItem)oldRoot); indexManager.freeIndex((IndexItem)oldRoot);
} }
} }
IndexItem getRoot(IndexManager containerIndexManager,ContainerId key) throws IOException{ IndexItem getRoot(IndexManager containerIndexManager, ContainerId key) throws IOException {
StoreEntry index = (StoreEntry) map.get(key); StoreEntry index = (StoreEntry)map.get(key);
if (index != null){ if (index != null) {
return containerIndexManager.getIndex(index.getValueOffset()); return containerIndexManager.getIndex(index.getValueOffset());
} }
return null; return null;
} }
boolean doesRootExist(Object key){ boolean doesRootExist(Object key) {
return map.containsKey(key); return map.containsKey(key);
} }
} }

View File

@ -18,27 +18,25 @@ package org.apache.activemq.kaha.impl;
import java.io.IOException; import java.io.IOException;
/** /**
* Exception thrown if the store is in use by another application * Exception thrown if the store is in use by another application
* *
* @version $Revision: 1.1.1.1 $ * @version $Revision: 1.1.1.1 $
*/ */
public class StoreLockedExcpetion extends IOException{ public class StoreLockedExcpetion extends IOException {
private static final long serialVersionUID=3857646689671366926L; private static final long serialVersionUID = 3857646689671366926L;
/** /**
* Default Constructor * Default Constructor
*/ */
public StoreLockedExcpetion(){ public StoreLockedExcpetion() {
} }
/** /**
* @param s * @param s
*/ */
public StoreLockedExcpetion(String s){ public StoreLockedExcpetion(String s) {
super(s); super(s);
} }
} }

View File

@ -23,129 +23,130 @@ import java.util.concurrent.ConcurrentHashMap;
import org.apache.activemq.kaha.impl.async.DataFileAppender.WriteCommand; import org.apache.activemq.kaha.impl.async.DataFileAppender.WriteCommand;
import org.apache.activemq.kaha.impl.async.DataFileAppender.WriteKey; import org.apache.activemq.kaha.impl.async.DataFileAppender.WriteKey;
import org.apache.activemq.util.ByteSequence; import org.apache.activemq.util.ByteSequence;
/** /**
* Optimized Store reader and updater. Single threaded and synchronous. Use in conjunction * Optimized Store reader and updater. Single threaded and synchronous. Use in
* with the DataFileAccessorPool of concurrent use. * conjunction with the DataFileAccessorPool of concurrent use.
* *
* @version $Revision: 1.1.1.1 $ * @version $Revision: 1.1.1.1 $
*/ */
final class DataFileAccessor { final class DataFileAccessor {
private final DataFile dataFile; private final DataFile dataFile;
private final ConcurrentHashMap<WriteKey, WriteCommand> inflightWrites; private final ConcurrentHashMap<WriteKey, WriteCommand> inflightWrites;
private final RandomAccessFile file; private final RandomAccessFile file;
private boolean disposed; private boolean disposed;
/** /**
* Construct a Store reader * Construct a Store reader
* *
* @param fileId * @param fileId
* @throws IOException * @throws IOException
*/ */
public DataFileAccessor(AsyncDataManager dataManager, DataFile dataFile) throws IOException{ public DataFileAccessor(AsyncDataManager dataManager, DataFile dataFile) throws IOException {
this.dataFile = dataFile; this.dataFile = dataFile;
this.inflightWrites = dataManager.getInflightWrites(); this.inflightWrites = dataManager.getInflightWrites();
this.file = dataFile.openRandomAccessFile(false); this.file = dataFile.openRandomAccessFile(false);
} }
public DataFile getDataFile() { public DataFile getDataFile() {
return dataFile; return dataFile;
} }
public void dispose() { public void dispose() {
if( disposed ) if (disposed)
return; return;
disposed=true; disposed = true;
try { try {
dataFile.closeRandomAccessFile(file); dataFile.closeRandomAccessFile(file);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
public ByteSequence readRecord(Location location) throws IOException { public ByteSequence readRecord(Location location) throws IOException {
if( !location.isValid() )
throw new IOException("Invalid location: "+location);
WriteCommand asyncWrite = (WriteCommand) inflightWrites.get(new WriteKey(location));
if( asyncWrite!= null ) {
return asyncWrite.data;
}
try { if (!location.isValid())
throw new IOException("Invalid location: " + location);
if( location.getSize()==Location.NOT_SET ) { WriteCommand asyncWrite = (WriteCommand)inflightWrites.get(new WriteKey(location));
file.seek(location.getOffset()); if (asyncWrite != null) {
location.setSize(file.readInt()); return asyncWrite.data;
file.seek(location.getOffset()+AsyncDataManager.ITEM_HEAD_SPACE); }
} else {
file.seek(location.getOffset()+AsyncDataManager.ITEM_HEAD_SPACE);
}
byte[] data=new byte[location.getSize()-AsyncDataManager.ITEM_HEAD_FOOT_SPACE];
file.readFully(data);
return new ByteSequence(data, 0, data.length);
} catch (RuntimeException e) { try {
throw new IOException("Invalid location: "+location+", : "+e);
} if (location.getSize() == Location.NOT_SET) {
file.seek(location.getOffset());
location.setSize(file.readInt());
file.seek(location.getOffset() + AsyncDataManager.ITEM_HEAD_SPACE);
} else {
file.seek(location.getOffset() + AsyncDataManager.ITEM_HEAD_SPACE);
}
byte[] data = new byte[location.getSize() - AsyncDataManager.ITEM_HEAD_FOOT_SPACE];
file.readFully(data);
return new ByteSequence(data, 0, data.length);
} catch (RuntimeException e) {
throw new IOException("Invalid location: " + location + ", : " + e);
}
} }
public void readLocationDetails(Location location) throws IOException { public void readLocationDetails(Location location) throws IOException {
WriteCommand asyncWrite = (WriteCommand) inflightWrites.get(new WriteKey(location)); WriteCommand asyncWrite = (WriteCommand)inflightWrites.get(new WriteKey(location));
if( asyncWrite!= null ) { if (asyncWrite != null) {
location.setSize(asyncWrite.location.getSize()); location.setSize(asyncWrite.location.getSize());
location.setType(asyncWrite.location.getType()); location.setType(asyncWrite.location.getType());
} else { } else {
file.seek(location.getOffset()); file.seek(location.getOffset());
location.setSize(file.readInt()); location.setSize(file.readInt());
location.setType(file.readByte()); location.setType(file.readByte());
} }
} }
public boolean readLocationDetailsAndValidate(Location location) { public boolean readLocationDetailsAndValidate(Location location) {
try { try {
WriteCommand asyncWrite = (WriteCommand) inflightWrites.get(new WriteKey(location)); WriteCommand asyncWrite = (WriteCommand)inflightWrites.get(new WriteKey(location));
if( asyncWrite!= null ) { if (asyncWrite != null) {
location.setSize(asyncWrite.location.getSize()); location.setSize(asyncWrite.location.getSize());
location.setType(asyncWrite.location.getType()); location.setType(asyncWrite.location.getType());
} else { } else {
file.seek(location.getOffset()); file.seek(location.getOffset());
location.setSize(file.readInt()); location.setSize(file.readInt());
location.setType(file.readByte()); location.setType(file.readByte());
byte data[] = new byte[3];
file.seek(location.getOffset()+AsyncDataManager.ITEM_HEAD_OFFSET_TO_SOR);
file.readFully(data);
if( data[0] != AsyncDataManager.ITEM_HEAD_SOR[0] ||
data[1] != AsyncDataManager.ITEM_HEAD_SOR[1] ||
data[2] != AsyncDataManager.ITEM_HEAD_SOR[2] ) {
return false;
}
file.seek(location.getOffset()+location.getSize()-AsyncDataManager.ITEM_FOOT_SPACE);
file.readFully(data);
if( data[0] != AsyncDataManager.ITEM_HEAD_EOR[0] ||
data[1] != AsyncDataManager.ITEM_HEAD_EOR[1] ||
data[2] != AsyncDataManager.ITEM_HEAD_EOR[2] ) {
return false;
}
}
} catch (IOException e) {
return false;
}
return true;
}
public void updateRecord(Location location, ByteSequence data, boolean sync) throws IOException { byte data[] = new byte[3];
file.seek(location.getOffset() + AsyncDataManager.ITEM_HEAD_OFFSET_TO_SOR);
file.seek(location.getOffset()+AsyncDataManager.ITEM_HEAD_SPACE); file.readFully(data);
int size = Math.min(data.getLength(), location.getSize()); if (data[0] != AsyncDataManager.ITEM_HEAD_SOR[0]
file.write(data.getData(), data.getOffset(), size); || data[1] != AsyncDataManager.ITEM_HEAD_SOR[1]
if( sync ) { || data[2] != AsyncDataManager.ITEM_HEAD_SOR[2]) {
file.getFD().sync(); return false;
} }
file.seek(location.getOffset() + location.getSize() - AsyncDataManager.ITEM_FOOT_SPACE);
} file.readFully(data);
if (data[0] != AsyncDataManager.ITEM_HEAD_EOR[0]
|| data[1] != AsyncDataManager.ITEM_HEAD_EOR[1]
|| data[2] != AsyncDataManager.ITEM_HEAD_EOR[2]) {
return false;
}
}
} catch (IOException e) {
return false;
}
return true;
}
public void updateRecord(Location location, ByteSequence data, boolean sync) throws IOException {
file.seek(location.getOffset() + AsyncDataManager.ITEM_HEAD_SPACE);
int size = Math.min(data.getLength(), location.getSize());
file.write(data.getData(), data.getOffset(), size);
if (sync) {
file.getFD().sync();
}
}
} }

View File

@ -27,348 +27,351 @@ import org.apache.activemq.util.DataByteArrayOutputStream;
import org.apache.activemq.util.LinkedNode; import org.apache.activemq.util.LinkedNode;
/** /**
* An optimized writer to do batch appends to a data file. This object is thread safe * An optimized writer to do batch appends to a data file. This object is thread
* and gains throughput as you increase the number of concurrent writes it does. * safe and gains throughput as you increase the number of concurrent writes it
* does.
* *
* @version $Revision: 1.1.1.1 $ * @version $Revision: 1.1.1.1 $
*/ */
class DataFileAppender { class DataFileAppender {
protected static final byte []RESERVED_SPACE= new byte[AsyncDataManager.ITEM_HEAD_RESERVED_SPACE];
protected static final String SHUTDOWN_COMMAND = "SHUTDOWN";
int MAX_WRITE_BATCH_SIZE = 1024*1024*4;
static public class WriteKey {
private final int file;
private final long offset;
private final int hash;
public WriteKey(Location item){ protected static final byte[] RESERVED_SPACE = new byte[AsyncDataManager.ITEM_HEAD_RESERVED_SPACE];
file = item.getDataFileId(); protected static final String SHUTDOWN_COMMAND = "SHUTDOWN";
offset = item.getOffset(); int MAX_WRITE_BATCH_SIZE = 1024 * 1024 * 4;
// TODO: see if we can build a better hash
hash = (int) (file ^ offset); static public class WriteKey {
} private final int file;
private final long offset;
public int hashCode() { private final int hash;
return hash;
} public WriteKey(Location item) {
file = item.getDataFileId();
public boolean equals(Object obj){ offset = item.getOffset();
if(obj instanceof WriteKey){ // TODO: see if we can build a better hash
WriteKey di=(WriteKey)obj; hash = (int)(file ^ offset);
return di.file==file&&di.offset==offset; }
public int hashCode() {
return hash;
}
public boolean equals(Object obj) {
if (obj instanceof WriteKey) {
WriteKey di = (WriteKey)obj;
return di.file == file && di.offset == offset;
} }
return false; return false;
} }
}
public class WriteBatch {
public final DataFile dataFile;
public final WriteCommand first;
public final CountDownLatch latch = new CountDownLatch(1);
public int size;
public WriteBatch(DataFile dataFile, WriteCommand write) throws IOException {
this.dataFile=dataFile;
this.first=write;
size+=write.location.getSize();
}
public boolean canAppend(DataFile dataFile, WriteCommand write) {
if( dataFile != this.dataFile )
return false;
if( size+write.location.getSize() >= MAX_WRITE_BATCH_SIZE )
return false;
return true;
}
public void append(WriteCommand write) throws IOException {
this.first.getTailNode().linkAfter(write);
size+=write.location.getSize();
}
}
public static class WriteCommand extends LinkedNode {
public final Location location;
public final ByteSequence data;
final boolean sync;
public WriteCommand(Location location, ByteSequence data, boolean sync) {
this.location = location;
this.data = data;
this.sync = sync;
}
} }
protected final AsyncDataManager dataManager; public class WriteBatch {
public final DataFile dataFile;
public final WriteCommand first;
public final CountDownLatch latch = new CountDownLatch(1);
public int size;
public WriteBatch(DataFile dataFile, WriteCommand write) throws IOException {
this.dataFile = dataFile;
this.first = write;
size += write.location.getSize();
}
public boolean canAppend(DataFile dataFile, WriteCommand write) {
if (dataFile != this.dataFile)
return false;
if (size + write.location.getSize() >= MAX_WRITE_BATCH_SIZE)
return false;
return true;
}
public void append(WriteCommand write) throws IOException {
this.first.getTailNode().linkAfter(write);
size += write.location.getSize();
}
}
public static class WriteCommand extends LinkedNode {
public final Location location;
public final ByteSequence data;
final boolean sync;
public WriteCommand(Location location, ByteSequence data, boolean sync) {
this.location = location;
this.data = data;
this.sync = sync;
}
}
protected final AsyncDataManager dataManager;
protected final ConcurrentHashMap<WriteKey, WriteCommand> inflightWrites; protected final ConcurrentHashMap<WriteKey, WriteCommand> inflightWrites;
protected final Object enqueueMutex = new Object(); protected final Object enqueueMutex = new Object();
protected WriteBatch nextWriteBatch; protected WriteBatch nextWriteBatch;
private boolean running; private boolean running;
protected boolean shutdown; protected boolean shutdown;
protected IOException firstAsyncException; protected IOException firstAsyncException;
protected final CountDownLatch shutdownDone = new CountDownLatch(1); protected final CountDownLatch shutdownDone = new CountDownLatch(1);
private Thread thread; private Thread thread;
/** /**
* Construct a Store writer * Construct a Store writer
* *
* @param fileId * @param fileId
*/ */
public DataFileAppender(AsyncDataManager dataManager){ public DataFileAppender(AsyncDataManager dataManager) {
this.dataManager=dataManager; this.dataManager = dataManager;
this.inflightWrites = this.dataManager.getInflightWrites(); this.inflightWrites = this.dataManager.getInflightWrites();
} }
/** /**
* @param type * @param type
* @param marshaller * @param marshaller
* @param payload * @param payload
* @param type * @param type
* @param sync * @param sync
* @return * @return
* @throws IOException * @throws IOException
* @throws * @throws
* @throws * @throws
*/ */
public Location storeItem(ByteSequence data, byte type, boolean sync) throws IOException { public Location storeItem(ByteSequence data, byte type, boolean sync) throws IOException {
// Write the packet our internal buffer.
int size = data.getLength()+AsyncDataManager.ITEM_HEAD_FOOT_SPACE;
final Location location=new Location();
location.setSize(size);
location.setType(type);
WriteBatch batch;
WriteCommand write = new WriteCommand(location, data, sync);
// Locate datafile and enqueue into the executor in sychronized block so that // Write the packet our internal buffer.
// writes get equeued onto the executor in order that they were assigned by int size = data.getLength() + AsyncDataManager.ITEM_HEAD_FOOT_SPACE;
final Location location = new Location();
location.setSize(size);
location.setType(type);
WriteBatch batch;
WriteCommand write = new WriteCommand(location, data, sync);
// Locate datafile and enqueue into the executor in sychronized block so
// that
// writes get equeued onto the executor in order that they were assigned
// by
// the data manager (which is basically just appending) // the data manager (which is basically just appending)
synchronized(this) { synchronized (this) {
// Find the position where this item will land at. // Find the position where this item will land at.
DataFile dataFile=dataManager.allocateLocation(location); DataFile dataFile = dataManager.allocateLocation(location);
batch = enqueue(dataFile, write); batch = enqueue(dataFile, write);
} }
location.setLatch(batch.latch); location.setLatch(batch.latch);
if( sync ) { if (sync) {
try { try {
batch.latch.await(); batch.latch.await();
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw new InterruptedIOException(); throw new InterruptedIOException();
} }
} else { } else {
inflightWrites.put(new WriteKey(location), write); inflightWrites.put(new WriteKey(location), write);
} }
return location; return location;
} }
private WriteBatch enqueue(DataFile dataFile, WriteCommand write) throws IOException { private WriteBatch enqueue(DataFile dataFile, WriteCommand write) throws IOException {
synchronized(enqueueMutex) { synchronized (enqueueMutex) {
WriteBatch rc=null; WriteBatch rc = null;
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;
thread = new Thread() { thread = new Thread() {
public void run() { public void run() {
processQueue(); processQueue();
} }
}; };
thread.setPriority(Thread.MAX_PRIORITY); thread.setPriority(Thread.MAX_PRIORITY);
thread.setDaemon(true); thread.setDaemon(true);
thread.setName("ActiveMQ Data File Writer"); thread.setName("ActiveMQ Data File Writer");
thread.start(); thread.start();
} }
if( nextWriteBatch == null ) { if (nextWriteBatch == null) {
nextWriteBatch = new WriteBatch(dataFile,write); nextWriteBatch = new WriteBatch(dataFile, write);
rc = nextWriteBatch; rc = nextWriteBatch;
enqueueMutex.notify(); enqueueMutex.notify();
} else { } else {
// Append to current batch if possible.. // Append to current batch if possible..
if( nextWriteBatch.canAppend(dataFile, write) ) { if (nextWriteBatch.canAppend(dataFile, write)) {
nextWriteBatch.append(write); nextWriteBatch.append(write);
rc = nextWriteBatch; rc = nextWriteBatch;
} else { } else {
// Otherwise wait for the queuedCommand to be null // Otherwise wait for the queuedCommand to be null
try { try {
while( nextWriteBatch!=null ) { while (nextWriteBatch != null) {
enqueueMutex.wait(); enqueueMutex.wait();
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw new InterruptedIOException(); throw new InterruptedIOException();
} }
if( shutdown ) { if (shutdown) {
throw new IOException("Async Writter Thread Shutdown"); throw new IOException("Async Writter Thread Shutdown");
} }
// Start a new batch. // Start a new batch.
nextWriteBatch = new WriteBatch(dataFile,write); nextWriteBatch = new WriteBatch(dataFile, write);
rc = nextWriteBatch; rc = nextWriteBatch;
enqueueMutex.notify(); enqueueMutex.notify();
} }
} }
return rc; return rc;
} }
} }
public void close() throws IOException { public void close() throws IOException {
synchronized( enqueueMutex ) { synchronized (enqueueMutex) {
if( shutdown == false ) { if (shutdown == false) {
shutdown = true; shutdown = true;
if( running ) { if (running) {
enqueueMutex.notifyAll(); enqueueMutex.notifyAll();
} else { } else {
shutdownDone.countDown(); shutdownDone.countDown();
} }
} }
} }
try { try {
shutdownDone.await(); shutdownDone.await();
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw new InterruptedIOException(); throw new InterruptedIOException();
} }
} }
/** /**
* The async processing loop that writes to the data files and * The async processing loop that writes to the data files and does the
* does the force calls. * force calls.
* *
* Since the file sync() call is the slowest of all the operations, * Since the file sync() call is the slowest of all the operations, this
* this algorithm tries to 'batch' or group together several file sync() requests * algorithm tries to 'batch' or group together several file sync() requests
* into a single file sync() call. The batching is accomplished attaching the * into a single file sync() call. The batching is accomplished attaching
* same CountDownLatch instance to every force request in a group. * the same CountDownLatch instance to every force request in a group.
* *
*/ */
protected void processQueue() { protected void processQueue() {
DataFile dataFile=null; DataFile dataFile = null;
RandomAccessFile file=null; RandomAccessFile file = null;
try { try {
DataByteArrayOutputStream buff = new DataByteArrayOutputStream(MAX_WRITE_BATCH_SIZE);
while( true ) {
Object o = null;
// Block till we get a command. DataByteArrayOutputStream buff = new DataByteArrayOutputStream(MAX_WRITE_BATCH_SIZE);
synchronized(enqueueMutex) { while (true) {
while( true ) {
if( shutdown ) { Object o = null;
o = SHUTDOWN_COMMAND;
break; // Block till we get a command.
} synchronized (enqueueMutex) {
if( nextWriteBatch!=null ) { while (true) {
o = nextWriteBatch; if (shutdown) {
nextWriteBatch=null; o = SHUTDOWN_COMMAND;
break; break;
} }
enqueueMutex.wait(); if (nextWriteBatch != null) {
} o = nextWriteBatch;
enqueueMutex.notify(); nextWriteBatch = null;
} break;
}
enqueueMutex.wait();
if( o == SHUTDOWN_COMMAND ) { }
break; enqueueMutex.notify();
} }
WriteBatch wb = (WriteBatch) o; if (o == SHUTDOWN_COMMAND) {
if( dataFile != wb.dataFile ) { break;
if( file!=null ) { }
dataFile.closeRandomAccessFile(file);
} WriteBatch wb = (WriteBatch)o;
dataFile = wb.dataFile; if (dataFile != wb.dataFile) {
file = dataFile.openRandomAccessFile(true); if (file != null) {
} dataFile.closeRandomAccessFile(file);
}
WriteCommand write = wb.first; dataFile = wb.dataFile;
file = dataFile.openRandomAccessFile(true);
// Write all the data. }
// Only need to seek to first location.. all others
// are in sequence. WriteCommand write = wb.first;
file.seek(write.location.getOffset());
// Write all the data.
// // Only need to seek to first location.. all others
// is it just 1 big write? // are in sequence.
if( wb.size == write.location.getSize() ) { file.seek(write.location.getOffset());
// Just write it directly.. //
file.writeInt(write.location.getSize()); // is it just 1 big write?
file.writeByte(write.location.getType()); if (wb.size == write.location.getSize()) {
file.write(RESERVED_SPACE);
file.write(AsyncDataManager.ITEM_HEAD_SOR); // Just write it directly..
file.write(write.data.getData(),write.data.getOffset(), write.data.getLength()); file.writeInt(write.location.getSize());
file.write(AsyncDataManager.ITEM_HEAD_EOR); file.writeByte(write.location.getType());
file.write(RESERVED_SPACE);
} else { file.write(AsyncDataManager.ITEM_HEAD_SOR);
file.write(write.data.getData(), write.data.getOffset(), write.data.getLength());
// Combine the smaller writes into 1 big buffer file.write(AsyncDataManager.ITEM_HEAD_EOR);
while( write!=null ) {
} else {
buff.writeInt(write.location.getSize());
buff.writeByte(write.location.getType()); // Combine the smaller writes into 1 big buffer
buff.write(RESERVED_SPACE); while (write != null) {
buff.write(AsyncDataManager.ITEM_HEAD_SOR);
buff.write(write.data.getData(),write.data.getOffset(), write.data.getLength()); buff.writeInt(write.location.getSize());
buff.write(AsyncDataManager.ITEM_HEAD_EOR); buff.writeByte(write.location.getType());
buff.write(RESERVED_SPACE);
write = (WriteCommand) write.getNext(); buff.write(AsyncDataManager.ITEM_HEAD_SOR);
} buff.write(write.data.getData(), write.data.getOffset(), write.data.getLength());
buff.write(AsyncDataManager.ITEM_HEAD_EOR);
// Now do the 1 big write.
ByteSequence sequence = buff.toByteSequence(); write = (WriteCommand)write.getNext();
file.write(sequence.getData(), sequence.getOffset(), sequence.getLength()); }
buff.reset();
} // Now do the 1 big write.
ByteSequence sequence = buff.toByteSequence();
file.getFD().sync(); file.write(sequence.getData(), sequence.getOffset(), sequence.getLength());
buff.reset();
WriteCommand lastWrite = (WriteCommand) wb.first.getTailNode(); }
dataManager.setLastAppendLocation( lastWrite.location );
file.getFD().sync();
// Signal any waiting threads that the write is on disk.
wb.latch.countDown(); WriteCommand lastWrite = (WriteCommand)wb.first.getTailNode();
dataManager.setLastAppendLocation(lastWrite.location);
// Now that the data is on disk, remove the writes from the in flight
// cache. // Signal any waiting threads that the write is on disk.
write = wb.first; wb.latch.countDown();
while( write!=null ) {
if( !write.sync ) { // Now that the data is on disk, remove the writes from the in
inflightWrites.remove(new WriteKey(write.location)); // flight
} // cache.
write = (WriteCommand) write.getNext(); write = wb.first;
} while (write != null) {
} if (!write.sync) {
buff.close(); inflightWrites.remove(new WriteKey(write.location));
} catch (IOException e) { }
synchronized( enqueueMutex ) { write = (WriteCommand)write.getNext();
firstAsyncException = e; }
} }
} catch (InterruptedException e) { buff.close();
} finally { } catch (IOException e) {
try { synchronized (enqueueMutex) {
if( file!=null ) { firstAsyncException = e;
dataFile.closeRandomAccessFile(file); }
} } catch (InterruptedException e) {
} catch (IOException e) { } finally {
} try {
shutdownDone.countDown(); if (file != null) {
} dataFile.closeRandomAccessFile(file);
}
} catch (IOException e) {
}
shutdownDone.countDown();
}
} }
} }

View File

@ -32,125 +32,124 @@ 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 class StoreLocationFacade implements StoreLocation { private static class StoreLocationFacade implements StoreLocation {
private final Location location; private final Location location;
public StoreLocationFacade(Location location) { public StoreLocationFacade(Location location) {
this.location = location; this.location = location;
} }
public int getFile() { public int getFile() {
return location.getDataFileId(); return location.getDataFileId();
} }
public long getOffset() { public long getOffset() {
return location.getOffset(); return location.getOffset();
} }
public int getSize() { public int getSize() {
return location.getSize(); return location.getSize();
} }
public Location getLocation() { public Location getLocation() {
return location; return location;
} }
} }
static private StoreLocation convertToStoreLocation(Location location) { static private StoreLocation convertToStoreLocation(Location location) {
if(location==null) if (location == null)
return null; return null;
return new StoreLocationFacade(location); return new StoreLocationFacade(location);
} }
static private Location convertFromStoreLocation(StoreLocation location) {
if(location==null)
return null;
if( location.getClass()== StoreLocationFacade.class )
return ((StoreLocationFacade)location).getLocation();
Location l = new Location();
l.setOffset((int) location.getOffset());
l.setSize(location.getSize());
l.setDataFileId(location.getFile());
return l;
}
static final private ByteSequence FORCE_COMMAND = new ByteSequence(new byte[]{'F', 'O', 'R', 'C', 'E'}); static private Location convertFromStoreLocation(StoreLocation location) {
AsyncDataManager dataManager; if (location == null)
private final String name; return null;
private Marshaller redoMarshaller;
if (location.getClass() == StoreLocationFacade.class)
return ((StoreLocationFacade)location).getLocation();
public DataManagerFacade(AsyncDataManager dataManager, String name) {
this.dataManager=dataManager; Location l = new Location();
this.name = name; l.setOffset((int)location.getOffset());
} l.setSize(location.getSize());
l.setDataFileId(location.getFile());
public Object readItem(Marshaller marshaller, StoreLocation location) throws IOException { return l;
ByteSequence sequence = dataManager.read(convertFromStoreLocation(location)); }
DataByteArrayInputStream dataIn = new DataByteArrayInputStream(sequence);
static final private 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 {
ByteSequence sequence = dataManager.read(convertFromStoreLocation(location));
DataByteArrayInputStream dataIn = new DataByteArrayInputStream(sequence);
return marshaller.readPayload(dataIn); return marshaller.readPayload(dataIn);
} }
public StoreLocation storeDataItem(Marshaller marshaller, Object payload) throws IOException {
final DataByteArrayOutputStream buffer = new DataByteArrayOutputStream();
marshaller.writePayload(payload, buffer);
ByteSequence data = buffer.toByteSequence();
return convertToStoreLocation(dataManager.write(data, (byte)1, false));
}
public StoreLocation storeDataItem(Marshaller marshaller, Object payload) throws IOException { public void force() throws IOException {
final DataByteArrayOutputStream buffer = new DataByteArrayOutputStream(); dataManager.write(FORCE_COMMAND, (byte)2, true);
marshaller.writePayload(payload,buffer); }
ByteSequence data = buffer.toByteSequence();
return convertToStoreLocation(dataManager.write(data, (byte)1, false));
}
public void updateItem(StoreLocation location, Marshaller marshaller, Object payload) throws IOException {
final DataByteArrayOutputStream buffer = new DataByteArrayOutputStream();
marshaller.writePayload(payload, buffer);
ByteSequence data = buffer.toByteSequence();
dataManager.update(convertFromStoreLocation(location), data, false);
}
public void force() throws IOException { public void close() throws IOException {
dataManager.write(FORCE_COMMAND, (byte)2, true); dataManager.close();
} }
public void updateItem(StoreLocation location, Marshaller marshaller, Object payload) throws IOException { public void consolidateDataFiles() throws IOException {
final DataByteArrayOutputStream buffer = new DataByteArrayOutputStream(); dataManager.consolidateDataFiles();
marshaller.writePayload(payload,buffer); }
ByteSequence data = buffer.toByteSequence();
dataManager.update(convertFromStoreLocation(location), data, false);
}
public void close() throws IOException {
dataManager.close();
}
public void consolidateDataFiles() throws IOException { public boolean delete() throws IOException {
dataManager.consolidateDataFiles(); return dataManager.delete();
} }
public boolean delete() throws IOException { public void addInterestInFile(int file) throws IOException {
return dataManager.delete(); dataManager.addInterestInFile(file);
} }
public void addInterestInFile(int file) throws IOException {
dataManager.addInterestInFile(file);
}
public void removeInterestInFile(int file) throws IOException {
dataManager.removeInterestInFile(file);
}
public void recoverRedoItems(RedoListener listener) throws IOException { public void removeInterestInFile(int file) throws IOException {
throw new RuntimeException("Not Implemented.."); dataManager.removeInterestInFile(file);
} }
public StoreLocation storeRedoItem(Object payload) throws IOException {
throw new RuntimeException("Not Implemented..");
}
public Marshaller getRedoMarshaller() { public void recoverRedoItems(RedoListener listener) throws IOException {
return redoMarshaller; throw new RuntimeException("Not Implemented..");
} }
public void setRedoMarshaller(Marshaller redoMarshaller) {
this.redoMarshaller = redoMarshaller;
}
public String getName() { public StoreLocation storeRedoItem(Object payload) throws IOException {
return name; throw new RuntimeException("Not Implemented..");
} }
public Marshaller getRedoMarshaller() {
return redoMarshaller;
}
public void setRedoMarshaller(Marshaller redoMarshaller) {
this.redoMarshaller = redoMarshaller;
}
public String getName() {
return name;
}
} }

View File

@ -33,75 +33,77 @@ import org.apache.activemq.util.ByteSequence;
*/ */
public final class JournalFacade implements Journal { public final class JournalFacade implements Journal {
public static class RecordLocationFacade implements RecordLocation {
public static class RecordLocationFacade implements RecordLocation { private final Location location;
private final Location location;
public RecordLocationFacade(Location location) { public RecordLocationFacade(Location location) {
this.location = location; this.location = location;
} }
public Location getLocation() { public Location getLocation() {
return location; return location;
} }
public int compareTo(Object o) { public int compareTo(Object o) {
RecordLocationFacade rlf = (RecordLocationFacade)o; RecordLocationFacade rlf = (RecordLocationFacade)o;
int rc = location.compareTo(rlf.location); int rc = location.compareTo(rlf.location);
return rc; return rc;
} }
} }
static private RecordLocation convertToRecordLocation(Location location) { static private RecordLocation convertToRecordLocation(Location location) {
if(location==null) if (location == null)
return null; return null;
return new RecordLocationFacade(location); return new RecordLocationFacade(location);
} }
static private Location convertFromRecordLocation(RecordLocation location) {
if(location==null)
return null;
return ((RecordLocationFacade)location).getLocation();
}
AsyncDataManager dataManager; static private Location convertFromRecordLocation(RecordLocation location) {
public JournalFacade(AsyncDataManager dataManager) {
this.dataManager = dataManager;
}
public void close() throws IOException { if (location == null)
dataManager.close(); return null;
}
public RecordLocation getMark() throws IllegalStateException { return ((RecordLocationFacade)location).getLocation();
return convertToRecordLocation(dataManager.getMark()); }
}
public RecordLocation getNextRecordLocation(RecordLocation location) throws InvalidRecordLocationException, IOException, IllegalStateException { AsyncDataManager dataManager;
return convertToRecordLocation(dataManager.getNextLocation(convertFromRecordLocation(location)));
}
public Packet read(RecordLocation location) throws InvalidRecordLocationException, IOException, IllegalStateException { public JournalFacade(AsyncDataManager dataManager) {
ByteSequence rc = dataManager.read(convertFromRecordLocation(location)); this.dataManager = dataManager;
if( rc == null ) }
return null;
return new ByteArrayPacket(rc.getData(), rc.getOffset(), rc.getLength());
}
public void setJournalEventListener(JournalEventListener listener) throws IllegalStateException { public void close() throws IOException {
} dataManager.close();
}
public void setMark(RecordLocation location, boolean sync) throws InvalidRecordLocationException, IOException, IllegalStateException { public RecordLocation getMark() throws IllegalStateException {
dataManager.setMark(convertFromRecordLocation(location), sync); return convertToRecordLocation(dataManager.getMark());
} }
public RecordLocation getNextRecordLocation(RecordLocation location)
throws InvalidRecordLocationException, IOException, IllegalStateException {
return convertToRecordLocation(dataManager.getNextLocation(convertFromRecordLocation(location)));
}
public Packet read(RecordLocation location) throws InvalidRecordLocationException, IOException,
IllegalStateException {
ByteSequence rc = dataManager.read(convertFromRecordLocation(location));
if (rc == null)
return null;
return new ByteArrayPacket(rc.getData(), rc.getOffset(), rc.getLength());
}
public void setJournalEventListener(JournalEventListener listener) throws IllegalStateException {
}
public void setMark(RecordLocation location, boolean sync) throws InvalidRecordLocationException,
IOException, IllegalStateException {
dataManager.setMark(convertFromRecordLocation(location), sync);
}
public RecordLocation write(Packet packet, boolean sync) throws IOException, IllegalStateException {
org.apache.activeio.packet.ByteSequence data = packet.asByteSequence();
ByteSequence sequence = new ByteSequence(data.getData(), data.getOffset(), data.getLength());
return convertToRecordLocation(dataManager.write(sequence, sync));
}
public RecordLocation write(Packet packet, boolean sync) throws IOException, IllegalStateException {
org.apache.activeio.packet.ByteSequence data = packet.asByteSequence();
ByteSequence sequence = new ByteSequence(data.getData(), data.getOffset(), data.getLength());
return convertToRecordLocation(dataManager.write(sequence, sync));
}
} }

View File

@ -27,121 +27,124 @@ import java.util.concurrent.CountDownLatch;
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public final class Location implements Comparable<Location> { public final class Location implements Comparable<Location> {
public static final byte MARK_TYPE=-1;
public static final byte USER_TYPE=1;
public static final byte NOT_SET_TYPE=0;
public static final int NOT_SET=-1;
private int dataFileId=NOT_SET; public static final byte MARK_TYPE = -1;
private int offset=NOT_SET; public static final byte USER_TYPE = 1;
private int size=NOT_SET; public static final byte NOT_SET_TYPE = 0;
private byte type=NOT_SET_TYPE; public static final int NOT_SET = -1;
private int dataFileId = NOT_SET;
private int offset = NOT_SET;
private int size = NOT_SET;
private byte type = NOT_SET_TYPE;
private CountDownLatch latch; private CountDownLatch latch;
public Location(){} public Location() {
}
Location(Location item) { Location(Location item) {
this.dataFileId = item.dataFileId; this.dataFileId = item.dataFileId;
this.offset = item.offset; this.offset = item.offset;
this.size = item.size; this.size = item.size;
this.type = item.type; this.type = item.type;
} }
boolean isValid(){ boolean isValid() {
return dataFileId != NOT_SET; return dataFileId != NOT_SET;
} }
/** /**
* @return the size of the data record including the header. * @return the size of the data record including the header.
*/ */
public int getSize(){ public int getSize() {
return size; return size;
} }
/** /**
* @param size the size of the data record including the header. * @param size the size of the data record including the header.
*/ */
public void setSize(int size){ public void setSize(int size) {
this.size=size; this.size = size;
} }
/** /**
* @return the size of the payload of the record. * @return the size of the payload of the record.
*/ */
public int getPaylodSize() { public int getPaylodSize() {
return size-AsyncDataManager.ITEM_HEAD_FOOT_SPACE; return size - AsyncDataManager.ITEM_HEAD_FOOT_SPACE;
}
public int getOffset(){
return offset;
}
public void setOffset(int offset){
this.offset=offset;
} }
public int getDataFileId(){ public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public int getDataFileId() {
return dataFileId; return dataFileId;
} }
public void setDataFileId(int file){ public void setDataFileId(int file) {
this.dataFileId=file; this.dataFileId = file;
} }
public byte getType() { public byte getType() {
return type; return type;
} }
public void setType(byte type) { public void setType(byte type) {
this.type = type; this.type = type;
} }
public String toString(){ public String toString() {
String result="offset = "+offset+", file = " + dataFileId + ", size = "+size + ", type = "+type; String result = "offset = " + offset + ", file = " + dataFileId + ", size = " + size + ", type = "
+ type;
return result; return result;
} }
public void writeExternal(DataOutput dos) throws IOException { public void writeExternal(DataOutput dos) throws IOException {
dos.writeInt(dataFileId); dos.writeInt(dataFileId);
dos.writeInt(offset); dos.writeInt(offset);
dos.writeInt(size); dos.writeInt(size);
dos.writeByte(type); dos.writeByte(type);
} }
public void readExternal(DataInput dis) throws IOException { public void readExternal(DataInput dis) throws IOException {
dataFileId = dis.readInt(); dataFileId = dis.readInt();
offset = dis.readInt(); offset = dis.readInt();
size = dis.readInt(); size = dis.readInt();
type = dis.readByte(); type = dis.readByte();
} }
public CountDownLatch getLatch() { public CountDownLatch getLatch() {
return latch; return latch;
} }
public void setLatch(CountDownLatch latch) {
this.latch = latch; public void setLatch(CountDownLatch latch) {
} this.latch = latch;
}
public int compareTo(Location o) {
Location l = (Location)o;
if (dataFileId == l.dataFileId) {
int rc = offset - l.offset;
return rc;
}
return dataFileId - l.dataFileId;
}
public int compareTo(Location o) {
Location l = (Location)o;
if( dataFileId == l.dataFileId ) {
int rc = offset-l.offset;
return rc;
}
return dataFileId - l.dataFileId;
}
public boolean equals(Object o) { public boolean equals(Object o) {
boolean result = false; boolean result = false;
if (o instanceof Location) { if (o instanceof Location) {
result = compareTo((Location)o)==0; result = compareTo((Location)o) == 0;
} }
return result; return result;
} }
public int hashCode() { public int hashCode() {
return dataFileId ^ offset; return dataFileId ^ offset;
} }
} }

View File

@ -22,191 +22,194 @@ import java.nio.ByteBuffer;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
/** /**
* An AsyncDataFileAppender that uses NIO ByteBuffers and File chanels to more efficently * An AsyncDataFileAppender that uses NIO ByteBuffers and File chanels to more
* copy data to files. * efficently copy data to files.
* *
* @version $Revision: 1.1.1.1 $ * @version $Revision: 1.1.1.1 $
*/ */
class NIODataFileAppender extends DataFileAppender { class NIODataFileAppender extends DataFileAppender {
public NIODataFileAppender(AsyncDataManager fileManager) {
super(fileManager);
}
/** public NIODataFileAppender(AsyncDataManager fileManager) {
* The async processing loop that writes to the data files and super(fileManager);
* does the force calls. }
/**
* The async processing loop that writes to the data files and does the
* force calls.
* *
* Since the file sync() call is the slowest of all the operations, * Since the file sync() call is the slowest of all the operations, this
* this algorithm tries to 'batch' or group together several file sync() requests * algorithm tries to 'batch' or group together several file sync() requests
* into a single file sync() call. The batching is accomplished attaching the * into a single file sync() call. The batching is accomplished attaching
* same CountDownLatch instance to every force request in a group. * the same CountDownLatch instance to every force request in a group.
* *
*/ */
protected void processQueue() { protected void processQueue() {
DataFile dataFile=null; DataFile dataFile = null;
RandomAccessFile file=null; RandomAccessFile file = null;
FileChannel channel=null; FileChannel channel = null;
try { try {
ByteBuffer header = ByteBuffer.allocateDirect(AsyncDataManager.ITEM_HEAD_SPACE);
ByteBuffer footer = ByteBuffer.allocateDirect(AsyncDataManager.ITEM_FOOT_SPACE);
ByteBuffer buffer = ByteBuffer.allocateDirect(MAX_WRITE_BATCH_SIZE);
// Populate the static parts of the headers and footers..
header.putInt(0); // size
header.put((byte) 0); // type
header.put(RESERVED_SPACE); // reserved
header.put(AsyncDataManager.ITEM_HEAD_SOR);
footer.put(AsyncDataManager.ITEM_HEAD_EOR);
while( true ) {
Object o = null;
// Block till we get a command. ByteBuffer header = ByteBuffer.allocateDirect(AsyncDataManager.ITEM_HEAD_SPACE);
synchronized(enqueueMutex) { ByteBuffer footer = ByteBuffer.allocateDirect(AsyncDataManager.ITEM_FOOT_SPACE);
while( true ) { ByteBuffer buffer = ByteBuffer.allocateDirect(MAX_WRITE_BATCH_SIZE);
if( shutdown ) {
o = SHUTDOWN_COMMAND;
break;
}
if( nextWriteBatch!=null ) {
o = nextWriteBatch;
nextWriteBatch=null;
break;
}
enqueueMutex.wait();
}
enqueueMutex.notify();
}
if( o == SHUTDOWN_COMMAND ) {
break;
}
WriteBatch wb = (WriteBatch) o;
if( dataFile != wb.dataFile ) {
if( file!=null ) {
dataFile.closeRandomAccessFile(file);
}
dataFile = wb.dataFile;
file = dataFile.openRandomAccessFile(true);
channel = file.getChannel();
}
WriteCommand write = wb.first;
// Write all the data.
// Only need to seek to first location.. all others
// are in sequence.
file.seek(write.location.getOffset());
//
// is it just 1 big write?
if( wb.size == write.location.getSize() ) {
header.clear();
header.putInt(write.location.getSize());
header.put(write.location.getType());
header.clear();
transfer(header, channel);
ByteBuffer source = ByteBuffer.wrap(write.data.getData(), write.data.getOffset(), write.data.getLength());
transfer(source, channel);
footer.clear();
transfer(footer, channel);
} else {
// Combine the smaller writes into 1 big buffer
while( write!=null ) {
header.clear();
header.putInt(write.location.getSize());
header.put(write.location.getType());
header.clear();
copy(header, buffer);
assert !header.hasRemaining();
ByteBuffer source = ByteBuffer.wrap(write.data.getData(), write.data.getOffset(), write.data.getLength());
copy(source, buffer);
assert !source.hasRemaining();
footer.clear(); // Populate the static parts of the headers and footers..
copy(footer, buffer); header.putInt(0); // size
assert !footer.hasRemaining(); header.put((byte)0); // type
header.put(RESERVED_SPACE); // reserved
write = (WriteCommand) write.getNext(); header.put(AsyncDataManager.ITEM_HEAD_SOR);
} footer.put(AsyncDataManager.ITEM_HEAD_EOR);
// Fully write out the buffer..
buffer.flip();
transfer(buffer, channel);
buffer.clear();
}
file.getChannel().force(false);
WriteCommand lastWrite = (WriteCommand) wb.first.getTailNode(); while (true) {
dataManager.setLastAppendLocation( lastWrite.location );
// Signal any waiting threads that the write is on disk. Object o = null;
if( wb.latch!=null ) {
wb.latch.countDown(); // Block till we get a command.
} synchronized (enqueueMutex) {
while (true) {
// Now that the data is on disk, remove the writes from the in flight if (shutdown) {
// cache. o = SHUTDOWN_COMMAND;
write = wb.first; break;
while( write!=null ) { }
if( !write.sync ) { if (nextWriteBatch != null) {
inflightWrites.remove(new WriteKey(write.location)); o = nextWriteBatch;
} nextWriteBatch = null;
write = (WriteCommand) write.getNext(); break;
} }
} enqueueMutex.wait();
}
} catch (IOException e) { enqueueMutex.notify();
synchronized( enqueueMutex ) { }
firstAsyncException = e;
} if (o == SHUTDOWN_COMMAND) {
} catch (InterruptedException e) { break;
} finally { }
try {
if( file!=null ) { WriteBatch wb = (WriteBatch)o;
dataFile.closeRandomAccessFile(file); if (dataFile != wb.dataFile) {
} if (file != null) {
} catch (IOException e) { dataFile.closeRandomAccessFile(file);
} }
shutdownDone.countDown(); dataFile = wb.dataFile;
} file = dataFile.openRandomAccessFile(true);
channel = file.getChannel();
}
WriteCommand write = wb.first;
// Write all the data.
// Only need to seek to first location.. all others
// are in sequence.
file.seek(write.location.getOffset());
//
// is it just 1 big write?
if (wb.size == write.location.getSize()) {
header.clear();
header.putInt(write.location.getSize());
header.put(write.location.getType());
header.clear();
transfer(header, channel);
ByteBuffer source = ByteBuffer.wrap(write.data.getData(), write.data.getOffset(),
write.data.getLength());
transfer(source, channel);
footer.clear();
transfer(footer, channel);
} else {
// Combine the smaller writes into 1 big buffer
while (write != null) {
header.clear();
header.putInt(write.location.getSize());
header.put(write.location.getType());
header.clear();
copy(header, buffer);
assert !header.hasRemaining();
ByteBuffer source = ByteBuffer.wrap(write.data.getData(), write.data.getOffset(),
write.data.getLength());
copy(source, buffer);
assert !source.hasRemaining();
footer.clear();
copy(footer, buffer);
assert !footer.hasRemaining();
write = (WriteCommand)write.getNext();
}
// Fully write out the buffer..
buffer.flip();
transfer(buffer, channel);
buffer.clear();
}
file.getChannel().force(false);
WriteCommand lastWrite = (WriteCommand)wb.first.getTailNode();
dataManager.setLastAppendLocation(lastWrite.location);
// Signal any waiting threads that the write is on disk.
if (wb.latch != null) {
wb.latch.countDown();
}
// Now that the data is on disk, remove the writes from the in
// flight
// cache.
write = wb.first;
while (write != null) {
if (!write.sync) {
inflightWrites.remove(new WriteKey(write.location));
}
write = (WriteCommand)write.getNext();
}
}
} catch (IOException e) {
synchronized (enqueueMutex) {
firstAsyncException = e;
}
} catch (InterruptedException e) {
} finally {
try {
if (file != null) {
dataFile.closeRandomAccessFile(file);
}
} catch (IOException e) {
}
shutdownDone.countDown();
}
} }
/** /**
* Copy the bytes in header to the channel. * Copy the bytes in header to the channel.
*
* @param header - source of data * @param header - source of data
* @param channel - destination where the data will be written. * @param channel - destination where the data will be written.
* @throws IOException * @throws IOException
*/ */
private void transfer(ByteBuffer header, FileChannel channel) throws IOException { private void transfer(ByteBuffer header, FileChannel channel) throws IOException {
while (header.hasRemaining()) { while (header.hasRemaining()) {
channel.write(header); channel.write(header);
} }
} }
private int copy(ByteBuffer src, ByteBuffer dest) { private int copy(ByteBuffer src, ByteBuffer dest) {
int rc = Math.min(dest.remaining(), src.remaining()); int rc = Math.min(dest.remaining(), src.remaining());
if( rc > 0 ) { if (rc > 0) {
// Adjust our limit so that we don't overflow the dest buffer. // Adjust our limit so that we don't overflow the dest buffer.
int limit = src.limit(); int limit = src.limit();
src.limit(src.position()+rc); src.limit(src.position() + rc);
dest.put(src); dest.put(src);
// restore the limit. // restore the limit.
src.limit(limit); src.limit(limit);
} }
return rc; return rc;
} }
} }

View File

@ -24,85 +24,85 @@ import java.util.List;
import java.util.Set; import java.util.Set;
/** /**
* Set of Map.Entry objects for a container * Set of Map.Entry objects for a container
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public class ContainerEntrySet extends ContainerCollectionSupport implements Set{ public class ContainerEntrySet extends ContainerCollectionSupport implements Set {
ContainerEntrySet(MapContainerImpl container){ ContainerEntrySet(MapContainerImpl container) {
super(container); super(container);
} }
public boolean contains(Object o){ public boolean contains(Object o) {
return container.entrySet().contains(o); return container.entrySet().contains(o);
} }
public Iterator iterator(){ public Iterator iterator() {
return new ContainerEntrySetIterator(container,buildEntrySet().iterator()); return new ContainerEntrySetIterator(container, buildEntrySet().iterator());
} }
public Object[] toArray(){ public Object[] toArray() {
return buildEntrySet().toArray(); return buildEntrySet().toArray();
} }
public Object[] toArray(Object[] a){ public Object[] toArray(Object[] a) {
return buildEntrySet().toArray(a); return buildEntrySet().toArray(a);
} }
public boolean add(Object o){ public boolean add(Object o) {
throw new UnsupportedOperationException("Cannot add here"); throw new UnsupportedOperationException("Cannot add here");
} }
public boolean remove(Object o){ public boolean remove(Object o) {
boolean result=false; boolean result = false;
if(buildEntrySet().remove(o)){ if (buildEntrySet().remove(o)) {
ContainerMapEntry entry=(ContainerMapEntry) o; ContainerMapEntry entry = (ContainerMapEntry)o;
container.remove(entry.getKey()); container.remove(entry.getKey());
} }
return result; return result;
} }
public boolean containsAll(Collection c){ public boolean containsAll(Collection c) {
return buildEntrySet().containsAll(c); return buildEntrySet().containsAll(c);
} }
public boolean addAll(Collection c){ public boolean addAll(Collection c) {
throw new UnsupportedOperationException("Cannot add here"); throw new UnsupportedOperationException("Cannot add here");
} }
public boolean retainAll(Collection c){ public boolean retainAll(Collection c) {
List tmpList=new ArrayList(); List tmpList = new ArrayList();
for(Iterator i=c.iterator();i.hasNext();){ for (Iterator i = c.iterator(); i.hasNext();) {
Object o=i.next(); Object o = i.next();
if(!contains(o)){ if (!contains(o)) {
tmpList.add(o); tmpList.add(o);
} }
} }
boolean result=false; boolean result = false;
for(Iterator i=tmpList.iterator();i.hasNext();){ for (Iterator i = tmpList.iterator(); i.hasNext();) {
result|=remove(i.next()); result |= remove(i.next());
} }
return result; return result;
} }
public boolean removeAll(Collection c){ public boolean removeAll(Collection c) {
boolean result=true; boolean result = true;
for(Iterator i=c.iterator();i.hasNext();){ for (Iterator i = c.iterator(); i.hasNext();) {
if(!remove(i.next())){ if (!remove(i.next())) {
result=false; result = false;
} }
} }
return result; return result;
} }
public void clear(){ public void clear() {
container.clear(); container.clear();
} }
protected Set buildEntrySet(){ protected Set buildEntrySet() {
Set set=new HashSet(); Set set = new HashSet();
for(Iterator i=container.keySet().iterator();i.hasNext();){ for (Iterator i = container.keySet().iterator(); i.hasNext();) {
ContainerMapEntry entry=new ContainerMapEntry(container,i.next()); ContainerMapEntry entry = new ContainerMapEntry(container, i.next());
set.add(entry); set.add(entry);
} }
return set; return set;

View File

@ -18,33 +18,33 @@ package org.apache.activemq.kaha.impl.container;
import java.util.Iterator; import java.util.Iterator;
/** /**
* An Iterator for a container entry Set * An Iterator for a container entry Set
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public class ContainerEntrySetIterator implements Iterator{ public class ContainerEntrySetIterator implements Iterator {
private MapContainerImpl container; private MapContainerImpl container;
private Iterator iter; private Iterator iter;
private ContainerMapEntry currentEntry; private ContainerMapEntry currentEntry;
ContainerEntrySetIterator(MapContainerImpl container,Iterator iter){
ContainerEntrySetIterator(MapContainerImpl container, Iterator iter) {
this.container = container; this.container = container;
this.iter = iter; this.iter = iter;
} }
public boolean hasNext(){ public boolean hasNext() {
return iter.hasNext(); return iter.hasNext();
} }
public Object next(){ public Object next() {
currentEntry = (ContainerMapEntry) iter.next(); currentEntry = (ContainerMapEntry)iter.next();
return currentEntry; return currentEntry;
} }
public void remove(){ public void remove() {
if (currentEntry != null){ if (currentEntry != null) {
container.remove(currentEntry.getKey()); container.remove(currentEntry.getKey());
} }
} }
} }

View File

@ -25,27 +25,25 @@ import org.apache.activemq.kaha.impl.index.IndexItem;
import org.apache.activemq.kaha.impl.index.IndexLinkedList; import org.apache.activemq.kaha.impl.index.IndexLinkedList;
/** /**
* A Set of keys for the container * A Set of keys for the container
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public class ContainerKeySet extends ContainerCollectionSupport implements Set{ public class ContainerKeySet extends ContainerCollectionSupport implements Set {
ContainerKeySet(MapContainerImpl container) {
ContainerKeySet(MapContainerImpl container){
super(container); super(container);
} }
public boolean contains(Object o) {
public boolean contains(Object o){
return container.containsKey(o); return container.containsKey(o);
} }
public Iterator iterator(){ public Iterator iterator() {
return new ContainerKeySetIterator(container); return new ContainerKeySetIterator(container);
} }
public Object[] toArray(){ public Object[] toArray() {
List list = new ArrayList(); List list = new ArrayList();
IndexItem item = container.getInternalList().getRoot(); IndexItem item = container.getInternalList().getRoot();
while ((item = container.getInternalList().getNextEntry(item)) != null) { while ((item = container.getInternalList().getNextEntry(item)) != null) {
@ -54,7 +52,7 @@ public class ContainerKeySet extends ContainerCollectionSupport implements Set{
return list.toArray(); return list.toArray();
} }
public Object[] toArray(Object[] a){ public Object[] toArray(Object[] a) {
List list = new ArrayList(); List list = new ArrayList();
IndexItem item = container.getInternalList().getRoot(); IndexItem item = container.getInternalList().getRoot();
while ((item = container.getInternalList().getNextEntry(item)) != null) { while ((item = container.getInternalList().getNextEntry(item)) != null) {
@ -63,58 +61,58 @@ public class ContainerKeySet extends ContainerCollectionSupport implements Set{
return list.toArray(a); return list.toArray(a);
} }
public boolean add(Object o){ public boolean add(Object o) {
throw new UnsupportedOperationException("Cannot add here"); throw new UnsupportedOperationException("Cannot add here");
} }
public boolean remove(Object o){ public boolean remove(Object o) {
return container.remove(o) != null; return container.remove(o) != null;
} }
public boolean containsAll(Collection c){ public boolean containsAll(Collection c) {
boolean result = true; boolean result = true;
for (Object key:c) { for (Object key : c) {
if (!(result&=container.containsKey(key))) { if (!(result &= container.containsKey(key))) {
break; break;
} }
} }
return result; return result;
} }
public boolean addAll(Collection c){ public boolean addAll(Collection c) {
throw new UnsupportedOperationException("Cannot add here"); throw new UnsupportedOperationException("Cannot add here");
} }
public boolean retainAll(Collection c){ public boolean retainAll(Collection c) {
List tmpList = new ArrayList(); List tmpList = new ArrayList();
for (Iterator i = c.iterator(); i.hasNext(); ){ for (Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next(); Object o = i.next();
if (!contains(o)){ if (!contains(o)) {
tmpList.add(o); tmpList.add(o);
} }
} }
for(Iterator i = tmpList.iterator(); i.hasNext();){ for (Iterator i = tmpList.iterator(); i.hasNext();) {
remove(i.next()); remove(i.next());
} }
return !tmpList.isEmpty(); return !tmpList.isEmpty();
} }
public boolean removeAll(Collection c){ public boolean removeAll(Collection c) {
boolean result = true; boolean result = true;
for (Iterator i = c.iterator(); i.hasNext(); ){ for (Iterator i = c.iterator(); i.hasNext();) {
if (!remove(i.next())){ if (!remove(i.next())) {
result = false; result = false;
} }
} }
return result; return result;
} }
public void clear(){ public void clear() {
container.clear(); container.clear();
} }
public String toString() { public String toString() {
StringBuffer result =new StringBuffer(32); StringBuffer result = new StringBuffer(32);
result.append("ContainerKeySet["); result.append("ContainerKeySet[");
IndexItem item = container.getInternalList().getRoot(); IndexItem item = container.getInternalList().getRoot();
while ((item = container.getInternalList().getNextEntry(item)) != null) { while ((item = container.getInternalList().getNextEntry(item)) != null) {

View File

@ -20,38 +20,37 @@ import java.util.Iterator;
import org.apache.activemq.kaha.impl.index.IndexItem; import org.apache.activemq.kaha.impl.index.IndexItem;
import org.apache.activemq.kaha.impl.index.IndexLinkedList; import org.apache.activemq.kaha.impl.index.IndexLinkedList;
/** /**
*Iterator for the set of keys for a container * Iterator for the set of keys for a container
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public class ContainerKeySetIterator implements Iterator{ public class ContainerKeySetIterator implements Iterator {
private MapContainerImpl container; private MapContainerImpl container;
private IndexLinkedList list; private IndexLinkedList list;
protected IndexItem nextItem; protected IndexItem nextItem;
protected IndexItem currentItem; protected IndexItem currentItem;
ContainerKeySetIterator(MapContainerImpl container){ ContainerKeySetIterator(MapContainerImpl container) {
this.container = container; this.container = container;
this.list=container.getInternalList(); this.list = container.getInternalList();
this.currentItem=list.getRoot(); this.currentItem = list.getRoot();
this.nextItem=list.getNextEntry(currentItem); this.nextItem = list.getNextEntry(currentItem);
}
public boolean hasNext(){
return nextItem!=null;
} }
public Object next(){ public boolean hasNext() {
currentItem=nextItem; return nextItem != null;
Object result=container.getKey(nextItem); }
nextItem=list.getNextEntry(nextItem);
public Object next() {
currentItem = nextItem;
Object result = container.getKey(nextItem);
nextItem = list.getNextEntry(nextItem);
return result; return result;
} }
public void remove(){ public void remove() {
if(currentItem!=null){ if (currentItem != null) {
container.remove(currentItem); container.remove(currentItem);
} }
} }

View File

@ -22,10 +22,10 @@ import org.apache.activemq.kaha.impl.index.IndexLinkedList;
/** /**
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public class ContainerListIterator extends ContainerValueCollectionIterator implements ListIterator{ public class ContainerListIterator extends ContainerValueCollectionIterator implements ListIterator {
protected ContainerListIterator(ListContainerImpl container,IndexLinkedList list,IndexItem start){ protected ContainerListIterator(ListContainerImpl container, IndexLinkedList list, IndexItem start) {
super(container,list,start); super(container, list, start);
} }
/* /*
@ -33,10 +33,10 @@ public class ContainerListIterator extends ContainerValueCollectionIterator impl
* *
* @see java.util.ListIterator#hasPrevious() * @see java.util.ListIterator#hasPrevious()
*/ */
public boolean hasPrevious(){ public boolean hasPrevious() {
synchronized(container){ synchronized (container) {
nextItem=(IndexItem)list.refreshEntry(nextItem); nextItem = (IndexItem)list.refreshEntry(nextItem);
return list.getPrevEntry(nextItem)!=null; return list.getPrevEntry(nextItem) != null;
} }
} }
@ -45,11 +45,11 @@ public class ContainerListIterator extends ContainerValueCollectionIterator impl
* *
* @see java.util.ListIterator#previous() * @see java.util.ListIterator#previous()
*/ */
public Object previous(){ public Object previous() {
synchronized(container){ synchronized (container) {
nextItem=(IndexItem)list.refreshEntry(nextItem); nextItem = (IndexItem)list.refreshEntry(nextItem);
nextItem=list.getPrevEntry(nextItem); nextItem = list.getPrevEntry(nextItem);
return nextItem!=null?container.getValue(nextItem):null; return nextItem != null ? container.getValue(nextItem) : null;
} }
} }
@ -58,14 +58,14 @@ public class ContainerListIterator extends ContainerValueCollectionIterator impl
* *
* @see java.util.ListIterator#nextIndex() * @see java.util.ListIterator#nextIndex()
*/ */
public int nextIndex(){ public int nextIndex() {
int result=-1; int result = -1;
if(nextItem!=null){ if (nextItem != null) {
synchronized(container){ synchronized (container) {
nextItem=(IndexItem)list.refreshEntry(nextItem); nextItem = (IndexItem)list.refreshEntry(nextItem);
StoreEntry next=list.getNextEntry(nextItem); StoreEntry next = list.getNextEntry(nextItem);
if(next!=null){ if (next != null) {
result=container.getInternalList().indexOf(next); result = container.getInternalList().indexOf(next);
} }
} }
} }
@ -77,14 +77,14 @@ public class ContainerListIterator extends ContainerValueCollectionIterator impl
* *
* @see java.util.ListIterator#previousIndex() * @see java.util.ListIterator#previousIndex()
*/ */
public int previousIndex(){ public int previousIndex() {
int result=-1; int result = -1;
if(nextItem!=null){ if (nextItem != null) {
synchronized(container){ synchronized (container) {
nextItem=(IndexItem)list.refreshEntry(nextItem); nextItem = (IndexItem)list.refreshEntry(nextItem);
StoreEntry prev=list.getPrevEntry(nextItem); StoreEntry prev = list.getPrevEntry(nextItem);
if(prev!=null){ if (prev != null) {
result=container.getInternalList().indexOf(prev); result = container.getInternalList().indexOf(prev);
} }
} }
} }
@ -96,9 +96,9 @@ public class ContainerListIterator extends ContainerValueCollectionIterator impl
* *
* @see java.util.ListIterator#set(E) * @see java.util.ListIterator#set(E)
*/ */
public void set(Object o){ public void set(Object o) {
IndexItem item=((ListContainerImpl)container).internalSet(previousIndex()+1,o); IndexItem item = ((ListContainerImpl)container).internalSet(previousIndex() + 1, o);
nextItem=item; nextItem = item;
} }
/* /*
@ -106,8 +106,8 @@ public class ContainerListIterator extends ContainerValueCollectionIterator impl
* *
* @see java.util.ListIterator#add(E) * @see java.util.ListIterator#add(E)
*/ */
public void add(Object o){ public void add(Object o) {
IndexItem item=((ListContainerImpl)container).internalAdd(previousIndex()+1,o); IndexItem item = ((ListContainerImpl)container).internalAdd(previousIndex() + 1, o);
nextItem=item; nextItem = item;
} }
} }

View File

@ -20,34 +20,30 @@ import java.util.Map;
import org.apache.activemq.kaha.MapContainer; import org.apache.activemq.kaha.MapContainer;
/** /**
* Map.Entry implementation for a container * Map.Entry implementation for a container
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
class ContainerMapEntry implements Map.Entry { class ContainerMapEntry implements Map.Entry {
private MapContainer container; private MapContainer container;
private Object key; private Object key;
ContainerMapEntry(MapContainer container,Object key){ ContainerMapEntry(MapContainer container, Object key) {
this.container = container; this.container = container;
this.key = key; this.key = key;
} }
public Object getKey() {
public Object getKey(){
return key; return key;
} }
public Object getValue(){ public Object getValue() {
return container.get(key); return container.get(key);
} }
public Object setValue(Object value){ public Object setValue(Object value) {
return container.put(key, value); return container.put(key, value);
} }
} }

View File

@ -26,59 +26,53 @@ import org.apache.activemq.kaha.impl.index.IndexItem;
import org.apache.activemq.kaha.impl.index.IndexLinkedList; import org.apache.activemq.kaha.impl.index.IndexLinkedList;
/** /**
* Values collection for the MapContainer * Values collection for the MapContainer
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
class ContainerValueCollection extends ContainerCollectionSupport implements Collection{ class ContainerValueCollection extends ContainerCollectionSupport implements Collection {
ContainerValueCollection(MapContainerImpl container) {
ContainerValueCollection(MapContainerImpl container){
super(container); super(container);
} }
public boolean contains(Object o) {
public boolean contains(Object o){
return container.containsValue(o); return container.containsValue(o);
} }
public Iterator iterator() {
public Iterator iterator(){ IndexLinkedList list = container.getItemList();
IndexLinkedList list=container.getItemList(); return new ContainerValueCollectionIterator(container, list, list.getRoot());
return new ContainerValueCollectionIterator(container,list,list.getRoot());
} }
public Object[] toArray() {
public Object[] toArray(){
Object[] result = null; Object[] result = null;
IndexLinkedList list = container.getItemList(); IndexLinkedList list = container.getItemList();
synchronized(list){ synchronized (list) {
result = new Object[list.size()]; result = new Object[list.size()];
IndexItem item = list.getFirst(); IndexItem item = list.getFirst();
int count = 0; int count = 0;
while (item != null){ while (item != null) {
Object value=container.getValue(item); Object value = container.getValue(item);
result[count++] = value; result[count++] = value;
item = list.getNextEntry(item); item = list.getNextEntry(item);
} }
} }
return result; return result;
} }
public Object[] toArray(Object[] result){ public Object[] toArray(Object[] result) {
IndexLinkedList list=container.getItemList(); IndexLinkedList list = container.getItemList();
synchronized(list){ synchronized (list) {
if(result.length<=list.size()){ if (result.length <= list.size()) {
IndexItem item = list.getFirst(); IndexItem item = list.getFirst();
int count = 0; int count = 0;
while (item != null){ while (item != null) {
Object value=container.getValue(item); Object value = container.getValue(item);
result[count++] = value; result[count++] = value;
item = list.getNextEntry(item); item = list.getNextEntry(item);
} }
} }
@ -86,21 +80,18 @@ class ContainerValueCollection extends ContainerCollectionSupport implements Col
return result; return result;
} }
public boolean add(Object o) {
public boolean add(Object o){ throw new UnsupportedOperationException("Can't add an object here");
throw new UnsupportedOperationException("Can't add an object here");
} }
public boolean remove(Object o) {
public boolean remove(Object o){
return container.removeValue(o); return container.removeValue(o);
} }
public boolean containsAll(Collection c) {
public boolean containsAll(Collection c){
boolean result = !c.isEmpty(); boolean result = !c.isEmpty();
for (Iterator i = c.iterator(); i.hasNext(); ){ for (Iterator i = c.iterator(); i.hasNext();) {
if (!contains(i.next())){ if (!contains(i.next())) {
result = false; result = false;
break; break;
} }
@ -108,38 +99,34 @@ class ContainerValueCollection extends ContainerCollectionSupport implements Col
return result; return result;
} }
public boolean addAll(Collection c) {
public boolean addAll(Collection c){ throw new UnsupportedOperationException("Can't add everything here!");
throw new UnsupportedOperationException("Can't add everything here!");
} }
public boolean removeAll(Collection c) {
public boolean removeAll(Collection c){
boolean result = true; boolean result = true;
for (Iterator i = c.iterator(); i.hasNext(); ){ for (Iterator i = c.iterator(); i.hasNext();) {
Object obj = i.next(); Object obj = i.next();
result&=remove(obj); result &= remove(obj);
} }
return result; return result;
} }
public boolean retainAll(Collection c) {
public boolean retainAll(Collection c){ List tmpList = new ArrayList();
List tmpList = new ArrayList(); for (Iterator i = c.iterator(); i.hasNext();) {
for (Iterator i = c.iterator(); i.hasNext(); ){ Object o = i.next();
Object o = i.next(); if (!contains(o)) {
if (!contains(o)){ tmpList.add(o);
tmpList.add(o); }
} }
} for (Iterator i = tmpList.iterator(); i.hasNext();) {
for(Iterator i = tmpList.iterator(); i.hasNext();){ remove(i.next());
remove(i.next()); }
} return !tmpList.isEmpty();
return !tmpList.isEmpty();
} }
public void clear() {
public void clear(){ container.clear();
container.clear();
} }
} }

View File

@ -23,38 +23,38 @@ import org.apache.activemq.kaha.impl.index.IndexLinkedList;
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public class ContainerValueCollectionIterator implements Iterator{ public class ContainerValueCollectionIterator implements Iterator {
protected BaseContainerImpl container; protected BaseContainerImpl container;
protected IndexLinkedList list; protected IndexLinkedList list;
protected IndexItem nextItem; protected IndexItem nextItem;
protected IndexItem currentItem; protected IndexItem currentItem;
ContainerValueCollectionIterator(BaseContainerImpl container,IndexLinkedList list,IndexItem start){ ContainerValueCollectionIterator(BaseContainerImpl container, IndexLinkedList list, IndexItem start) {
this.container=container; this.container = container;
this.list=list; this.list = list;
this.currentItem=start; this.currentItem = start;
this.nextItem=list.getNextEntry((IndexItem)list.refreshEntry(start)); this.nextItem = list.getNextEntry((IndexItem)list.refreshEntry(start));
} }
public boolean hasNext(){ public boolean hasNext() {
return nextItem!=null; return nextItem != null;
} }
public Object next(){ public Object next() {
synchronized(container){ synchronized (container) {
nextItem=(IndexItem)list.refreshEntry(nextItem); nextItem = (IndexItem)list.refreshEntry(nextItem);
currentItem=nextItem; currentItem = nextItem;
Object result=container.getValue(nextItem); Object result = container.getValue(nextItem);
nextItem=list.getNextEntry(nextItem); nextItem = list.getNextEntry(nextItem);
return result; return result;
} }
} }
public void remove(){ public void remove() {
synchronized(container){ synchronized (container) {
if(currentItem!=null){ if (currentItem != null) {
currentItem=(IndexItem)list.refreshEntry(currentItem); currentItem = (IndexItem)list.refreshEntry(currentItem);
container.remove(currentItem); container.remove(currentItem);
} }
} }

View File

@ -43,34 +43,34 @@ import org.apache.commons.logging.LogFactory;
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public final class MapContainerImpl extends BaseContainerImpl implements MapContainer{ public final class MapContainerImpl extends BaseContainerImpl implements MapContainer {
private static final Log log=LogFactory.getLog(MapContainerImpl.class); private static final Log log = LogFactory.getLog(MapContainerImpl.class);
protected Index index; protected Index index;
protected Marshaller keyMarshaller=Store.ObjectMarshaller; protected Marshaller keyMarshaller = Store.ObjectMarshaller;
protected Marshaller valueMarshaller=Store.ObjectMarshaller; protected Marshaller valueMarshaller = Store.ObjectMarshaller;
protected File directory; protected File directory;
public MapContainerImpl(File directory,ContainerId id,IndexItem root,IndexManager indexManager, public MapContainerImpl(File directory, ContainerId id, IndexItem root, IndexManager indexManager,
DataManager dataManager,boolean persistentIndex){ DataManager dataManager, boolean persistentIndex) {
super(id,root,indexManager,dataManager,persistentIndex); super(id, root, indexManager, dataManager, persistentIndex);
this.directory=directory; this.directory = directory;
} }
public synchronized void init(){ public synchronized void init() {
super.init(); super.init();
if(index==null){ if (index == null) {
if(persistentIndex){ if (persistentIndex) {
String name=containerId.getDataContainerName()+"_"+containerId.getKey(); String name = containerId.getDataContainerName() + "_" + containerId.getKey();
name=name.replaceAll("[^a-zA-Z0-9\\.\\_\\-]", "_"); name = name.replaceAll("[^a-zA-Z0-9\\.\\_\\-]", "_");
try{ try {
this.index=new HashIndex(directory,name,indexManager); this.index = new HashIndex(directory, name, indexManager);
}catch(IOException e){ } catch (IOException e) {
log.error("Failed to create HashIndex",e); log.error("Failed to create HashIndex", e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
}else{ } else {
this.index=new VMIndex(indexManager); this.index = new VMIndex(indexManager);
} }
} }
index.setKeyMarshaller(keyMarshaller); index.setKeyMarshaller(keyMarshaller);
@ -81,27 +81,27 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
* *
* @see org.apache.activemq.kaha.MapContainer#load() * @see org.apache.activemq.kaha.MapContainer#load()
*/ */
public synchronized void load(){ public synchronized void load() {
checkClosed(); checkClosed();
if(!loaded){ if (!loaded) {
if(!loaded){ if (!loaded) {
loaded=true; loaded = true;
try{ try {
init(); init();
index.load(); index.load();
long nextItem=root.getNextItem(); long nextItem = root.getNextItem();
while(nextItem!=Item.POSITION_NOT_SET){ while (nextItem != Item.POSITION_NOT_SET) {
IndexItem item=indexManager.getIndex(nextItem); IndexItem item = indexManager.getIndex(nextItem);
StoreLocation data=item.getKeyDataItem(); StoreLocation data = item.getKeyDataItem();
Object key=dataManager.readItem(keyMarshaller,data); Object key = dataManager.readItem(keyMarshaller, data);
if(index.isTransient()){ if (index.isTransient()) {
index.store(key,item); index.store(key, item);
} }
indexList.add(item); indexList.add(item);
nextItem=item.getNextItem(); nextItem = item.getNextItem();
} }
}catch(IOException e){ } catch (IOException e) {
log.error("Failed to load container "+getId(),e); log.error("Failed to load container " + getId(), e);
throw new RuntimeStoreException(e); throw new RuntimeStoreException(e);
} }
} }
@ -113,30 +113,30 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
* *
* @see org.apache.activemq.kaha.MapContainer#unload() * @see org.apache.activemq.kaha.MapContainer#unload()
*/ */
public synchronized void unload(){ public synchronized void unload() {
checkClosed(); checkClosed();
if(loaded){ if (loaded) {
loaded=false; loaded = false;
try{ try {
index.unload(); index.unload();
}catch(IOException e){ } catch (IOException e) {
log.warn("Failed to unload the index",e); log.warn("Failed to unload the index", e);
} }
indexList.clear(); indexList.clear();
} }
} }
public synchronized void setKeyMarshaller(Marshaller keyMarshaller){ public synchronized void setKeyMarshaller(Marshaller keyMarshaller) {
checkClosed(); checkClosed();
this.keyMarshaller=keyMarshaller; this.keyMarshaller = keyMarshaller;
if(index!=null){ if (index != null) {
index.setKeyMarshaller(keyMarshaller); index.setKeyMarshaller(keyMarshaller);
} }
} }
public synchronized void setValueMarshaller(Marshaller valueMarshaller){ public synchronized void setValueMarshaller(Marshaller valueMarshaller) {
checkClosed(); checkClosed();
this.valueMarshaller=valueMarshaller; this.valueMarshaller = valueMarshaller;
} }
/* /*
@ -144,7 +144,7 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
* *
* @see org.apache.activemq.kaha.MapContainer#size() * @see org.apache.activemq.kaha.MapContainer#size()
*/ */
public synchronized int size(){ public synchronized int size() {
load(); load();
return indexList.size(); return indexList.size();
} }
@ -154,7 +154,7 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
* *
* @see org.apache.activemq.kaha.MapContainer#isEmpty() * @see org.apache.activemq.kaha.MapContainer#isEmpty()
*/ */
public synchronized boolean isEmpty(){ public synchronized boolean isEmpty() {
load(); load();
return indexList.isEmpty(); return indexList.isEmpty();
} }
@ -164,12 +164,12 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
* *
* @see org.apache.activemq.kaha.MapContainer#containsKey(java.lang.Object) * @see org.apache.activemq.kaha.MapContainer#containsKey(java.lang.Object)
*/ */
public synchronized boolean containsKey(Object key){ public synchronized boolean containsKey(Object key) {
load(); load();
try{ try {
return index.containsKey(key); return index.containsKey(key);
}catch(IOException e){ } catch (IOException e) {
log.error("Failed trying to find key: "+key,e); log.error("Failed trying to find key: " + key, e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@ -179,34 +179,35 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
* *
* @see org.apache.activemq.kaha.MapContainer#get(java.lang.Object) * @see org.apache.activemq.kaha.MapContainer#get(java.lang.Object)
*/ */
public synchronized Object get(Object key){ public synchronized Object get(Object key) {
load(); load();
Object result=null; Object result = null;
StoreEntry item=null; StoreEntry item = null;
try{ try {
item=index.get(key); item = index.get(key);
}catch(IOException e){ } catch (IOException e) {
log.error("Failed trying to get key: "+key,e); log.error("Failed trying to get key: " + key, e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
if(item!=null){ if (item != null) {
result=getValue(item); result = getValue(item);
} }
return result; return result;
} }
/** /**
* Get the StoreEntry associated with the key * Get the StoreEntry associated with the key
*
* @param key * @param key
* @return the StoreEntry * @return the StoreEntry
*/ */
public synchronized StoreEntry getEntry(Object key) { public synchronized StoreEntry getEntry(Object key) {
load(); load();
StoreEntry item=null; StoreEntry item = null;
try{ try {
item=index.get(key); item = index.get(key);
}catch(IOException e){ } catch (IOException e) {
log.error("Failed trying to get key: "+key,e); log.error("Failed trying to get key: " + key, e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
return item; return item;
@ -217,18 +218,18 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
* *
* @see org.apache.activemq.kaha.MapContainer#containsValue(java.lang.Object) * @see org.apache.activemq.kaha.MapContainer#containsValue(java.lang.Object)
*/ */
public synchronized boolean containsValue(Object o){ public synchronized boolean containsValue(Object o) {
load(); load();
boolean result=false; boolean result = false;
if(o!=null){ if (o != null) {
IndexItem item=indexList.getFirst(); IndexItem item = indexList.getFirst();
while(item!=null){ while (item != null) {
Object value=getValue(item); Object value = getValue(item);
if(value!=null&&value.equals(o)){ if (value != null && value.equals(o)) {
result=true; result = true;
break; break;
} }
item=indexList.getNextEntry(item); item = indexList.getNextEntry(item);
} }
} }
return result; return result;
@ -239,12 +240,12 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
* *
* @see org.apache.activemq.kaha.MapContainer#putAll(java.util.Map) * @see org.apache.activemq.kaha.MapContainer#putAll(java.util.Map)
*/ */
public synchronized void putAll(Map t){ public synchronized void putAll(Map t) {
load(); load();
if(t!=null){ if (t != null) {
for(Iterator i=t.entrySet().iterator();i.hasNext();){ for (Iterator i = t.entrySet().iterator(); i.hasNext();) {
Map.Entry entry=(Map.Entry)i.next(); Map.Entry entry = (Map.Entry)i.next();
put(entry.getKey(),entry.getValue()); put(entry.getKey(), entry.getValue());
} }
} }
} }
@ -254,7 +255,7 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
* *
* @see org.apache.activemq.kaha.MapContainer#keySet() * @see org.apache.activemq.kaha.MapContainer#keySet()
*/ */
public synchronized Set keySet(){ public synchronized Set keySet() {
load(); load();
return new ContainerKeySet(this); return new ContainerKeySet(this);
} }
@ -264,7 +265,7 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
* *
* @see org.apache.activemq.kaha.MapContainer#values() * @see org.apache.activemq.kaha.MapContainer#values()
*/ */
public synchronized Collection values(){ public synchronized Collection values() {
load(); load();
return new ContainerValueCollection(this); return new ContainerValueCollection(this);
} }
@ -274,7 +275,7 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
* *
* @see org.apache.activemq.kaha.MapContainer#entrySet() * @see org.apache.activemq.kaha.MapContainer#entrySet()
*/ */
public synchronized Set entrySet(){ public synchronized Set entrySet() {
load(); load();
return new ContainerEntrySet(this); return new ContainerEntrySet(this);
} }
@ -282,16 +283,17 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see org.apache.activemq.kaha.MapContainer#put(java.lang.Object, java.lang.Object) * @see org.apache.activemq.kaha.MapContainer#put(java.lang.Object,
* java.lang.Object)
*/ */
public synchronized Object put(Object key,Object value){ public synchronized Object put(Object key, Object value) {
load(); load();
Object result=remove(key); Object result = remove(key);
IndexItem item=write(key,value); IndexItem item = write(key, value);
try{ try {
index.store(key,item); index.store(key, item);
}catch(IOException e){ } catch (IOException e) {
log.error("Failed trying to insert key: "+key,e); log.error("Failed trying to insert key: " + key, e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
indexList.add(item); indexList.add(item);
@ -303,52 +305,52 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
* *
* @see org.apache.activemq.kaha.MapContainer#remove(java.lang.Object) * @see org.apache.activemq.kaha.MapContainer#remove(java.lang.Object)
*/ */
public synchronized Object remove(Object key){ public synchronized Object remove(Object key) {
load(); load();
try{ try {
Object result=null; Object result = null;
IndexItem item=(IndexItem)index.remove(key); IndexItem item = (IndexItem)index.remove(key);
if(item!=null){ if (item != null) {
// refresh the index // refresh the index
item=(IndexItem)indexList.refreshEntry(item); item = (IndexItem)indexList.refreshEntry(item);
result=getValue(item); result = getValue(item);
IndexItem prev=indexList.getPrevEntry(item); IndexItem prev = indexList.getPrevEntry(item);
IndexItem next=indexList.getNextEntry(item); IndexItem next = indexList.getNextEntry(item);
indexList.remove(item); indexList.remove(item);
delete(item,prev,next); delete(item, prev, next);
} }
return result; return result;
}catch(IOException e){ } catch (IOException e) {
log.error("Failed trying to remove key: "+key,e); log.error("Failed trying to remove key: " + key, e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
public synchronized boolean removeValue(Object o){ public synchronized boolean removeValue(Object o) {
load(); load();
boolean result=false; boolean result = false;
if(o!=null){ if (o != null) {
IndexItem item=indexList.getFirst(); IndexItem item = indexList.getFirst();
while(item!=null){ while (item != null) {
Object value=getValue(item); Object value = getValue(item);
if(value!=null&&value.equals(o)){ if (value != null && value.equals(o)) {
result=true; result = true;
// find the key // find the key
Object key=getKey(item); Object key = getKey(item);
if(key!=null){ if (key != null) {
remove(key); remove(key);
} }
break; break;
} }
item=indexList.getNextEntry(item); item = indexList.getNextEntry(item);
} }
} }
return result; return result;
} }
protected synchronized void remove(IndexItem item){ protected synchronized void remove(IndexItem item) {
Object key=getKey(item); Object key = getKey(item);
if(key!=null){ if (key != null) {
remove(key); remove(key);
} }
} }
@ -358,15 +360,15 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
* *
* @see org.apache.activemq.kaha.MapContainer#clear() * @see org.apache.activemq.kaha.MapContainer#clear()
*/ */
public synchronized void clear(){ public synchronized void clear() {
checkClosed(); checkClosed();
loaded=true; loaded = true;
init(); init();
if(index!=null){ if (index != null) {
try{ try {
index.clear(); index.clear();
}catch(IOException e){ } catch (IOException e) {
log.error("Failed trying clear index",e); log.error("Failed trying clear index", e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@ -381,16 +383,16 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
* @param value * @param value
* @return the StoreEntry associated with the entry * @return the StoreEntry associated with the entry
*/ */
public synchronized StoreEntry place(Object key,Object value){ public synchronized StoreEntry place(Object key, Object value) {
load(); load();
try{ try {
remove(key); remove(key);
IndexItem item=write(key,value); IndexItem item = write(key, value);
index.store(key,item); index.store(key, item);
indexList.add(item); indexList.add(item);
return item; return item;
}catch(IOException e){ } catch (IOException e) {
log.error("Failed trying to place key: "+key,e); log.error("Failed trying to place key: " + key, e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@ -401,47 +403,47 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
* @param entry * @param entry
* @throws IOException * @throws IOException
*/ */
public synchronized void remove(StoreEntry entry){ public synchronized void remove(StoreEntry entry) {
load(); load();
IndexItem item=(IndexItem)entry; IndexItem item = (IndexItem)entry;
if(item!=null){ if (item != null) {
Object key=getKey(item); Object key = getKey(item);
try{ try {
index.remove(key); index.remove(key);
}catch(IOException e){ } catch (IOException e) {
log.error("Failed trying to remove entry: "+entry,e); log.error("Failed trying to remove entry: " + entry, e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
IndexItem prev=indexList.getPrevEntry(item); IndexItem prev = indexList.getPrevEntry(item);
IndexItem next=indexList.getNextEntry(item); IndexItem next = indexList.getNextEntry(item);
indexList.remove(item); indexList.remove(item);
delete(item,prev,next); delete(item, prev, next);
} }
} }
public synchronized StoreEntry getFirst(){ public synchronized StoreEntry getFirst() {
load(); load();
return indexList.getFirst(); return indexList.getFirst();
} }
public synchronized StoreEntry getLast(){ public synchronized StoreEntry getLast() {
load(); load();
return indexList.getLast(); return indexList.getLast();
} }
public synchronized StoreEntry getNext(StoreEntry entry){ public synchronized StoreEntry getNext(StoreEntry entry) {
load(); load();
IndexItem item=(IndexItem)entry; IndexItem item = (IndexItem)entry;
return indexList.getNextEntry(item); return indexList.getNextEntry(item);
} }
public synchronized StoreEntry getPrevious(StoreEntry entry){ public synchronized StoreEntry getPrevious(StoreEntry entry) {
load(); load();
IndexItem item=(IndexItem)entry; IndexItem item = (IndexItem)entry;
return indexList.getPrevEntry(item); return indexList.getPrevEntry(item);
} }
public synchronized StoreEntry refresh(StoreEntry entry){ public synchronized StoreEntry refresh(StoreEntry entry) {
load(); load();
return indexList.getEntry(entry); return indexList.getEntry(entry);
} }
@ -452,17 +454,17 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
* @param item * @param item
* @return the value associated with the store entry * @return the value associated with the store entry
*/ */
public synchronized Object getValue(StoreEntry item){ public synchronized Object getValue(StoreEntry item) {
load(); load();
Object result=null; Object result = null;
if(item!=null){ if (item != null) {
try{ try {
// ensure this value is up to date // ensure this value is up to date
// item=indexList.getEntry(item); // item=indexList.getEntry(item);
StoreLocation data=item.getValueDataItem(); StoreLocation data = item.getValueDataItem();
result=dataManager.readItem(valueMarshaller,data); result = dataManager.readItem(valueMarshaller, data);
}catch(IOException e){ } catch (IOException e) {
log.error("Failed to get value for "+item,e); log.error("Failed to get value for " + item, e);
throw new RuntimeStoreException(e); throw new RuntimeStoreException(e);
} }
} }
@ -475,50 +477,50 @@ public final class MapContainerImpl extends BaseContainerImpl implements MapCont
* @param item * @param item
* @return the Key Object associated with the StoreEntry * @return the Key Object associated with the StoreEntry
*/ */
public synchronized Object getKey(StoreEntry item){ public synchronized Object getKey(StoreEntry item) {
load(); load();
Object result=null; Object result = null;
if(item!=null){ if (item != null) {
try{ try {
StoreLocation data=item.getKeyDataItem(); StoreLocation data = item.getKeyDataItem();
result=dataManager.readItem(keyMarshaller,data); result = dataManager.readItem(keyMarshaller, data);
}catch(IOException e){ } catch (IOException e) {
log.error("Failed to get key for "+item,e); log.error("Failed to get key for " + item, e);
throw new RuntimeStoreException(e); throw new RuntimeStoreException(e);
} }
} }
return result; return result;
} }
protected IndexLinkedList getItemList(){ protected IndexLinkedList getItemList() {
return indexList; return indexList;
} }
protected synchronized IndexItem write(Object key,Object value){ protected synchronized IndexItem write(Object key, Object value) {
IndexItem index=null; IndexItem index = null;
try{ try {
index=indexManager.createNewIndex(); index = indexManager.createNewIndex();
StoreLocation data=dataManager.storeDataItem(keyMarshaller,key); StoreLocation data = dataManager.storeDataItem(keyMarshaller, key);
index.setKeyData(data); index.setKeyData(data);
if(value!=null){ if (value != null) {
data=dataManager.storeDataItem(valueMarshaller,value); data = dataManager.storeDataItem(valueMarshaller, value);
index.setValueData(data); index.setValueData(data);
} }
IndexItem prev=indexList.getLast(); IndexItem prev = indexList.getLast();
prev=prev!=null?prev:indexList.getRoot(); prev = prev != null ? prev : indexList.getRoot();
IndexItem next=indexList.getNextEntry(prev); IndexItem next = indexList.getNextEntry(prev);
prev.setNextItem(index.getOffset()); prev.setNextItem(index.getOffset());
index.setPreviousItem(prev.getOffset()); index.setPreviousItem(prev.getOffset());
updateIndexes(prev); updateIndexes(prev);
if(next!=null){ if (next != null) {
next.setPreviousItem(index.getOffset()); next.setPreviousItem(index.getOffset());
index.setNextItem(next.getOffset()); index.setNextItem(next.getOffset());
updateIndexes(next); updateIndexes(next);
} }
storeIndex(index); storeIndex(index);
}catch(IOException e){ } catch (IOException e) {
log.error("Failed to write "+key+" , "+value,e); log.error("Failed to write " + key + " , " + value, e);
throw new RuntimeStoreException(e); throw new RuntimeStoreException(e);
} }
return index; return index;

View File

@ -18,27 +18,27 @@ package org.apache.activemq.kaha.impl.data;
import org.apache.activemq.kaha.StoreLocation; import org.apache.activemq.kaha.StoreLocation;
/** /**
* A a wrapper for a data in the store * A a wrapper for a data in the store
* *
* @version $Revision: 1.2 $ * @version $Revision: 1.2 $
*/ */
public final class DataItem implements Item, StoreLocation{ public final class DataItem implements Item, StoreLocation {
private int file=(int) POSITION_NOT_SET; private int file = (int)POSITION_NOT_SET;
private long offset=POSITION_NOT_SET; private long offset = POSITION_NOT_SET;
private int size; private int size;
public DataItem(){} public DataItem() {
}
DataItem(DataItem item) { DataItem(DataItem item) {
this.file = item.file; this.file = item.file;
this.offset = item.offset; this.offset = item.offset;
this.size = item.size; this.size = item.size;
} }
boolean isValid(){ boolean isValid() {
return file != POSITION_NOT_SET; return file != POSITION_NOT_SET;
} }
@ -46,52 +46,52 @@ public final class DataItem implements Item, StoreLocation{
* @return * @return
* @see org.apache.activemq.kaha.StoreLocation#getSize() * @see org.apache.activemq.kaha.StoreLocation#getSize()
*/ */
public int getSize(){ public int getSize() {
return size; return size;
} }
/** /**
* @param size The size to set. * @param size The size to set.
*/ */
public void setSize(int size){ public void setSize(int size) {
this.size=size; this.size = size;
} }
/** /**
* @return * @return
* @see org.apache.activemq.kaha.StoreLocation#getOffset() * @see org.apache.activemq.kaha.StoreLocation#getOffset()
*/ */
public long getOffset(){ public long getOffset() {
return offset; return offset;
} }
/** /**
* @param offset The offset to set. * @param offset The offset to set.
*/ */
public void setOffset(long offset){ public void setOffset(long offset) {
this.offset=offset; this.offset = offset;
} }
/** /**
* @return * @return
* @see org.apache.activemq.kaha.StoreLocation#getFile() * @see org.apache.activemq.kaha.StoreLocation#getFile()
*/ */
public int getFile(){ public int getFile() {
return file; return file;
} }
/** /**
* @param file The file to set. * @param file The file to set.
*/ */
public void setFile(int file){ public void setFile(int file) {
this.file=file; this.file = file;
} }
/** /**
* @return a pretty print * @return a pretty print
*/ */
public String toString(){ public String toString() {
String result="offset = "+offset+", file = " + file + ", size = "+size; String result = "offset = " + offset + ", file = " + file + ", size = " + size;
return result; return result;
} }

View File

@ -32,284 +32,316 @@ import org.apache.activemq.kaha.impl.index.RedoStoreIndexItem;
import org.apache.activemq.util.IOExceptionSupport; import org.apache.activemq.util.IOExceptionSupport;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
/** /**
* Manages DataFiles * Manages DataFiles
* *
* @version $Revision: 1.1.1.1 $ * @version $Revision: 1.1.1.1 $
*/ */
public final class DataManagerImpl implements DataManager { public final class DataManagerImpl implements DataManager {
private static final Log log=LogFactory.getLog(DataManagerImpl.class); private static final Log log = LogFactory.getLog(DataManagerImpl.class);
public static final long MAX_FILE_LENGTH=1024*1024*32; public static final long MAX_FILE_LENGTH = 1024 * 1024 * 32;
private static final String NAME_PREFIX="data-"; private static final String NAME_PREFIX = "data-";
private final File directory; private final File directory;
private final String name; private final String name;
private SyncDataFileReader reader; private SyncDataFileReader reader;
private SyncDataFileWriter writer; private SyncDataFileWriter writer;
private DataFile currentWriteFile; private DataFile currentWriteFile;
private long maxFileLength = MAX_FILE_LENGTH; private long maxFileLength = MAX_FILE_LENGTH;
Map fileMap=new HashMap(); Map fileMap = new HashMap();
public static final int ITEM_HEAD_SIZE=5; // type + length public static final int ITEM_HEAD_SIZE = 5; // type + length
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;
Marshaller redoMarshaller = RedoStoreIndexItem.MARSHALLER; Marshaller redoMarshaller = RedoStoreIndexItem.MARSHALLER;
private String dataFilePrefix; private String dataFilePrefix;
public DataManagerImpl(File dir, final String name){ public DataManagerImpl(File dir, final String name) {
this.directory=dir; this.directory = dir;
this.name=name; this.name = name;
dataFilePrefix = NAME_PREFIX+name+"-"; dataFilePrefix = NAME_PREFIX + name + "-";
// build up list of current dataFiles // build up list of current dataFiles
File[] files=dir.listFiles(new FilenameFilter(){ File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir,String n){ public boolean accept(File dir, String n) {
return dir.equals(directory)&&n.startsWith(dataFilePrefix); return dir.equals(directory) && n.startsWith(dataFilePrefix);
} }
}); });
if(files!=null){ if (files != null) {
for(int i=0;i<files.length;i++){ for (int i = 0; i < files.length; i++) {
File file=files[i]; File file = files[i];
String n=file.getName(); String n = file.getName();
String numStr=n.substring(dataFilePrefix.length(),n.length()); String numStr = n.substring(dataFilePrefix.length(), n.length());
int num=Integer.parseInt(numStr); int num = Integer.parseInt(numStr);
DataFile dataFile=new DataFile(file,num); DataFile dataFile = new DataFile(file, num);
fileMap.put(dataFile.getNumber(),dataFile); fileMap.put(dataFile.getNumber(), dataFile);
if(currentWriteFile==null||currentWriteFile.getNumber().intValue()<num){ if (currentWriteFile == null || currentWriteFile.getNumber().intValue() < num) {
currentWriteFile=dataFile; currentWriteFile = dataFile;
} }
} }
} }
} }
private DataFile createAndAddDataFile(int num){ private DataFile createAndAddDataFile(int num) {
String fileName=dataFilePrefix+num; String fileName = dataFilePrefix + num;
File file=new File(directory,fileName); File file = new File(directory, fileName);
DataFile result=new DataFile(file,num); DataFile result = new DataFile(file, num);
fileMap.put(result.getNumber(),result); fileMap.put(result.getNumber(), result);
return result; return result;
} }
/* (non-Javadoc) /*
* @see org.apache.activemq.kaha.impl.data.IDataManager#getName() * (non-Javadoc)
*/ *
public String getName(){ * @see org.apache.activemq.kaha.impl.data.IDataManager#getName()
*/
public String getName() {
return name; return name;
} }
synchronized DataFile findSpaceForData(DataItem item) throws IOException{ synchronized DataFile findSpaceForData(DataItem item) throws IOException {
if(currentWriteFile==null||((currentWriteFile.getLength()+item.getSize())>maxFileLength)){ if (currentWriteFile == null || ((currentWriteFile.getLength() + item.getSize()) > maxFileLength)) {
int nextNum=currentWriteFile!=null?currentWriteFile.getNumber().intValue()+1:1; int nextNum = currentWriteFile != null ? currentWriteFile.getNumber().intValue() + 1 : 1;
if(currentWriteFile!=null&&currentWriteFile.isUnused()){ if (currentWriteFile != null && currentWriteFile.isUnused()) {
removeDataFile(currentWriteFile); removeDataFile(currentWriteFile);
} }
currentWriteFile=createAndAddDataFile(nextNum); currentWriteFile = createAndAddDataFile(nextNum);
} }
item.setOffset(currentWriteFile.getLength()); item.setOffset(currentWriteFile.getLength());
item.setFile(currentWriteFile.getNumber().intValue()); item.setFile(currentWriteFile.getNumber().intValue());
currentWriteFile.incrementLength(item.getSize()+ITEM_HEAD_SIZE); currentWriteFile.incrementLength(item.getSize() + ITEM_HEAD_SIZE);
return currentWriteFile; return currentWriteFile;
} }
DataFile getDataFile(StoreLocation item) throws IOException{ DataFile getDataFile(StoreLocation item) throws IOException {
Integer key=Integer.valueOf(item.getFile()); Integer key = Integer.valueOf(item.getFile());
DataFile dataFile=(DataFile) fileMap.get(key); DataFile dataFile = (DataFile)fileMap.get(key);
if(dataFile==null){ if (dataFile == null) {
log.error("Looking for key " + key + " but not found in fileMap: " + fileMap); log.error("Looking for key " + key + " but not found in fileMap: " + fileMap);
throw new IOException("Could not locate data file "+NAME_PREFIX+name+"-"+item.getFile()); throw new IOException("Could not locate data file " + NAME_PREFIX + name + "-" + item.getFile());
} }
return dataFile; return dataFile;
} }
/* (non-Javadoc) /*
* @see org.apache.activemq.kaha.impl.data.IDataManager#readItem(org.apache.activemq.kaha.Marshaller, org.apache.activemq.kaha.StoreLocation) * (non-Javadoc)
*/ *
public synchronized Object readItem(Marshaller marshaller, StoreLocation item) throws IOException{ * @see org.apache.activemq.kaha.impl.data.IDataManager#readItem(org.apache.activemq.kaha.Marshaller,
return getReader().readItem(marshaller,item); * org.apache.activemq.kaha.StoreLocation)
*/
public synchronized Object readItem(Marshaller marshaller, StoreLocation item) throws IOException {
return getReader().readItem(marshaller, item);
} }
/* (non-Javadoc) /*
* @see org.apache.activemq.kaha.impl.data.IDataManager#storeDataItem(org.apache.activemq.kaha.Marshaller, java.lang.Object) * (non-Javadoc)
*/ *
public synchronized StoreLocation storeDataItem(Marshaller marshaller, Object payload) throws IOException{ * @see org.apache.activemq.kaha.impl.data.IDataManager#storeDataItem(org.apache.activemq.kaha.Marshaller,
return getWriter().storeItem(marshaller,payload, DATA_ITEM_TYPE); * java.lang.Object)
*/
public synchronized StoreLocation storeDataItem(Marshaller marshaller, Object payload) throws IOException {
return getWriter().storeItem(marshaller, payload, DATA_ITEM_TYPE);
} }
/* (non-Javadoc) /*
* @see org.apache.activemq.kaha.impl.data.IDataManager#storeRedoItem(java.lang.Object) * (non-Javadoc)
*/ *
public synchronized StoreLocation storeRedoItem(Object payload) throws IOException{ * @see org.apache.activemq.kaha.impl.data.IDataManager#storeRedoItem(java.lang.Object)
*/
public synchronized StoreLocation storeRedoItem(Object payload) throws IOException {
return getWriter().storeItem(redoMarshaller, payload, REDO_ITEM_TYPE); return getWriter().storeItem(redoMarshaller, payload, REDO_ITEM_TYPE);
} }
/* (non-Javadoc) /*
* @see org.apache.activemq.kaha.impl.data.IDataManager#updateItem(org.apache.activemq.kaha.StoreLocation, org.apache.activemq.kaha.Marshaller, java.lang.Object) * (non-Javadoc)
*/ *
public synchronized void updateItem(StoreLocation location,Marshaller marshaller, Object payload) throws IOException { * @see org.apache.activemq.kaha.impl.data.IDataManager#updateItem(org.apache.activemq.kaha.StoreLocation,
getWriter().updateItem((DataItem)location,marshaller,payload,DATA_ITEM_TYPE); * org.apache.activemq.kaha.Marshaller, java.lang.Object)
*/
public synchronized void updateItem(StoreLocation location, Marshaller marshaller, Object payload)
throws IOException {
getWriter().updateItem((DataItem)location, marshaller, payload, DATA_ITEM_TYPE);
} }
/* (non-Javadoc) /*
* @see org.apache.activemq.kaha.impl.data.IDataManager#recoverRedoItems(org.apache.activemq.kaha.impl.data.RedoListener) * (non-Javadoc)
*/ *
public synchronized void recoverRedoItems(RedoListener listener) throws IOException{ * @see org.apache.activemq.kaha.impl.data.IDataManager#recoverRedoItems(org.apache.activemq.kaha.impl.data.RedoListener)
*/
public synchronized void recoverRedoItems(RedoListener listener) throws IOException {
// Nothing to recover if there is no current file. // Nothing to recover if there is no current file.
if( currentWriteFile == null ) if (currentWriteFile == null)
return; return;
DataItem item = new DataItem(); DataItem item = new DataItem();
item.setFile(currentWriteFile.getNumber().intValue()); item.setFile(currentWriteFile.getNumber().intValue());
item.setOffset(0); item.setOffset(0);
while( true ) { while (true) {
byte type; byte type;
try { try {
type = getReader().readDataItemSize(item); type = getReader().readDataItemSize(item);
} catch (IOException ignore) { } catch (IOException ignore) {
log.trace("End of data file reached at (header was invalid): "+item); log.trace("End of data file reached at (header was invalid): " + item);
return; return;
} }
if( type == REDO_ITEM_TYPE ) { if (type == REDO_ITEM_TYPE) {
// Un-marshal the redo item // Un-marshal the redo item
Object object; Object object;
try { try {
object = readItem(redoMarshaller, item); object = readItem(redoMarshaller, item);
} catch (IOException e1) { } catch (IOException e1) {
log.trace("End of data file reached at (payload was invalid): "+item); log.trace("End of data file reached at (payload was invalid): " + item);
return; return;
} }
try { try {
listener.onRedoItem(item, object); listener.onRedoItem(item, object);
// in case the listener is holding on to item references, copy it // in case the listener is holding on to item references,
// copy it
// so we don't change it behind the listener's back. // so we don't change it behind the listener's back.
item = item.copy(); item = item.copy();
} catch (Exception e) { } catch (Exception e) {
throw IOExceptionSupport.create("Recovery handler failed: "+e,e); throw IOExceptionSupport.create("Recovery handler failed: " + e, e);
} }
} }
// Move to the next item. // Move to the next item.
item.setOffset(item.getOffset()+ITEM_HEAD_SIZE+item.getSize()); item.setOffset(item.getOffset() + ITEM_HEAD_SIZE + item.getSize());
} }
} }
/* (non-Javadoc) /*
* @see org.apache.activemq.kaha.impl.data.IDataManager#close() * (non-Javadoc)
*/ *
public synchronized void close() throws IOException{ * @see org.apache.activemq.kaha.impl.data.IDataManager#close()
getWriter().close(); */
for(Iterator i=fileMap.values().iterator();i.hasNext();){ public synchronized void close() throws IOException {
DataFile dataFile=(DataFile) i.next(); getWriter().close();
for (Iterator i = fileMap.values().iterator(); i.hasNext();) {
DataFile dataFile = (DataFile)i.next();
getWriter().force(dataFile); getWriter().force(dataFile);
dataFile.close(); dataFile.close();
} }
fileMap.clear(); fileMap.clear();
} }
/* (non-Javadoc) /*
* @see org.apache.activemq.kaha.impl.data.IDataManager#force() * (non-Javadoc)
*/ *
public synchronized void force() throws IOException{ * @see org.apache.activemq.kaha.impl.data.IDataManager#force()
for(Iterator i=fileMap.values().iterator();i.hasNext();){ */
DataFile dataFile=(DataFile) i.next(); public synchronized void force() throws IOException {
for (Iterator i = fileMap.values().iterator(); i.hasNext();) {
DataFile dataFile = (DataFile)i.next();
getWriter().force(dataFile); getWriter().force(dataFile);
} }
} }
/*
/* (non-Javadoc) * (non-Javadoc)
* @see org.apache.activemq.kaha.impl.data.IDataManager#delete() *
*/ * @see org.apache.activemq.kaha.impl.data.IDataManager#delete()
public synchronized boolean delete() throws IOException{ */
boolean result=true; public synchronized boolean delete() throws IOException {
for(Iterator i=fileMap.values().iterator();i.hasNext();){ boolean result = true;
DataFile dataFile=(DataFile) i.next(); for (Iterator i = fileMap.values().iterator(); i.hasNext();) {
result&=dataFile.delete(); DataFile dataFile = (DataFile)i.next();
result &= dataFile.delete();
} }
fileMap.clear(); fileMap.clear();
return result; return result;
} }
/* (non-Javadoc) /*
* @see org.apache.activemq.kaha.impl.data.IDataManager#addInterestInFile(int) * (non-Javadoc)
*/ *
public synchronized void addInterestInFile(int file) throws IOException{ * @see org.apache.activemq.kaha.impl.data.IDataManager#addInterestInFile(int)
if(file>=0){ */
Integer key=Integer.valueOf(file); public synchronized void addInterestInFile(int file) throws IOException {
DataFile dataFile=(DataFile) fileMap.get(key); if (file >= 0) {
if(dataFile==null){ Integer key = Integer.valueOf(file);
dataFile=createAndAddDataFile(file); DataFile dataFile = (DataFile)fileMap.get(key);
if (dataFile == null) {
dataFile = createAndAddDataFile(file);
} }
addInterestInFile(dataFile); addInterestInFile(dataFile);
} }
} }
synchronized void addInterestInFile(DataFile dataFile){ synchronized void addInterestInFile(DataFile dataFile) {
if(dataFile!=null){ if (dataFile != null) {
dataFile.increment(); dataFile.increment();
} }
} }
/* (non-Javadoc) /*
* @see org.apache.activemq.kaha.impl.data.IDataManager#removeInterestInFile(int) * (non-Javadoc)
*/ *
public synchronized void removeInterestInFile(int file) throws IOException{ * @see org.apache.activemq.kaha.impl.data.IDataManager#removeInterestInFile(int)
if(file>=0){ */
Integer key=Integer.valueOf(file); public synchronized void removeInterestInFile(int file) throws IOException {
DataFile dataFile=(DataFile) fileMap.get(key); if (file >= 0) {
Integer key = Integer.valueOf(file);
DataFile dataFile = (DataFile)fileMap.get(key);
removeInterestInFile(dataFile); removeInterestInFile(dataFile);
} }
} }
synchronized void removeInterestInFile(DataFile dataFile) throws IOException{ synchronized void removeInterestInFile(DataFile dataFile) throws IOException {
if(dataFile!=null){ if (dataFile != null) {
if(dataFile.decrement()<=0){ if (dataFile.decrement() <= 0) {
if(dataFile!=currentWriteFile){ if (dataFile != currentWriteFile) {
removeDataFile(dataFile); removeDataFile(dataFile);
} }
} }
} }
} }
/* (non-Javadoc) /*
* @see org.apache.activemq.kaha.impl.data.IDataManager#consolidateDataFiles() * (non-Javadoc)
*/ *
public synchronized void consolidateDataFiles() throws IOException{ * @see org.apache.activemq.kaha.impl.data.IDataManager#consolidateDataFiles()
List purgeList=new ArrayList(); */
for(Iterator i=fileMap.values().iterator();i.hasNext();){ public synchronized void consolidateDataFiles() throws IOException {
DataFile dataFile=(DataFile) i.next(); List purgeList = new ArrayList();
if(dataFile.isUnused() && dataFile != currentWriteFile){ for (Iterator i = fileMap.values().iterator(); i.hasNext();) {
DataFile dataFile = (DataFile)i.next();
if (dataFile.isUnused() && dataFile != currentWriteFile) {
purgeList.add(dataFile); purgeList.add(dataFile);
} }
} }
for(int i=0;i<purgeList.size();i++){ for (int i = 0; i < purgeList.size(); i++) {
DataFile dataFile=(DataFile) purgeList.get(i); DataFile dataFile = (DataFile)purgeList.get(i);
removeDataFile(dataFile); removeDataFile(dataFile);
} }
} }
private void removeDataFile(DataFile dataFile) throws IOException{ private void removeDataFile(DataFile dataFile) throws IOException {
fileMap.remove(dataFile.getNumber()); fileMap.remove(dataFile.getNumber());
if(writer!=null){ if (writer != null) {
writer.force(dataFile); writer.force(dataFile);
} }
boolean result=dataFile.delete(); boolean result = dataFile.delete();
log.debug("discarding data file "+dataFile+(result?"successful ":"failed")); log.debug("discarding data file " + dataFile + (result ? "successful " : "failed"));
} }
/* (non-Javadoc) /*
* @see org.apache.activemq.kaha.impl.data.IDataManager#getRedoMarshaller() * (non-Javadoc)
*/ *
* @see org.apache.activemq.kaha.impl.data.IDataManager#getRedoMarshaller()
*/
public Marshaller getRedoMarshaller() { public Marshaller getRedoMarshaller() {
return redoMarshaller; return redoMarshaller;
} }
/* (non-Javadoc) /*
* @see org.apache.activemq.kaha.impl.data.IDataManager#setRedoMarshaller(org.apache.activemq.kaha.Marshaller) * (non-Javadoc)
*/ *
* @see org.apache.activemq.kaha.impl.data.IDataManager#setRedoMarshaller(org.apache.activemq.kaha.Marshaller)
*/
public void setRedoMarshaller(Marshaller redoMarshaller) { public void setRedoMarshaller(Marshaller redoMarshaller) {
this.redoMarshaller = redoMarshaller; this.redoMarshaller = redoMarshaller;
} }
@ -317,45 +349,49 @@ public final class DataManagerImpl implements DataManager {
/** /**
* @return the maxFileLength * @return the maxFileLength
*/ */
public long getMaxFileLength(){ public long getMaxFileLength() {
return maxFileLength; return maxFileLength;
} }
/** /**
* @param maxFileLength the maxFileLength to set * @param maxFileLength the maxFileLength to set
*/ */
public void setMaxFileLength(long maxFileLength){ public void setMaxFileLength(long maxFileLength) {
this.maxFileLength=maxFileLength; this.maxFileLength = maxFileLength;
}
public String toString(){
return "DataManager:("+NAME_PREFIX+name+")";
} }
public synchronized SyncDataFileReader getReader() { public String toString() {
if( reader == null ) { return "DataManager:(" + NAME_PREFIX + name + ")";
reader = createReader(); }
}
return reader;
}
protected synchronized SyncDataFileReader createReader() {
return new SyncDataFileReader(this);
}
public synchronized void setReader(SyncDataFileReader reader) {
this.reader = reader;
}
public synchronized SyncDataFileWriter getWriter() { public synchronized SyncDataFileReader getReader() {
if( writer==null ) { if (reader == null) {
writer = createWriter(); reader = createReader();
} }
return writer; return reader;
} }
private SyncDataFileWriter createWriter() {
return new SyncDataFileWriter(this); protected synchronized SyncDataFileReader createReader() {
} return new SyncDataFileReader(this);
public synchronized void setWriter(SyncDataFileWriter writer) { }
this.writer = writer;
} public synchronized void setReader(SyncDataFileReader reader) {
this.reader = reader;
}
public synchronized SyncDataFileWriter getWriter() {
if (writer == null) {
writer = createWriter();
}
return writer;
}
private SyncDataFileWriter createWriter() {
return new SyncDataFileWriter(this);
}
public synchronized void setWriter(SyncDataFileWriter writer) {
this.writer = writer;
}
} }

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