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.Topic;
import org.apache.activemq.command.ActiveMQBytesMessage;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQMapMessage;
@ -46,65 +45,66 @@ import org.apache.activemq.command.ActiveMQTextMessage;
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 $
*/
public class ActiveMQMessageTransformation {
/**
/**
* Creates a an available JMS message from another provider.
*
* @param destination - Destination to be converted into ActiveMQ's implementation.
* @return ActiveMQDestination - ActiveMQ's implementation of the destination.
* @throws JMSException if an error occurs
*/
public static ActiveMQDestination transformDestination(Destination destination) throws JMSException {
*
* @param destination - Destination to be converted into ActiveMQ's
* implementation.
* @return ActiveMQDestination - ActiveMQ's implementation of the
* destination.
* @throws JMSException if an error occurs
*/
public static ActiveMQDestination transformDestination(Destination destination) throws JMSException {
ActiveMQDestination activeMQDestination = null;
if (destination != null) {
if (destination instanceof ActiveMQDestination) {
return (ActiveMQDestination) destination;
}
else {
return (ActiveMQDestination)destination;
} else {
if (destination instanceof TemporaryQueue) {
activeMQDestination = new ActiveMQTempQueue(((Queue) destination).getQueueName());
}
else if (destination instanceof TemporaryTopic) {
activeMQDestination = new ActiveMQTempTopic(((Topic) destination).getTopicName());
}
else if (destination instanceof Queue) {
activeMQDestination = new ActiveMQQueue(((Queue) destination).getQueueName());
}
else if (destination instanceof Topic) {
activeMQDestination = new ActiveMQTopic(((Topic) destination).getTopicName());
activeMQDestination = new ActiveMQTempQueue(((Queue)destination).getQueueName());
} else if (destination instanceof TemporaryTopic) {
activeMQDestination = new ActiveMQTempTopic(((Topic)destination).getTopicName());
} else if (destination instanceof Queue) {
activeMQDestination = new ActiveMQQueue(((Queue)destination).getQueueName());
} 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
* message instance from an available JMS message from another provider.
*
* Creates a fast shallow copy of the current ActiveMQMessage or creates a
* whole new message instance from an available JMS message from another
* provider.
*
* @param message - Message to be converted into ActiveMQ's implementation.
* @param connection
* @return ActiveMQMessage - ActiveMQ's implementation object of the message.
* @param connection
* @return ActiveMQMessage - ActiveMQ's implementation object of the
* message.
* @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) {
return (ActiveMQMessage) message;
return (ActiveMQMessage)message;
} else {
ActiveMQMessage activeMessage = null;
if (message instanceof BytesMessage) {
BytesMessage bytesMsg = (BytesMessage) message;
BytesMessage bytesMsg = (BytesMessage)message;
bytesMsg.reset();
ActiveMQBytesMessage msg = new ActiveMQBytesMessage();
msg.setConnection(connection);
@ -121,7 +121,7 @@ public class ActiveMQMessageTransformation {
activeMessage = msg;
} else if (message instanceof MapMessage) {
MapMessage mapMsg = (MapMessage) message;
MapMessage mapMsg = (MapMessage)message;
ActiveMQMapMessage msg = new ActiveMQMapMessage();
msg.setConnection(connection);
Enumeration iter = mapMsg.getMapNames();
@ -133,14 +133,14 @@ public class ActiveMQMessageTransformation {
activeMessage = msg;
} else if (message instanceof ObjectMessage) {
ObjectMessage objMsg = (ObjectMessage) message;
ObjectMessage objMsg = (ObjectMessage)message;
ActiveMQObjectMessage msg = new ActiveMQObjectMessage();
msg.setConnection(connection);
msg.setObject(objMsg.getObject());
msg.storeContent();
activeMessage = msg;
} else if (message instanceof StreamMessage) {
StreamMessage streamMessage = (StreamMessage) message;
StreamMessage streamMessage = (StreamMessage)message;
streamMessage.reset();
ActiveMQStreamMessage msg = new ActiveMQStreamMessage();
msg.setConnection(connection);
@ -157,7 +157,7 @@ public class ActiveMQMessageTransformation {
activeMessage = msg;
} else if (message instanceof TextMessage) {
TextMessage textMsg = (TextMessage) message;
TextMessage textMsg = (TextMessage)message;
ActiveMQTextMessage msg = new ActiveMQTextMessage();
msg.setConnection(connection);
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 toMesage the message to add the properties to
* @throws JMSException

View File

@ -16,22 +16,20 @@
*/
package org.apache.activemq;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ConsumerId;
import javax.jms.JMSException;
import javax.jms.Queue;
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
* have been delivered to a queue.
* <p/>
* have been delivered to a queue. <p/>
* <P>
* 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
* between the <CODE>QueueReceiver</CODE>s.
* <p/>
* between the <CODE>QueueReceiver</CODE>s. <p/>
* <P>
* If a <CODE>QueueReceiver</CODE> specifies a message selector, the messages
* 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
* does not retain the partial order defined by each message producer. Only
* <CODE>QueueReceiver</CODE> s without a message selector will read messages
* in message producer order.
* <p/>
* in message producer order. <p/>
* <P>
* Creating a <CODE>MessageConsumer</CODE> provides the same features as
* creating a <CODE>QueueReceiver</CODE>. A <CODE>MessageConsumer</CODE>
* 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)
* @see javax.jms.QueueSession#createReceiver(Queue, String)
@ -54,8 +52,7 @@ import javax.jms.QueueReceiver;
* @see javax.jms.MessageConsumer
*/
public class ActiveMQQueueReceiver extends ActiveMQMessageConsumer implements
QueueReceiver {
public class ActiveMQQueueReceiver extends ActiveMQMessageConsumer implements QueueReceiver {
/**
* @param theSession
@ -63,26 +60,28 @@ public class ActiveMQQueueReceiver extends ActiveMQMessageConsumer implements
* @param destination
* @param messageSelector
* @param prefetch
* @param asyncDispatch
* @param asyncDispatch
* @throws JMSException
*/
protected ActiveMQQueueReceiver(ActiveMQSession theSession,
ConsumerId consumerId, ActiveMQDestination destination, String selector, int prefetch, int maximumPendingMessageCount, boolean asyncDispatch)
throws JMSException {
super(theSession, consumerId, destination, null, selector, prefetch, maximumPendingMessageCount, false, false, asyncDispatch);
protected ActiveMQQueueReceiver(ActiveMQSession theSession, ConsumerId consumerId,
ActiveMQDestination destination, String selector, int prefetch,
int maximumPendingMessageCount, boolean asyncDispatch)
throws JMSException {
super(theSession, consumerId, destination, null, selector, prefetch, maximumPendingMessageCount,
false, false, asyncDispatch);
}
/**
* Gets the <CODE>Queue</CODE> associated with this queue receiver.
*
*
* @return this receiver's <CODE>Queue</CODE>
* @throws JMSException if the JMS provider fails to get the queue for this queue
* receiver due to some internal error.
* @throws JMSException if the JMS provider fails to get the queue for this
* queue receiver due to some internal error.
*/
public Queue getQueue() throws JMSException {
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
* queue.
* <p/>
* queue. <p/>
* <P>
* 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>
* methods for an unidentified <CODE>QueueSender</CODE> will throw a <CODE>
* </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>.
* <p/>
* <P>
* If the <CODE>QueueSender</CODE> is created with an unidentified <CODE>
* Queue</CODE>, an attempt to use the <CODE>send</CODE> methods that
* assume that the <CODE>Queue</CODE> has been identified will throw a <CODE>
* Queue</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>.
* <p/>
* <P>
* During the execution of its <CODE>send</CODE> method, a message must not
* be changed by other threads within the client. If the message is modified,
* the result of the <CODE>send</CODE> is undefined.
* <p/>
* During the execution of its <CODE>send</CODE> method, a message must not be
* changed by other threads within the client. If the message is modified, the
* result of the <CODE>send</CODE> is undefined. <p/>
* <P>
* 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
* times.
* <p/>
* times. <p/>
* <P>
* The following message headers are set as part of sending a message: <code>JMSDestination</code>,
* <code>JMSDeliveryMode</code>,<code>JMSExpiration</code>,<code>JMSPriority</code>,
* The following message headers are set as part of sending a message:
* <code>JMSDestination</code>, <code>JMSDeliveryMode</code>,<code>JMSExpiration</code>,<code>JMSPriority</code>,
* <code>JMSMessageID</code> and <code>JMSTimeStamp</code>. When the
* message is sent, the values of these headers are ignored. After the
* completion of the <CODE>send</CODE>, the headers hold the values
* specified by the method sending the message. It is possible for the <code>send</code>
* completion of the <CODE>send</CODE>, the headers hold the values specified
* 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>
* if the setting of these headers is explicitly disabled by the <code>MessageProducer.setDisableMessageID</code>
* or <code>MessageProducer.setDisableMessageTimestamp</code> method.
* <p/>
* if the setting of these headers is explicitly disabled by the
* <code>MessageProducer.setDisableMessageID</code> or
* <code>MessageProducer.setDisableMessageTimestamp</code> method. <p/>
* <P>
* Creating a <CODE>MessageProducer</CODE> provides the same features as
* creating a <CODE>QueueSender</CODE>. A <CODE>MessageProducer</CODE>
* object is recommended when creating new code. The <CODE>QueueSender</CODE>
* is provided to support existing code.
*
*
* @see javax.jms.MessageProducer
* @see javax.jms.QueueSession#createSender(Queue)
*/
@ -74,38 +73,35 @@ import org.apache.activemq.command.ActiveMQDestination;
public class ActiveMQQueueSender extends ActiveMQMessageProducer implements QueueSender {
protected ActiveMQQueueSender(ActiveMQSession session, ActiveMQDestination destination)
throws JMSException {
super(session,
session.getNextProducerId(),
destination);
throws JMSException {
super(session, session.getNextProducerId(), destination);
}
/**
* Gets the queue associated with this <CODE>QueueSender</CODE>.
*
*
* @return this sender's queue
* @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 {
return (Queue) super.getDestination();
return (Queue)super.getDestination();
}
/**
* Sends a message to a queue for an unidentified message producer. Uses
* the <CODE>QueueSender</CODE>'s default delivery mode, priority, and
* time to live.
* <p/>
* Sends a message to a queue for an unidentified message producer. Uses the
* <CODE>QueueSender</CODE>'s default delivery mode, priority, and time
* to live. <p/>
* <P>
* Typically, a message producer is assigned a queue at creation time;
* 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
* @throws JMSException if the JMS provider fails to send the message due to some
* internal error.
* @throws JMSException if the JMS provider fails to send the message due to
* some internal error.
* @see javax.jms.MessageProducer#getDeliveryMode()
* @see javax.jms.MessageProducer#getTimeToLive()
* @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,
* specifying delivery mode, priority and time to live.
* <p/>
* specifying delivery mode, priority and time to live. <p/>
* <P>
* Typically, a message producer is assigned a queue at creation time;
* 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 priority the priority for this message
* @param timeToLive the message's lifetime (in milliseconds)
* @throws JMSException if the JMS provider fails to send the message due to some
* internal error.
* @param priority the priority for this message
* @param timeToLive the message's lifetime (in milliseconds)
* @throws JMSException if the JMS provider fails to send the message due to
* some internal error.
*/
public void send(Queue queue, Message message, int deliveryMode, int priority, long timeToLive)
throws JMSException {
super.send(queue,
message,
deliveryMode,
priority,
timeToLive);
throws JMSException {
super.send(queue, message, deliveryMode, priority, timeToLive);
}
}

View File

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

View File

@ -104,8 +104,9 @@ public class ActiveMQTopicSession implements TopicSession {
* @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");
}
return next.createConsumer(destination);
}
@ -116,8 +117,9 @@ public class ActiveMQTopicSession implements TopicSession {
* @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");
}
return next.createConsumer(destination, messageSelector);
}
@ -129,8 +131,9 @@ public class ActiveMQTopicSession implements TopicSession {
* @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");
}
return next.createConsumer(destination, messageSelector, NoLocal);
}
@ -195,8 +198,9 @@ public class ActiveMQTopicSession implements TopicSession {
* @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");
}
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
* that provide a close() method. Useful for when you want to collect
* a heterogeous set of JMS object in a collection to be closed at a later time.
*
* that provide a close() method. Useful for when you want to collect a
* heterogeous set of JMS object in a collection to be closed at a later time.
*
* @version $Revision: 1.2 $
*/
public interface Closeable {
/**
* Closes a JMS object.
* <P>
* 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.
*/
public void close() throws JMSException;
/**
* Closes a JMS object.
* <P>
* 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.
*/
public void close() throws JMSException;
}

View File

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

View File

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

View File

@ -30,8 +30,8 @@ import javax.jms.JMSException;
import org.apache.activemq.command.ActiveMQBlobMessage;
/**
* A default implementation of {@link BlobUploadStrategy} which uses the URL class to upload
* files or streams to a remote URL
* A default implementation of {@link BlobUploadStrategy} which uses the URL
* class to upload files or streams to a remote URL
*/
public class DefaultBlobUploadStrategy implements BlobUploadStrategy {
private BlobTransferPolicy transferPolicy;
@ -50,30 +50,31 @@ public class DefaultBlobUploadStrategy implements BlobUploadStrategy {
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("PUT");
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)
connection.setChunkedStreamingMode(transferPolicy.getBufferSize());
OutputStream os = connection.getOutputStream();
byte[] buf = new byte[transferPolicy.getBufferSize()];
for (int c = fis.read(buf); c != -1; c = fis.read(buf)) {
os.write(buf, 0, c);
os.flush();
os.write(buf, 0, c);
os.flush();
}
os.close();
fis.close();
if (!isSuccessfulCode(connection.getResponseCode())) {
throw new IOException("PUT was not successful: "
+ connection.getResponseCode() + " " + connection.getResponseMessage());
throw new IOException("PUT was not successful: " + connection.getResponseCode() + " "
+ connection.getResponseMessage());
}
return url;
}
public void deleteFile(ActiveMQBlobMessage message) throws IOException, JMSException {
public void deleteFile(ActiveMQBlobMessage message) throws IOException, JMSException {
URL url = createUploadURL(message);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
@ -82,16 +83,16 @@ public class DefaultBlobUploadStrategy implements BlobUploadStrategy {
connection.disconnect();
if (!isSuccessfulCode(connection.getResponseCode())) {
throw new IOException("DELETE was not successful: "
+ connection.getResponseCode() + " " + connection.getResponseMessage());
throw new IOException("DELETE was not successful: " + connection.getResponseCode() + " "
+ 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());
}
}

View File

@ -23,26 +23,28 @@ import org.apache.activemq.util.FactoryFinder;
import org.apache.activemq.util.IOExceptionSupport;
/**
* A helper class to create a fully configured broker service using a URI.
* The list of currently supported URI syntaxes is described
* <a href="http://activemq.apache.org/how-do-i-embed-a-broker-inside-a-connection.html">here</a>
* A helper class to create a fully configured broker service using a URI. The
* list of currently supported URI syntaxes is described <a
* href="http://activemq.apache.org/how-do-i-embed-a-broker-inside-a-connection.html">here</a>
*
* @version $Revision$
*/
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 {
try {
return (BrokerFactoryHandler)brokerFactoryHandlerFinder.newInstance(type);
} 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
*
* @param brokerURI the URI scheme to configure the broker
* @throws Exception
*/
@ -52,14 +54,17 @@ public class BrokerFactory {
/**
* Creates a broker from a URI configuration
*
* @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
*/
public static BrokerService createBroker(URI brokerURI, boolean startBroker) throws Exception {
if( brokerURI.getScheme() == null )
throw new IllegalArgumentException("Invalid broker URI, no scheme specified: "+brokerURI);
if (brokerURI.getScheme() == null) {
throw new IllegalArgumentException("Invalid broker URI, no scheme specified: " + brokerURI);
}
BrokerFactoryHandler handler = createBrokerFactoryHandler(brokerURI.getScheme());
BrokerService broker = handler.createBroker(brokerURI);
if (startBroker) {
@ -68,9 +73,9 @@ public class BrokerFactory {
return broker;
}
/**
* Creates a broker from a URI configuration
*
* @param brokerURI the URI scheme to configure the broker
* @throws Exception
*/
@ -78,16 +83,17 @@ public class BrokerFactory {
return createBroker(new URI(brokerURI));
}
/**
* Creates a broker from a URI configuration
*
* @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
*/
public static BrokerService createBroker(String brokerURI, boolean startBroker) throws Exception {
return createBroker(new URI(brokerURI), startBroker);
}
}

View File

@ -17,29 +17,30 @@
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
*/
public class BrokerStoppedException extends IllegalStateException {
private static final long serialVersionUID = -3435230276850902220L;
private static final long serialVersionUID = -3435230276850902220L;
public BrokerStoppedException() {
super();
}
public BrokerStoppedException() {
super();
}
public BrokerStoppedException(String message, Throwable cause) {
super(message);
initCause(cause);
}
public BrokerStoppedException(String message, Throwable cause) {
super(message);
initCause(cause);
}
public BrokerStoppedException(String s) {
super(s);
}
public BrokerStoppedException(String s) {
super(s);
}
public BrokerStoppedException(Throwable cause) {
initCause(cause);
}
public BrokerStoppedException(Throwable cause) {
initCause(cause);
}
}

View File

@ -24,7 +24,6 @@ import org.apache.activemq.command.Command;
import org.apache.activemq.command.Response;
/**
*
* @version $Revision: 1.5 $
*/
public interface Connection extends Service {
@ -37,8 +36,7 @@ public interface Connection extends Service {
/**
* Sends a message to the client.
*
* @param message
* the message to send to the client.
* @param message the message to send to the client.
*/
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
*/
public int getDispatchQueueSize();
/**
* Returns the statistics for this connection
*/
public ConnectionStatistics getStatistics();
/**
* @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
*/
public String getRemoteAddress();
public String getRemoteAddress();
public void serviceExceptionAsync(IOException e);
public String getConnectionId();
public void serviceExceptionAsync(IOException e);
public String getConnectionId();
}

View File

@ -97,7 +97,8 @@ import org.apache.commons.logging.LogFactory;
public class TransportConnection implements Service, Connection, Task, CommandVisitor {
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");
// Keeps track of the broker and connector that created this connection.
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
* 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.broker = broker;
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) {
if (!disposed.get()) {
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();
ce.setException(e);
dispatchSync(ce);
@ -400,7 +403,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
}
TransactionState transactionState = cs.getTransactionState(info.getTransactionId());
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.
if (!transactionState.isPrepared()) {
transactionState.setPrepared(true);
@ -469,7 +473,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
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);
return null;
}
@ -498,7 +503,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
TransportConnectionState cs = lookupConnectionState(connectionId);
SessionState ss = cs.getSessionState(sessionId);
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
if (!ss.getProducerIds().contains(info.getProducerId())) {
broker.addProducer(cs.getContext(), info);
@ -517,7 +524,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
TransportConnectionState cs = lookupConnectionState(connectionId);
SessionState ss = cs.getSessionState(sessionId);
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);
if (ps == null)
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);
SessionState ss = cs.getSessionState(sessionId);
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
if (!ss.getConsumerIds().contains(info.getConsumerId())) {
broker.addConsumer(cs.getContext(), info);
@ -551,7 +562,9 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
TransportConnectionState cs = lookupConnectionState(connectionId);
SessionState ss = cs.getSessionState(sessionId);
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);
if (consumerState == null)
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) {
LOG.debug("Killing previous stale connection: " + state.getConnection().getRemoteAddress());
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.reset(info);
}
@ -751,7 +765,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
}
protected void processDispatch(Command command) throws IOException {
final MessageDispatch messageDispatch = (MessageDispatch)(command.isMessageDispatch() ? command : null);
final MessageDispatch messageDispatch = (MessageDispatch)(command.isMessageDispatch()
? command : null);
try {
if (!disposed.get()) {
if (messageDispatch != null) {
@ -831,7 +846,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
transport.start();
if (taskRunnerFactory != null) {
taskRunner = taskRunnerFactory.createTaskRunner(this, "ActiveMQ Connection Dispatcher: " + getRemoteAddress());
taskRunner = taskRunnerFactory.createTaskRunner(this, "ActiveMQ Connection Dispatcher: "
+ getRemoteAddress());
} else {
taskRunner = null;
}
@ -1098,7 +1114,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
uri = URISupport.createURIWithQuery(uri, URISupport.createQueryString(map));
Transport localTransport = TransportFactory.connect(uri);
Transport remoteBridgeTransport = new ResponseCorrelator(transport);
duplexBridge = NetworkBridgeFactory.createBridge(config, localTransport, remoteBridgeTransport);
duplexBridge = NetworkBridgeFactory.createBridge(config, localTransport,
remoteBridgeTransport);
// now turn duplex off this side
info.setDuplexConnection(false);
duplexBridge.setCreatedByDuplex(true);
@ -1163,7 +1180,8 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
ProducerState producerState = ss.getProducerState(id);
if (producerState != null && producerState.getInfo() != null) {
ProducerInfo info = producerState.getInfo();
result.setMutable(info.getDestination() == null || info.getDestination().isComposite());
result.setMutable(info.getDestination() == null
|| info.getDestination().isComposite());
}
}
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;
connectionState = state;
return rc;
@ -1290,35 +1309,44 @@ public class TransportConnection implements Service, Connection, Task, CommandVi
protected TransportConnectionState lookupConnectionState(String connectionId) {
TransportConnectionState cs = connectionState;
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;
}
protected TransportConnectionState lookupConnectionState(ConsumerId id) {
TransportConnectionState cs = connectionState;
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;
}
protected TransportConnectionState lookupConnectionState(ProducerId id) {
TransportConnectionState cs = connectionState;
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;
}
protected TransportConnectionState lookupConnectionState(SessionId id) {
TransportConnectionState cs = connectionState;
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;
}
protected TransportConnectionState lookupConnectionState(ConnectionId connectionId) {
TransportConnectionState cs = connectionState;
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;
}

View File

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

View File

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

View File

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

View File

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

View File

@ -25,92 +25,92 @@ public class NetworkConnectorView implements NetworkConnectorViewMBean {
public NetworkConnectorView(NetworkConnector connector) {
this.connector = connector;
}
public void start() throws Exception {
connector.start();
}
public void stop() throws Exception {
connector.stop();
connector.stop();
}
public String getName() {
return connector.getName();
}
public String getName() {
return connector.getName();
}
public int getNetworkTTL() {
return connector.getNetworkTTL();
}
public int getNetworkTTL() {
return connector.getNetworkTTL();
}
public int getPrefetchSize() {
return connector.getPrefetchSize();
}
public int getPrefetchSize() {
return connector.getPrefetchSize();
}
public String getUserName() {
return connector.getUserName();
}
public String getUserName() {
return connector.getUserName();
}
public boolean isBridgeTempDestinations() {
return connector.isBridgeTempDestinations();
}
public boolean isBridgeTempDestinations() {
return connector.isBridgeTempDestinations();
}
public boolean isConduitSubscriptions() {
return connector.isConduitSubscriptions();
}
public boolean isConduitSubscriptions() {
return connector.isConduitSubscriptions();
}
public boolean isDecreaseNetworkConsumerPriority() {
return connector.isDecreaseNetworkConsumerPriority();
}
public boolean isDecreaseNetworkConsumerPriority() {
return connector.isDecreaseNetworkConsumerPriority();
}
public boolean isDispatchAsync() {
return connector.isDispatchAsync();
}
public boolean isDispatchAsync() {
return connector.isDispatchAsync();
}
public boolean isDynamicOnly() {
return connector.isDynamicOnly();
}
public boolean isDynamicOnly() {
return connector.isDynamicOnly();
}
public void setBridgeTempDestinations(boolean bridgeTempDestinations) {
connector.setBridgeTempDestinations(bridgeTempDestinations);
}
public void setBridgeTempDestinations(boolean bridgeTempDestinations) {
connector.setBridgeTempDestinations(bridgeTempDestinations);
}
public void setConduitSubscriptions(boolean conduitSubscriptions) {
connector.setConduitSubscriptions(conduitSubscriptions);
}
public void setConduitSubscriptions(boolean conduitSubscriptions) {
connector.setConduitSubscriptions(conduitSubscriptions);
}
public void setDispatchAsync(boolean dispatchAsync) {
connector.setDispatchAsync(dispatchAsync);
}
public void setDispatchAsync(boolean dispatchAsync) {
connector.setDispatchAsync(dispatchAsync);
}
public void setDynamicOnly(boolean dynamicOnly) {
connector.setDynamicOnly(dynamicOnly);
}
public void setDynamicOnly(boolean dynamicOnly) {
connector.setDynamicOnly(dynamicOnly);
}
public void setNetworkTTL(int networkTTL) {
connector.setNetworkTTL(networkTTL);
}
public void setNetworkTTL(int networkTTL) {
connector.setNetworkTTL(networkTTL);
}
public void setPassword(String password) {
connector.setPassword(password);
}
public void setPassword(String password) {
connector.setPassword(password);
}
public void setPrefetchSize(int prefetchSize) {
connector.setPrefetchSize(prefetchSize);
}
public void setPrefetchSize(int prefetchSize) {
connector.setPrefetchSize(prefetchSize);
}
public void setUserName(String userName) {
connector.setUserName(userName);
}
public void setUserName(String userName) {
connector.setUserName(userName);
}
public String getPassword() {
String pw = connector.getPassword();
// Hide the password for security reasons.
if( pw!= null )
pw = pw.replaceAll(".", "*");
return pw;
}
public String getPassword() {
String pw = connector.getPassword();
// Hide the password for security reasons.
if (pw != null)
pw = pw.replaceAll(".", "*");
return pw;
}
public void setDecreaseNetworkConsumerPriority(boolean decreaseNetworkConsumerPriority) {
connector.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority);
}
public void setDecreaseNetworkConsumerPriority(boolean decreaseNetworkConsumerPriority) {
connector.setDecreaseNetworkConsumerPriority(decreaseNetworkConsumerPriority);
}
}

View File

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

View File

@ -29,7 +29,7 @@ public class TopicSubscriptionView extends SubscriptionView implements TopicSubs
}
protected TopicSubscription getTopicSubscription() {
return (TopicSubscription) subscription;
return (TopicSubscription)subscription;
}
/**
@ -47,14 +47,14 @@ public class TopicSubscriptionView extends SubscriptionView implements TopicSubs
TopicSubscription topicSubscription = getTopicSubscription();
return topicSubscription != null ? topicSubscription.getMaximumPendingMessages() : 0;
}
/**
*
*/
public void setMaximumPendingQueueSize(int max) {
TopicSubscription topicSubscription = getTopicSubscription();
if ( topicSubscription != null ) {
topicSubscription.setMaximumPendingMessages(max);
if (topicSubscription != null) {
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.memory.UsageManager;
import org.apache.activemq.store.MessageStore;
import org.apache.activemq.store.TopicMessageStore;
/**
*
* @version $Revision: 1.12 $
*/
public interface Destination extends Service {
void addSubscription(ConnectionContext context, Subscription sub) throws Exception;
void removeSubscription(ConnectionContext context, Subscription sub) throws Exception;
void send(ProducerBrokerExchange producerExchange, Message messageSend) throws Exception;
boolean lock(MessageReference node, LockOwner lockOwner);
void acknowledge(ConnectionContext context, Subscription sub, final MessageAck ack, final MessageReference node) throws IOException;
void gc();
ActiveMQDestination getActiveMQDestination();
UsageManager getUsageManager();
void dispose(ConnectionContext context) throws IOException;
DestinationStatistics getDestinationStatistics();
DeadLetterStrategy getDeadLetterStrategy();
public Message[] browse();
public String getName();
public MessageStore getMessageStore();
public MessageStore getMessageStore();
}

View File

@ -16,6 +16,10 @@
*/
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.ConnectionContext;
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.store.MessageStore;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
/**
*
* @version $Revision$
@ -42,7 +42,8 @@ public class DestinationFilter implements Destination {
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);
}
@ -105,17 +106,18 @@ public class DestinationFilter implements Destination {
/**
* 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();
Set destinations = broker.getDestinations(destination);
for (Iterator iter = destinations.iterator(); iter.hasNext();) {
Destination dest = (Destination) iter.next();
Destination dest = (Destination)iter.next();
dest.send(context, message);
}
}
public MessageStore getMessageStore() {
return next.getMessageStore();
}
public MessageStore getMessageStore() {
return next.getMessageStore();
}
}

View File

@ -24,103 +24,102 @@ import org.apache.activemq.command.Message;
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
QueueMessageReference {
final class NullMessageReference implements QueueMessageReference {
private ActiveMQMessage message = new ActiveMQMessage();
private volatile int references;
public void drop() {
throw new RuntimeException("not implemented");
}
private ActiveMQMessage message = new ActiveMQMessage();
private volatile int references;
public LockOwner getLockOwner() {
throw new RuntimeException("not implemented");
}
public void drop() {
throw new RuntimeException("not implemented");
}
public boolean isAcked() {
return false;
}
public LockOwner getLockOwner() {
throw new RuntimeException("not implemented");
}
public boolean isDropped() {
throw new RuntimeException("not implemented");
}
public boolean isAcked() {
return false;
}
public boolean lock(LockOwner subscription) {
return true;
}
public boolean isDropped() {
throw new RuntimeException("not implemented");
}
public void setAcked(boolean b) {
throw new RuntimeException("not implemented");
}
public boolean lock(LockOwner subscription) {
return true;
}
public void unlock() {
}
public void setAcked(boolean b) {
throw new RuntimeException("not implemented");
}
public int decrementReferenceCount() {
return --references;
}
public void unlock() {
}
public long getExpiration() {
throw new RuntimeException("not implemented");
}
public int decrementReferenceCount() {
return --references;
}
public String getGroupID() {
return null;
}
public long getExpiration() {
throw new RuntimeException("not implemented");
}
public int getGroupSequence() {
return 0;
}
public String getGroupID() {
return null;
}
public Message getMessage() throws IOException {
return message;
}
public int getGroupSequence() {
return 0;
}
public Message getMessageHardRef() {
throw new RuntimeException("not implemented");
}
public Message getMessage() throws IOException {
return message;
}
public MessageId getMessageId() {
return message.getMessageId();
}
public Message getMessageHardRef() {
throw new RuntimeException("not implemented");
}
public int getRedeliveryCounter() {
throw new RuntimeException("not implemented");
}
public MessageId getMessageId() {
return message.getMessageId();
}
public int getReferenceCount() {
return references;
}
public int getRedeliveryCounter() {
throw new RuntimeException("not implemented");
}
public Destination getRegionDestination() {
return null;
}
public int getReferenceCount() {
return references;
}
public int getSize() {
throw new RuntimeException("not implemented");
}
public Destination getRegionDestination() {
return null;
}
public ConsumerId getTargetConsumerId() {
throw new RuntimeException("not implemented");
}
public int getSize() {
throw new RuntimeException("not implemented");
}
public void incrementRedeliveryCounter() {
throw new RuntimeException("not implemented");
}
public ConsumerId getTargetConsumerId() {
throw new RuntimeException("not implemented");
}
public int incrementReferenceCount() {
return ++references;
}
public void incrementRedeliveryCounter() {
throw new RuntimeException("not implemented");
}
public boolean isExpired() {
throw new RuntimeException("not implemented");
}
public int incrementReferenceCount() {
return ++references;
}
public boolean isPersistent() {
throw new RuntimeException("not implemented");
}
public boolean isExpired() {
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;
public class QueueBrowserSubscription extends QueueSubscription {
boolean browseDone;
public QueueBrowserSubscription(Broker broker,ConnectionContext context, ConsumerInfo info) throws InvalidSelectorException {
super(broker,context, info);
public QueueBrowserSubscription(Broker broker, ConnectionContext context, ConsumerInfo info)
throws InvalidSelectorException {
super(broker, context, info);
}
protected boolean canDispatch(MessageReference node) {
return !((QueueMessageReference)node).isAcked();
}
public synchronized String toString() {
return
"QueueBrowserSubscription:" +
" consumer="+info.getConsumerId()+
", destinations="+destinations.size()+
", dispatched="+dispatched.size()+
", delivered="+this.prefetchExtension+
", pending="+getPendingQueueSize();
return "QueueBrowserSubscription:" + " consumer=" + info.getConsumerId() + ", destinations="
+ destinations.size() + ", dispatched=" + dispatched.size() + ", delivered="
+ this.prefetchExtension + ", pending=" + getPendingQueueSize();
}
public void browseDone() throws Exception {
browseDone = true;
add(QueueMessageReference.NULL_MESSAGE);
}
public boolean matches(MessageReference node, MessageEvaluationContext context) throws IOException {
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.
*/
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 QueueRegion(RegionBroker broker,DestinationStatistics destinationStatistics, UsageManager memoryManager, TaskRunnerFactory taskRunnerFactory,
DestinationFactory destinationFactory) {
super(broker,destinationStatistics, memoryManager, taskRunnerFactory, destinationFactory);
public QueueRegion(RegionBroker broker, DestinationStatistics destinationStatistics,
UsageManager memoryManager, TaskRunnerFactory taskRunnerFactory,
DestinationFactory destinationFactory) {
super(broker, destinationStatistics, memoryManager, taskRunnerFactory, destinationFactory);
}
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()) {
return new QueueBrowserSubscription(broker,context, info);
}
else {
return new QueueSubscription(broker,context, info);
return new QueueBrowserSubscription(broker, context, info);
} else {
return new QueueSubscription(broker, context, info);
}
}
protected Set getInactiveDestinations() {
Set inactiveDestinations = super.getInactiveDestinations();
for (Iterator iter = inactiveDestinations.iterator(); iter.hasNext();) {
ActiveMQDestination dest = (ActiveMQDestination) iter.next();
ActiveMQDestination dest = (ActiveMQDestination)iter.next();
if (!dest.isQueue())
iter.remove();
}

View File

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

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.kaha.Store;
/**
* Creates a FilePendingMessageCursor
* *
* @org.apache.xbean.XBean element="fileQueueCursor" description="Pending messages paged in from file"
* Creates a FilePendingMessageCursor *
*
* @org.apache.xbean.XBean element="fileQueueCursor" description="Pending
* messages paged in from file"
*
* @version $Revision$
*/
public class FilePendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy{
public class FilePendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy {
/**
* @param queue
* @param tmpStore
* @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){
return new FilePendingMessageCursor("PendingCursor:" + queue.getName(),tmpStore);
public PendingMessageCursor getQueuePendingMessageCursor(Queue queue, Store 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.kaha.Store;
/**
* Creates a PendIngMessageCursor for Durable subscribers
* *
* @org.apache.xbean.XBean element="fileCursor" description="Pending messages for durable subscribers
* held in temporary files"
* Creates a PendIngMessageCursor for Durable subscribers *
*
* @org.apache.xbean.XBean element="fileCursor" description="Pending messages
* for durable subscribers held in temporary files"
*
* @version $Revision$
*/
public class FilePendingSubscriberMessageStoragePolicy implements PendingSubscriberMessageStoragePolicy{
public class FilePendingSubscriberMessageStoragePolicy implements PendingSubscriberMessageStoragePolicy {
/**
* @param name
* @param tmpStorage
* @param maxBatchSize
* @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){
return new FilePendingMessageCursor("PendingCursor:" + name,tmpStorage);
public PendingMessageCursor getSubscriberPendingMessageCursor(String name, Store 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.kaha.Store;
/**
* Creates a StoreQueueCursor
* *
* @org.apache.xbean.XBean element="storeCursor" description="Pending messages paged in from the Store"
* Creates a StoreQueueCursor *
*
* @org.apache.xbean.XBean element="storeCursor" description="Pending messages
* paged in from the Store"
*
* @version $Revision$
*/
public class StorePendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy{
public class StorePendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy {
/**
* @param queue
* @param tmpStore
* @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){
return new StoreQueueCursor(queue,tmpStore);
public PendingMessageCursor getQueuePendingMessageCursor(Queue queue, Store 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;
/**
* Creates a VMPendingMessageCursor
* *
* @org.apache.xbean.XBean element="vmQueueCursor" description="Pending messages held in the JVM"
* Creates a VMPendingMessageCursor *
*
* @org.apache.xbean.XBean element="vmQueueCursor" description="Pending messages
* held in the JVM"
*
* @version $Revision$
*/
public class VMPendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy{
public class VMPendingQueueMessageStoragePolicy implements PendingQueueMessageStoragePolicy {
/**
* @param queue
* @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();
}
}

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.kaha.Store;
/**
* Creates a VMPendingMessageCursor
* *
* @org.apache.xbean.XBean element="vmCursor" description="Pending messages held in the JVM"
* Creates a VMPendingMessageCursor *
*
* @org.apache.xbean.XBean element="vmCursor" description="Pending messages held
* in the JVM"
*
* @version $Revision$
*/
public class VMPendingSubscriberMessageStoragePolicy implements PendingSubscriberMessageStoragePolicy{
public class VMPendingSubscriberMessageStoragePolicy implements PendingSubscriberMessageStoragePolicy {
/**
* @param name
* @param tmpStorage
* @param maxBatchSize
* @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();
}
}

View File

@ -23,7 +23,8 @@ import java.net.URI;
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
*
@ -31,30 +32,30 @@ import java.net.URISyntaxException;
*/
public class MulticastTraceBrokerPlugin extends UDPTraceBrokerPlugin {
private int timeToLive = 1;
public MulticastTraceBrokerPlugin() {
try {
destination = new URI("multicast://224.1.2.3:61616");
} catch (URISyntaxException wontHappen) {
}
}
protected DatagramSocket createSocket() throws IOException {
private int timeToLive = 1;
public MulticastTraceBrokerPlugin() {
try {
destination = new URI("multicast://224.1.2.3:61616");
} catch (URISyntaxException wontHappen) {
}
}
protected DatagramSocket createSocket() throws IOException {
MulticastSocket s = new MulticastSocket();
s.setSendBufferSize(maxTraceDatagramSize);
s.setBroadcast(broadcast);
s.setSendBufferSize(maxTraceDatagramSize);
s.setBroadcast(broadcast);
s.setLoopbackMode(true);
s.setTimeToLive(timeToLive);
return s;
}
}
public int getTimeToLive() {
return timeToLive;
}
public int getTimeToLive() {
return timeToLive;
}
public void setTimeToLive(int timeToLive) {
this.timeToLive = timeToLive;
}
public void setTimeToLive(int 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.command.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
* not be correct and you can only trust the time set on the broker machines.
* with a broker timestamp. Useful when the clocks on client machines are known
* 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
* sees on the messages after as send() will be different from the timestamp the consumer
* will observe when he receives the message. This plugin is not enabled in the default
* ActiveMQ configuration.
* Enabling this plugin will break JMS compliance since the timestamp that the
* producer sees on the messages after as send() will be different from the
* timestamp the consumer will observe when he receives the message. This plugin
* is not enabled in the default ActiveMQ configuration.
*
* @org.apache.xbean.XBean element="timeStampingBrokerPlugin"
* @org.apache.xbean.XBean element="timeStampingBrokerPlugin"
*
* @version $Revision$
*/
public class TimeStampingBrokerPlugin extends BrokerPluginSupport {
public void send(ProducerBrokerExchange producerExchange, Message message) throws Exception {
if (message.getTimestamp() > 0 && (message.getBrokerPath() == null || message.getBrokerPath().length == 0)) {
//timestamp not been disabled and has not passed through a network
public class TimeStampingBrokerPlugin extends BrokerPluginSupport {
public void send(ProducerBrokerExchange producerExchange, Message message) throws Exception {
if (message.getTimestamp() > 0
&& (message.getBrokerPath() == null || message.getBrokerPath().length == 0)) {
// timestamp not been disabled and has not passed through a network
message.setTimestamp(System.currentTimeMillis());
}
super.send(producerExchange, message);
}
super.send(producerExchange, message);
}
}

View File

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

View File

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

View File

@ -41,7 +41,8 @@ import java.util.StringTokenizer;
* @openwire:marshaller
* @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;
@ -196,7 +197,8 @@ abstract public class ActiveMQDestination extends JNDIBaseStorable implements Da
public void setPhysicalName(String physicalName) {
final int len = physicalName.length();
int p = -1;// options offset
// options offset
int p = -1;
boolean composite = false;
for (int i = 0; i < len; i++) {
char c = physicalName.charAt(i);
@ -219,7 +221,8 @@ abstract public class ActiveMQDestination extends JNDIBaseStorable implements Da
try {
options = URISupport.parseQuery(optstring);
} 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;

View File

@ -42,33 +42,51 @@ import org.apache.activemq.util.MarshallingSupport;
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>
* objects, and the values are primitive data types in the Java programming language. The names must have a value that
* is not null, and not an empty string. The entries can be accessed sequentially or randomly by name. The order of the
* entries is undefined. <CODE>MapMessage</CODE> inherits from the <CODE>Message</CODE> interface and adds a message
* body that contains a Map. <P> The primitive types can be read or written explicitly using methods for each type. They
* may also be read or written generically as objects. For instance, a call to <CODE>MapMessage.setInt("foo", 6)</CODE>
* is equivalent to <CODE> MapMessage.setObject("foo", new Integer(6))</CODE>. Both forms are provided, because the
* explicit form is convenient for static programming, and the object form is needed when types are not known at compile
* time. <P> When a client receives a <CODE>MapMessage</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. <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[] |----------------------------------------------------------------------
* A <CODE>MapMessage</CODE> object is used to send a set of name-value pairs.
* The names are <CODE>String</CODE> objects, and the values are primitive
* data types in the Java programming language. The names must have a value that
* is not null, and not an empty string. The entries can be accessed
* sequentially or randomly by name. The order of the entries is undefined.
* <CODE>MapMessage</CODE> inherits from the <CODE>Message</CODE> interface
* and adds a message body that contains a Map.
* <P>
* The primitive types can be read or written explicitly using methods for each
* type. They may also be read or written generically as objects. For instance,
* a call to <CODE>MapMessage.setInt("foo", 6)</CODE> is equivalent to
* <CODE> MapMessage.setObject("foo", new Integer(6))</CODE>. Both forms are
* provided, because the explicit form is convenient for static programming, and
* the object form is needed when types are not known at compile time.
* <P>
* When a client receives a <CODE>MapMessage</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.
* <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
* |String | X X X X X X X X |byte[] | X |----------------------------------------------------------------------
* <p/>
* &lt;p/&gt;
* </PRE>
*
* <p/>
* <P> Attempting to read a null value as a primitive type must be treated as calling the primitive's corresponding
* <code>valueOf(String)</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>.
*
* <P>
* Attempting to read a null value as a primitive type must be treated as
* calling the primitive's corresponding <code>valueOf(String)</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"
* @see javax.jms.Session#createMapMessage()
* @see javax.jms.BytesMessage
@ -99,14 +117,14 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
super.beforeMarshall(wireFormat);
storeContent();
}
private void storeContent() {
try {
if( getContent()==null && !map.isEmpty()) {
if (getContent() == null && !map.isEmpty()) {
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
OutputStream os = bytesOut;
ActiveMQConnection connection = getConnection();
if( connection!= null && connection.isUseCompression() ) {
if (connection != null && connection.isUseCompression()) {
compressed = true;
os = new DeflaterOutputStream(os);
}
@ -119,19 +137,20 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
throw new RuntimeException(e);
}
}
/**
* Builds the message body from data
* @throws JMSException
*
*
* @throws JMSException
*
* @throws IOException
*/
private void loadContent() throws JMSException {
try {
if( getContent()!=null && map.isEmpty() ) {
if (getContent() != null && map.isEmpty()) {
ByteSequence content = getContent();
InputStream is = new ByteArrayInputStream(content);
if( isCompressed() ) {
if (isCompressed()) {
is = new InflaterInputStream(is);
}
DataInputStream dataIn = new DataInputStream(is);
@ -146,16 +165,18 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE;
}
public String getJMSXMimeType() {
return "jms/map-message";
}
/**
* Clears out the message body. Clearing a message's body does not clear its header values or property entries. <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.
* Clears out the message body. Clearing a message's body does not clear its
* header values or property entries.
* <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 {
super.clearBody();
@ -164,10 +185,11 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
/**
* Returns the <CODE>boolean</CODE> value with the specified name.
*
*
* @param name the name of the <CODE>boolean</CODE>
* @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.
*/
public boolean getBoolean(String name) throws JMSException {
@ -177,7 +199,7 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
return false;
}
if (value instanceof Boolean) {
return ((Boolean) value).booleanValue();
return ((Boolean)value).booleanValue();
}
if (value instanceof String) {
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.
*
*
* @param name the name of the <CODE>byte</CODE>
* @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.
*/
public byte getByte(String name) throws JMSException {
@ -201,7 +224,7 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
return 0;
}
if (value instanceof Byte) {
return ((Byte) value).byteValue();
return ((Byte)value).byteValue();
}
if (value instanceof String) {
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.
*
*
* @param name the name of the <CODE>short</CODE>
* @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.
*/
public short getShort(String name) throws JMSException {
@ -225,10 +249,10 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
return 0;
}
if (value instanceof Short) {
return ((Short) value).shortValue();
return ((Short)value).shortValue();
}
if (value instanceof Byte) {
return ((Byte) value).shortValue();
return ((Byte)value).shortValue();
}
if (value instanceof String) {
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.
*
*
* @param name the name of the Unicode character
* @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.
*/
public char getChar(String name) throws JMSException {
@ -252,7 +277,7 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
throw new NullPointerException();
}
if (value instanceof Character) {
return ((Character) value).charValue();
return ((Character)value).charValue();
} else {
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.
*
*
* @param name the name of the <CODE>int</CODE>
* @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.
*/
public int getInt(String name) throws JMSException {
@ -273,13 +299,13 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
return 0;
}
if (value instanceof Integer) {
return ((Integer) value).intValue();
return ((Integer)value).intValue();
}
if (value instanceof Short) {
return ((Short) value).intValue();
return ((Short)value).intValue();
}
if (value instanceof Byte) {
return ((Byte) value).intValue();
return ((Byte)value).intValue();
}
if (value instanceof String) {
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.
*
*
* @param name the name of the <CODE>long</CODE>
* @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.
*/
public long getLong(String name) throws JMSException {
@ -303,16 +330,16 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
return 0;
}
if (value instanceof Long) {
return ((Long) value).longValue();
return ((Long)value).longValue();
}
if (value instanceof Integer) {
return ((Integer) value).longValue();
return ((Integer)value).longValue();
}
if (value instanceof Short) {
return ((Short) value).longValue();
return ((Short)value).longValue();
}
if (value instanceof Byte) {
return ((Byte) value).longValue();
return ((Byte)value).longValue();
}
if (value instanceof String) {
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.
*
*
* @param name the name of the <CODE>float</CODE>
* @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.
*/
public float getFloat(String name) throws JMSException {
@ -336,7 +364,7 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
return 0;
}
if (value instanceof Float) {
return ((Float) value).floatValue();
return ((Float)value).floatValue();
}
if (value instanceof String) {
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.
*
*
* @param name the name of the <CODE>double</CODE>
* @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.
*/
public double getDouble(String name) throws JMSException {
@ -360,10 +389,10 @@ public class ActiveMQMapMessage extends ActiveMQMessage implements MapMessage {
return 0;
}
if (value instanceof Double) {
return ((Double) value).doubleValue();
return ((Double)value).doubleValue();
}
if (value instanceof Float) {
return ((Float) value).floatValue();
return ((Float)value).floatValue();
}
if (value instanceof String) {
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.
*
*
* @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
* returned
* @throws JMSException if the JMS provider fails to read the message due to some internal error.
* @return the <CODE>String</CODE> value with the specified name; if 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.
* @throws MessageFormatException if this type conversion is invalid.
*/
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.
*
*
* @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
* returned.
* @throws JMSException if the JMS provider fails to read the message due to some internal error.
* @return a copy of the byte array value with the specified name; if 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.
* @throws MessageFormatException if this type conversion is invalid.
*/
public byte[] getBytes(String name) throws JMSException {
initializeReading();
Object value = map.get(name);
if ( value instanceof byte[] ) {
return (byte[]) value;
Object value = map.get(name);
if (value instanceof byte[]) {
return (byte[])value;
} else {
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
* format, an object in 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>.
*
* Returns the value of the object with the specified name.
* <P>
* This method can be used to return, in objectified format, an object in
* 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
* @return a copy of the Java object value with the specified name, in objectified format (for example, if the
* object was set as an <CODE>int</CODE>, an <CODE>Integer</CODE> is returned); if 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.
* @return a copy of the Java object value with the specified name, in
* objectified format (for example, if the object was set as an
* <CODE>int</CODE>, an <CODE>Integer</CODE> is returned); if
* 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 {
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>
* @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.
*
* @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
* @throws JMSException if the JMS provider fails to write the message due to some internal error.
* @throws IllegalArgumentException 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 IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode.
*/
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.
*
* @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
* @throws JMSException if the JMS provider fails to write the message due to some internal error.
* @throws IllegalArgumentException 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 IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode.
*/
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.
*
* @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
* @throws JMSException if the JMS provider fails to write the message due to some internal error.
* @throws IllegalArgumentException 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 IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode.
*/
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.
*
* @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
* @throws JMSException if the JMS provider fails to write the message due to some internal error.
* @throws IllegalArgumentException 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 IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode.
*/
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.
*
* @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
* @throws JMSException if the JMS provider fails to write the message due to some internal error.
* @throws IllegalArgumentException 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 IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode.
*/
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.
*
* @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
* @throws JMSException if the JMS provider fails to write the message due to some internal error.
* @throws IllegalArgumentException 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 IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode.
*/
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.
*
* @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
* @throws JMSException if the JMS provider fails to write the message due to some internal error.
* @throws IllegalArgumentException 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 IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode.
*/
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.
*
* @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
* @throws JMSException if the JMS provider fails to write the message due to some internal error.
* @throws IllegalArgumentException 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 IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode.
*/
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.
*
* @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
* @throws JMSException if the JMS provider fails to write the message due to some internal error.
* @throws IllegalArgumentException 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 IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode.
*/
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.
*
* @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>
* will not be altered by future modifications
* @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.
*
* @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> will not be
* altered by future modifications
* @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.
*/
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.
*
* @param name the name of the byte array
* @param value the byte array value to set in 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 offset the initial offset within the byte array
* @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 IllegalArgumentException 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 IllegalArgumentException if the name is null or if the name is an
* empty string.
* @throws MessageNotWriteableException if the message is in read-only mode.
*/
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
* primitive object types (<code>Integer</code>,<code>Double</code>, <code>Long</code> &nbsp;...),
* <code>String</code> objects, and byte arrays.
*
* @param name the name of the Java object
* Sets an object value with the specified name into the Map.
* <P>
* 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
* arrays.
*
* @param name the name of the Java object
* @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 IllegalArgumentException if the name is null or if the name is an empty string.
* @throws MessageFormatException if the object is invalid.
* @throws JMSException if the JMS provider fails to write the message due
* to some internal error.
* @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.
*/
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
* @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 {
initializeReading();
return map.containsKey(name);
}
private void initializeReading() throws JMSException {
loadContent();
}
private void initializeWriting() throws MessageNotWriteableException {
checkReadOnlyBody();
setContent(null);
}
public String toString() {
return super.toString() + " ActiveMQMapMessage{ " +
"theTable = " + map +
" }";
return super.toString() + " ActiveMQMapMessage{ " + "theTable = " + map + " }";
}
public Map getContentMap() throws JMSException {
initializeReading();
return map;

View File

@ -17,9 +17,6 @@
package org.apache.activemq.command;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.util.ByteArrayInputStream;
import org.apache.activemq.util.ByteArrayOutputStream;
@ -40,17 +37,21 @@ import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
/**
* An <CODE>ObjectMessage</CODE> object is used to send a message that contains a serializable object in the Java
* programming language ("Java object"). It inherits from the <CODE>Message</CODE> interface and adds a body containing
* a single reference to an object. Only <CODE>Serializable</CODE> Java objects can be used.
* <p/>
* <P>If a collection of Java objects must be sent, one of the <CODE>Collection</CODE> classes provided since JDK 1.2
* can be used.
* <p/>
* <P>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.
*
* An <CODE>ObjectMessage</CODE> object is used to send a message that
* contains a serializable object in the Java programming language ("Java
* object"). It inherits from the <CODE>Message</CODE> interface and adds a
* body containing a single reference to an object. Only
* <CODE>Serializable</CODE> Java objects can be used. <p/>
* <P>
* If a collection of Java objects must be sent, one of the
* <CODE>Collection</CODE> classes provided since JDK 1.2 can be used. <p/>
* <P>
* 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"
* @see javax.jms.Session#createObjectMessage()
* @see javax.jms.Session#createObjectMessage(Serializable)
@ -61,7 +62,9 @@ import java.util.zip.InflaterInputStream;
* @see javax.jms.TextMessage
*/
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;
protected transient Serializable object;
@ -75,9 +78,9 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess
private void copy(ActiveMQObjectMessage copy) {
storeContent();
super.copy(copy);
copy.object=null;
copy.object = null;
}
public void storeContent() {
ByteSequence bodyAsBytes = getContent();
if (bodyAsBytes == null && object != null) {
@ -85,7 +88,7 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
OutputStream os = bytesOut;
ActiveMQConnection connection = getConnection();
if (connection!=null && connection.isUseCompression()) {
if (connection != null && connection.isUseCompression()) {
compressed = true;
os = new DeflaterOutputStream(os);
}
@ -110,14 +113,16 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess
return "jms/object-message";
}
/**
* Clears out the message body. Clearing a message's body does not clear its 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
* body in a newly created message.
*
* @throws JMSException if the JMS provider fails to clear the message body due to some internal error.
* Clears out the message body. Clearing a message's body does not clear its
* 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 body in a newly created
* message.
*
* @throws JMSException if the JMS provider fails to clear the message body
* due to some internal error.
*/
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
* <CODE>ObjectMessage</CODE> contains a 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.
*
* Sets the serializable object containing this message's data. It is
* important to note that an <CODE>ObjectMessage</CODE> contains a
* 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
* @throws JMSException if the JMS provider fails to set the object due to some internal error.
* @throws javax.jms.MessageFormatException
* if object serialization fails.
* @throws javax.jms.MessageNotWriteableException
* if the message is in read-only mode.
* @throws JMSException if the JMS provider fails to set the object due to
* some internal error.
* @throws javax.jms.MessageFormatException if object serialization fails.
* @throws javax.jms.MessageNotWriteableException if the message is in
* read-only mode.
*/
public void setObject(Serializable newObject) throws JMSException {
@ -143,30 +150,30 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess
this.object = newObject;
setContent(null);
ActiveMQConnection connection = getConnection();
if( connection==null || !connection.isObjectMessageSerializationDefered() ) {
if (connection == null || !connection.isObjectMessageSerializationDefered()) {
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
* @throws JMSException
*/
public Serializable getObject() throws JMSException {
if (object == null && getContent()!=null ) {
if (object == null && getContent() != null) {
try {
ByteSequence content = getContent();
InputStream is = new ByteArrayInputStream(content);
if( isCompressed() ) {
if (isCompressed()) {
is = new InflaterInputStream(is);
}
DataInputStream dataIn = new DataInputStream(is);
ClassLoadingAwareObjectInputStream objIn = new ClassLoadingAwareObjectInputStream(dataIn);
try {
object = (Serializable) objIn.readObject();
object = (Serializable)objIn.readObject();
} catch (ClassNotFoundException ce) {
throw new IOException(ce.getMessage());
}
@ -180,8 +187,9 @@ public class ActiveMQObjectMessage extends ActiveMQMessage implements ObjectMess
public void 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;
}

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"
* @version $Revision: 1.5 $
*/
public class ActiveMQQueue extends ActiveMQDestination implements Queue {
private static final long serialVersionUID = -3885260014960795889L;
public static final byte DATA_STRUCTURE_TYPE=CommandTypes.ACTIVEMQ_QUEUE;
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.ACTIVEMQ_QUEUE;
public ActiveMQQueue() {
}

View File

@ -1130,8 +1130,9 @@ public class ActiveMQStreamMessage extends ActiveMQMessage implements StreamMess
checkWriteOnlyBody();
if (this.dataIn == null) {
ByteSequence data = getContent();
if (data == null)
if (data == null) {
data = new ByteSequence(new byte[] {}, 0, 0);
}
InputStream is = new ByteArrayInputStream(data);
if (isCompressed()) {
is = new InflaterInputStream(is);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -18,7 +18,6 @@ package org.apache.activemq.command;
import org.apache.activemq.state.CommandVisitor;
/**
*
* @openwire:marshaller code="21"
@ -26,7 +25,7 @@ import org.apache.activemq.state.CommandVisitor;
*/
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 ActiveMQDestination destination;
@ -36,11 +35,11 @@ public class MessageDispatch extends BaseCommand {
transient protected long deliverySequenceId;
transient protected Object consumer;
transient protected Runnable transmitCallback;
public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE;
}
public boolean isMessageDispatch() {
return true;
}
@ -51,6 +50,7 @@ public class MessageDispatch extends BaseCommand {
public ConsumerId getConsumerId() {
return consumerId;
}
public void setConsumerId(ConsumerId consumerId) {
this.consumerId = consumerId;
}
@ -61,16 +61,18 @@ public class MessageDispatch extends BaseCommand {
public ActiveMQDestination getDestination() {
return destination;
}
public void setDestination(ActiveMQDestination destination) {
this.destination = destination;
}
/**
* @openwire:property version=1
*/
public Message getMessage() {
return message;
}
public void setMessage(Message message) {
this.message = message;
}
@ -78,16 +80,18 @@ public class MessageDispatch extends BaseCommand {
public long getDeliverySequenceId() {
return deliverySequenceId;
}
public void setDeliverySequenceId(long deliverySequenceId) {
this.deliverySequenceId = deliverySequenceId;
}
/**
* @openwire:property version=1
*/
public int getRedeliveryCounter() {
return redeliveryCounter;
}
public void setRedeliveryCounter(int deliveryCounter) {
this.redeliveryCounter = deliveryCounter;
}
@ -104,12 +108,12 @@ public class MessageDispatch extends BaseCommand {
return visitor.processMessageDispatch(this);
}
public Runnable getTransmitCallback() {
return transmitCallback;
}
public Runnable getTransmitCallback() {
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 static final byte DATA_STRUCTURE_TYPE=CommandTypes.PRODUCER_INFO;
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.PRODUCER_INFO;
protected ProducerId producerId;
protected ActiveMQDestination destination;
protected BrokerId[] brokerPath;
protected boolean dispatchAsync;
protected int windowSize;
public ProducerInfo() {
}
@ -59,77 +59,80 @@ public class ProducerInfo extends BaseCommand {
public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE;
}
/**
* @openwire:property version=1 cache=true
*/
public ProducerId getProducerId() {
return producerId;
}
public void setProducerId(ProducerId producerId) {
this.producerId = producerId;
}
/**
* @openwire:property version=1 cache=true
*/
public ActiveMQDestination getDestination() {
return destination;
}
}
public void setDestination(ActiveMQDestination destination) {
this.destination = destination;
}
public RemoveInfo createRemoveCommand() {
RemoveInfo command = new RemoveInfo(getProducerId());
command.setResponseRequired(isResponseRequired());
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
*/
public BrokerId[] getBrokerPath() {
return brokerPath;
}
public void setBrokerPath(BrokerId[] brokerPath) {
this.brokerPath = brokerPath;
}
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
* dispatch could potentally block the producer thread, this could be an important
* setting for the producer.
* If the broker should dispatch messages from this producer async. Since
* sync dispatch could potentally block the producer thread, this could be
* an important setting for the producer.
*
* @openwire:property version=2
*/
public boolean isDispatchAsync() {
return dispatchAsync;
}
public boolean isDispatchAsync() {
return dispatchAsync;
}
public void setDispatchAsync(boolean dispatchAsync) {
this.dispatchAsync = dispatchAsync;
}
public void setDispatchAsync(boolean dispatchAsync) {
this.dispatchAsync = dispatchAsync;
}
/**
* Used to configure the producer window size. A producer will
* send up to the configured window size worth of payload data to
* the broker before waiting for an Ack that allows him to send more.
* Used to configure the producer window size. A producer will send up to
* the configured window size worth of payload data to the broker before
* waiting for an Ack that allows him to send more.
*
* @openwire:property version=3
*/
public int getWindowSize() {
return windowSize;
}
public int getWindowSize() {
return windowSize;
}
public void setWindowSize(int windowSize) {
this.windowSize = windowSize;
}
public void setWindowSize(int windowSize) {
this.windowSize = windowSize;
}
}

View File

@ -22,26 +22,27 @@ import org.apache.activemq.state.CommandVisitor;
/**
* Removes a consumer, producer, session or connection.
*
*
* @openwire:marshaller code="12"
* @version $Revision$
*/
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;
public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE;
}
}
public RemoveInfo() {
public RemoveInfo() {
}
public RemoveInfo(DataStructure objectId) {
this.objectId=objectId;
this.objectId = objectId;
}
/**
* @openwire:property version=1 cache=true
*/
@ -56,32 +57,32 @@ public class RemoveInfo extends BaseCommand {
public Response visit(CommandVisitor visitor) throws Exception {
switch (objectId.getDataStructureType()) {
case ConnectionId.DATA_STRUCTURE_TYPE:
return visitor.processRemoveConnection((ConnectionId) objectId);
return visitor.processRemoveConnection((ConnectionId)objectId);
case SessionId.DATA_STRUCTURE_TYPE:
return visitor.processRemoveSession((SessionId) objectId);
return visitor.processRemoveSession((SessionId)objectId);
case ConsumerId.DATA_STRUCTURE_TYPE:
return visitor.processRemoveConsumer((ConsumerId) objectId);
return visitor.processRemoveConsumer((ConsumerId)objectId);
case ProducerId.DATA_STRUCTURE_TYPE:
return visitor.processRemoveProducer((ProducerId) objectId);
return visitor.processRemoveProducer((ProducerId)objectId);
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
*/
public boolean isConnectionRemove() {
return objectId.getDataStructureType() == ConnectionId.DATA_STRUCTURE_TYPE;
}
/**
* Returns true if this event is for a removed session
*/
public boolean isSessionRemove() {
return objectId.getDataStructureType() == SessionId.DATA_STRUCTURE_TYPE;
}
/**
* 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"
* @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 long value;
protected transient int hashCode;
protected transient String key;
protected transient ConnectionId parentId;
public SessionId() {
public SessionId() {
}
public SessionId(ConnectionId connectionId, long sessionId) {
this.connectionId = connectionId.getValue();
this.value=sessionId;
this.value = sessionId;
}
public SessionId(SessionId id) {
this.connectionId = id.getConnectionId();
this.value=id.getValue();
this.value = id.getValue();
}
public SessionId(ProducerId id) {
this.connectionId = id.getConnectionId();
this.value=id.getSessionId();
this.value = id.getSessionId();
}
public SessionId(ConsumerId id) {
this.connectionId = id.getConnectionId();
this.value=id.getSessionId();
this.value = id.getSessionId();
}
public ConnectionId getParentId() {
if( parentId == null ) {
if (parentId == null) {
parentId = new ConnectionId(this);
}
return parentId;
}
public int hashCode() {
if( hashCode == 0 ) {
if (hashCode == 0) {
hashCode = connectionId.hashCode() ^ (int)value;
}
return hashCode;
}
public boolean equals(Object o) {
if( this == o )
if (this == o)
return true;
if( o == null || o.getClass()!=SessionId.class )
if (o == null || o.getClass() != SessionId.class)
return false;
SessionId id = (SessionId) o;
return value==id.value
&& connectionId.equals(id.connectionId);
SessionId id = (SessionId)o;
return value == id.value && connectionId.equals(id.connectionId);
}
public byte getDataStructureType() {
@ -88,7 +87,8 @@ public class SessionId implements DataStructure {
*/
public String getConnectionId() {
return connectionId;
}
}
public void setConnectionId(String connectionId) {
this.connectionId = connectionId;
}
@ -99,13 +99,14 @@ public class SessionId implements DataStructure {
public long getValue() {
return value;
}
public void setValue(long sessionId) {
this.value = sessionId;
}
public String toString() {
if( key==null ) {
key = connectionId+":"+value;
if (key == null) {
key = connectionId + ":" + value;
}
return key;
}

View File

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

View File

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

View File

@ -27,29 +27,28 @@ import org.apache.activemq.state.CommandVisitor;
*/
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 PREPARE=1;
public static final byte COMMIT_ONE_PHASE=2;
public static final byte COMMIT_TWO_PHASE=3;
public static final byte ROLLBACK=4;
public static final byte RECOVER=5;
public static final byte FORGET=6;
public static final byte END=7;
public static final byte PREPARE = 1;
public static final byte COMMIT_ONE_PHASE = 2;
public static final byte COMMIT_TWO_PHASE = 3;
public static final byte ROLLBACK = 4;
public static final byte RECOVER = 5;
public static final byte FORGET = 6;
public static final byte END = 7;
protected byte type;
protected ConnectionId connectionId;
protected TransactionId transactionId;
public TransactionInfo() {
public TransactionInfo() {
}
public TransactionInfo(ConnectionId connectionId, TransactionId transactionId, byte type) {
this.connectionId=connectionId;
this.transactionId=transactionId;
this.type=type;
this.connectionId = connectionId;
this.transactionId = transactionId;
this.type = type;
}
public byte getDataStructureType() {
@ -58,20 +57,22 @@ public class TransactionInfo extends BaseCommand {
/**
* @openwire:property version=1 cache=true
*/
*/
public ConnectionId getConnectionId() {
return connectionId;
}
public void setConnectionId(ConnectionId connectionId) {
this.connectionId = connectionId;
}
/**
* @openwire:property version=1 cache=true
*/
*/
public TransactionId getTransactionId() {
return transactionId;
}
}
public void setTransactionId(TransactionId transactionId) {
this.transactionId = transactionId;
}
@ -81,13 +82,14 @@ public class TransactionInfo extends BaseCommand {
*/
public byte getType() {
return type;
}
}
public void setType(byte type) {
this.type = type;
}
public Response visit(CommandVisitor visitor) throws Exception {
switch( type ) {
switch (type) {
case TransactionInfo.BEGIN:
return visitor.processBeginTransaction(this);
case TransactionInfo.END:
@ -105,7 +107,7 @@ public class TransactionInfo extends BaseCommand {
case TransactionInfo.FORGET:
return visitor.processForgetTransaction(this);
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 {
private static final int MAX_PROPERTY_SIZE = 1024*4;
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' };
private static final int MAX_PROPERTY_SIZE = 1024 * 4;
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'};
protected byte magic[] = MAGIC;
protected int version;
protected ByteSequence marshalledProperties;
protected transient Map properties;
private transient Endpoint from;
private transient Endpoint to;
@ -68,6 +68,7 @@ public class WireFormatInfo implements Command, MarshallAware {
public byte[] getMagic() {
return magic;
}
public void setMagic(byte[] magic) {
this.magic = magic;
}
@ -78,16 +79,18 @@ public class WireFormatInfo implements Command, MarshallAware {
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
/**
* @openwire:property version=1
*/
public ByteSequence getMarshalledProperties() {
return marshalledProperties;
}
public void setMarshalledProperties(ByteSequence 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() {
return to;
@ -113,34 +117,34 @@ public class WireFormatInfo implements Command, MarshallAware {
public void setTo(Endpoint to) {
this.to = to;
}
//////////////////////
// ////////////////////
//
// Implementation Methods.
//
//////////////////////
// ////////////////////
public Object getProperty(String name) throws IOException {
if( properties == null ) {
if( marshalledProperties ==null )
if (properties == null) {
if (marshalledProperties == null)
return null;
properties = unmarsallProperties(marshalledProperties);
}
return properties.get(name);
}
public Map getProperties() throws IOException {
if( properties == null ) {
if( marshalledProperties==null )
if (properties == null) {
if (marshalledProperties == null)
return Collections.EMPTY_MAP;
properties = unmarsallProperties(marshalledProperties);
}
return Collections.unmodifiableMap(properties);
}
public void clearProperties() {
marshalledProperties = null;
properties=null;
properties = null;
}
public void setProperty(String name, Object value) throws IOException {
@ -149,8 +153,8 @@ public class WireFormatInfo implements Command, MarshallAware {
}
protected void lazyCreateProperties() throws IOException {
if( properties == null ) {
if( marshalledProperties == null ) {
if (properties == null) {
if (marshalledProperties == null) {
properties = new HashMap();
} else {
properties = unmarsallProperties(marshalledProperties);
@ -158,14 +162,16 @@ public class WireFormatInfo implements Command, MarshallAware {
}
}
}
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 {
// Need to marshal the properties.
if( marshalledProperties==null && properties!=null ) {
if (marshalledProperties == null && properties != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream os = new DataOutputStream(baos);
MarshallingSupport.marshalPrimitiveMap(properties, os);
@ -183,7 +189,6 @@ public class WireFormatInfo implements Command, MarshallAware {
public void afterUnmarshall(WireFormat wireFormat) throws IOException {
}
public boolean isValid() {
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 {
return Boolean.TRUE == getProperty("CacheEnabled");
}
public void setCacheEnabled(boolean cacheEnabled) throws IOException {
setProperty("CacheEnabled", cacheEnabled ? Boolean.TRUE : Boolean.FALSE);
}
/**
* @throws IOException
* @throws IOException
*/
public boolean isStackTraceEnabled() throws IOException {
return Boolean.TRUE == getProperty("StackTraceEnabled");
}
public void setStackTraceEnabled(boolean stackTraceEnabled) throws IOException {
setProperty("StackTraceEnabled", stackTraceEnabled ? Boolean.TRUE : Boolean.FALSE);
}
/**
* @throws IOException
* @throws IOException
*/
public boolean isTcpNoDelayEnabled() throws IOException {
return Boolean.TRUE == getProperty("TcpNoDelayEnabled");
}
public void setTcpNoDelayEnabled(boolean tcpNoDelayEnabled) throws IOException {
setProperty("TcpNoDelayEnabled", tcpNoDelayEnabled ? Boolean.TRUE : Boolean.FALSE);
}
/**
* @throws IOException
* @throws IOException
*/
public boolean isSizePrefixDisabled() throws IOException {
return Boolean.TRUE == getProperty("SizePrefixDisabled");
}
public void setSizePrefixDisabled(boolean prefixPacketSize) throws IOException {
setProperty("SizePrefixDisabled", prefixPacketSize ? Boolean.TRUE : Boolean.FALSE);
}
/**
* @throws IOException
* @throws IOException
*/
public boolean isTightEncodingEnabled() throws IOException {
return Boolean.TRUE == getProperty("TightEncodingEnabled");
}
public void setTightEncodingEnabled(boolean tightEncodingEnabled) throws IOException {
setProperty("TightEncodingEnabled", tightEncodingEnabled ? Boolean.TRUE : Boolean.FALSE);
}
/**
* @throws IOException
* @throws IOException
*/
public long getMaxInactivityDuration() throws IOException {
Long l = (Long) getProperty("MaxInactivityDuration");
Long l = (Long)getProperty("MaxInactivityDuration");
return l == null ? 0 : l.longValue();
}
public void seMaxInactivityDuration(long maxInactivityDuration) throws IOException {
setProperty("MaxInactivityDuration", new Long(maxInactivityDuration));
}
/**
* @throws IOException
* @throws IOException
*/
public int getCacheSize() throws IOException {
Integer i = (Integer) getProperty("CacheSize");
Integer i = (Integer)getProperty("CacheSize");
return i == null ? 0 : i.intValue();
}
public void setCacheSize(int cacheSize) throws IOException {
setProperty("CacheSize", new Integer(cacheSize));
}
public Response visit(CommandVisitor visitor) throws Exception {
return visitor.processWireFormat(this);
}
public String toString() {
Map p=null;
try {
p = getProperties();
} catch (IOException e) {
}
return "WireFormatInfo { version="+version+", properties="+p+", magic="+toString(magic)+"}";
Map p = null;
try {
p = getProperties();
} catch (IOException e) {
}
return "WireFormatInfo { version=" + version + ", properties=" + p + ", magic=" + toString(magic)
+ "}";
}
private String toString(byte []data) {
private String toString(byte[] data) {
StringBuffer sb = new StringBuffer();
sb.append('[');
for (int i = 0; i < data.length; i++) {
if( i != 0 ) {
if (i != 0) {
sb.append(',');
}
sb.append((char)data[i]);
sb.append((char)data[i]);
}
sb.append(']');
return sb.toString();
}
///////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////
//
// This are not implemented.
//
///////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////
public void setCommandId(int value) {
}
public int getCommandId() {
return 0;
}
public boolean isResponseRequired() {
return false;
}
public boolean isResponse() {
return false;
}
public boolean isBrokerInfo() {
return false;
}
public boolean isMessageDispatch() {
return false;
}
public boolean isMessage() {
return false;
}
public boolean isMessageAck() {
return false;
}
public boolean isMessageDispatchNotification(){
public boolean isMessageDispatchNotification() {
return false;
}
public boolean isShutdownInfo(){
public boolean isShutdownInfo() {
return false;
}
public void setCachedMarshalledForm(WireFormat wireFormat, ByteSequence data) {
}
public ByteSequence getCachedMarshalledForm(WireFormat wireFormat) {
return null;
}

View File

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

View File

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

View File

@ -30,7 +30,8 @@ import javax.jms.JMSException;
public abstract class ComparisonExpression extends BinaryExpression implements BooleanExpression {
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) {
@ -86,18 +87,14 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
char t = like.charAt(i);
regexp.append("\\x");
regexp.append(Integer.toHexString(0xFFFF & t));
}
else if (c == '%') {
regexp.append(".*?"); // Do a non-greedy match
}
else if (c == '_') {
regexp.append("."); // match one
}
else if (REGEXP_CONTROL_CHARS.contains(new Character(c))) {
} else if (c == '%') {
regexp.append(".*?"); // Do a non-greedy match
} else if (c == '_') {
regexp.append("."); // match one
} else if (REGEXP_CONTROL_CHARS.contains(new Character(c))) {
regexp.append("\\x");
regexp.append(Integer.toHexString(0xFFFF & c));
}
else {
} else {
regexp.append(c);
}
}
@ -125,22 +122,25 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
}
if (!(rv instanceof String)) {
return Boolean.FALSE;
//throw new RuntimeException("LIKE can only operate on String identifiers. LIKE attemped on: '" + rv.getClass());
return Boolean.FALSE;
// 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 {
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) {
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;
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) {
return UnaryExpression.createNOT(createLike(left, right, escape));
}
}
public static BooleanExpression createInFilter(Expression left, List elements) {
if( !(left instanceof PropertyExpression) )
throw new RuntimeException("Expected a property for In expression, got: "+left);
return UnaryExpression.createInExpression((PropertyExpression)left, elements, false);
if (!(left instanceof PropertyExpression))
throw new RuntimeException("Expected a property for In expression, got: " + left);
return UnaryExpression.createInExpression((PropertyExpression)left, elements, false);
}
public static BooleanExpression createNotInFilter(Expression left, List elements) {
if( !(left instanceof PropertyExpression) )
throw new RuntimeException("Expected a property for In expression, got: "+left);
return UnaryExpression.createInExpression((PropertyExpression)left, elements, true);
if (!(left instanceof PropertyExpression))
throw new RuntimeException("Expected a property for In expression, got: " + left);
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) {
checkEqualOperand(left);
checkEqualOperand(right);
checkEqualOperandCompatability(left, right);
return doCreateEqual(left, right);
checkEqualOperand(left);
checkEqualOperand(right);
checkEqualOperandCompatability(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) {
public Object evaluate(MessageEvaluationContext message) throws JMSException {
Object lv = left.evaluate(message);
Object rv = right.evaluate(message);
// Iff one of the values is null
if (lv == null ^ rv == null) {
return Boolean.FALSE;
}
if (lv == rv || lv.equals(rv)) {
return Boolean.TRUE;
}
if( lv instanceof Comparable && rv instanceof Comparable ) {
}
if (lv instanceof Comparable && rv instanceof Comparable) {
return compare((Comparable)lv, (Comparable)rv);
}
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) {
checkLessThanOperand(left);
checkLessThanOperand(right);
checkLessThanOperand(left);
checkLessThanOperand(right);
return new ComparisonExpression(left, right) {
protected boolean asBoolean(int answer) {
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) {
checkLessThanOperand(left);
checkLessThanOperand(right);
checkLessThanOperand(left);
checkLessThanOperand(right);
return new ComparisonExpression(left, right) {
protected boolean asBoolean(int answer) {
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) {
checkLessThanOperand(left);
checkLessThanOperand(right);
checkLessThanOperand(left);
checkLessThanOperand(right);
return new ComparisonExpression(left, right) {
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) {
checkLessThanOperand(left);
checkLessThanOperand(right);
public static BooleanExpression createLessThanEqual(final Expression left, final Expression right) {
checkLessThanOperand(left);
checkLessThanOperand(right);
return new ComparisonExpression(left, right) {
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
*/
public static void checkLessThanOperand(Expression expr ) {
if( expr instanceof ConstantExpression ) {
Object value = ((ConstantExpression)expr).getValue();
if( value instanceof Number )
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.");
}
}
* @param expr
*/
public static void checkLessThanOperand(Expression expr) {
if (expr instanceof ConstantExpression) {
Object value = ((ConstantExpression)expr).getValue();
if (value instanceof Number)
return;
/**
* Validates that the expression can be used in == or <> expression.
* Cannot not be NULL TRUE or FALSE litterals.
// 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.");
}
}
/**
* Validates that the expression can be used in == or <> expression. Cannot
* not be NULL TRUE or FALSE litterals.
*
* @param expr
*/
public static void checkEqualOperand(Expression expr ) {
if( expr instanceof ConstantExpression ) {
Object value = ((ConstantExpression)expr).getValue();
if( value == null )
throw new RuntimeException("'"+expr+"' cannot be compared.");
}
}
* @param expr
*/
public static void checkEqualOperand(Expression expr) {
if (expr instanceof ConstantExpression) {
Object value = ((ConstantExpression)expr).getValue();
if (value == null)
throw new RuntimeException("'" + expr + "' cannot be compared.");
}
}
/**
*
* @param left
* @param right
*/
private static void checkEqualOperandCompatability(Expression left, Expression right) {
if( left instanceof ConstantExpression && right instanceof ConstantExpression ) {
if( left instanceof BooleanExpression && !(right instanceof BooleanExpression) )
throw new RuntimeException("'"+left+"' cannot be compared with '"+right+"'");
}
}
/**
*
* @param left
* @param right
*/
private static void checkEqualOperandCompatability(Expression left, Expression right) {
if (left instanceof ConstantExpression && right instanceof ConstantExpression) {
if (left instanceof BooleanExpression && !(right instanceof BooleanExpression))
throw new RuntimeException("'" + left + "' cannot be compared with '" + right + "'");
}
}
/**
* @param left
* @param right
@ -334,11 +332,11 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
}
public Object evaluate(MessageEvaluationContext message) throws JMSException {
Comparable lv = (Comparable) left.evaluate(message);
Comparable lv = (Comparable)left.evaluate(message);
if (lv == null) {
return null;
}
Comparable rv = (Comparable) right.evaluate(message);
Comparable rv = (Comparable)right.evaluate(message);
if (rv == null) {
return null;
}
@ -353,106 +351,81 @@ public abstract class ComparisonExpression extends BinaryExpression implements B
if (lc != rc) {
if (lc == Byte.class) {
if (rc == Short.class) {
lv = Short.valueOf(((Number) lv).shortValue());
}
else if (rc == Integer.class) {
lv = Integer.valueOf(((Number) lv).intValue());
}
else if (rc == Long.class) {
lv = Long.valueOf(((Number) lv).longValue());
}
else if (rc == Float.class) {
lv = new Float(((Number) lv).floatValue());
}
else if (rc == Double.class) {
lv = new Double(((Number) lv).doubleValue());
}
else {
lv = Short.valueOf(((Number)lv).shortValue());
} else if (rc == Integer.class) {
lv = Integer.valueOf(((Number)lv).intValue());
} else if (rc == Long.class) {
lv = Long.valueOf(((Number)lv).longValue());
} else if (rc == Float.class) {
lv = new Float(((Number)lv).floatValue());
} else if (rc == Double.class) {
lv = new Double(((Number)lv).doubleValue());
} else {
return Boolean.FALSE;
}
} else if (lc == Short.class) {
} else if (lc == Short.class) {
if (rc == Integer.class) {
lv = Integer.valueOf(((Number) lv).intValue());
}
else if (rc == Long.class) {
lv = Long.valueOf(((Number) lv).longValue());
}
else if (rc == Float.class) {
lv = new Float(((Number) lv).floatValue());
}
else if (rc == Double.class) {
lv = new Double(((Number) lv).doubleValue());
}
else {
lv = Integer.valueOf(((Number)lv).intValue());
} else if (rc == Long.class) {
lv = Long.valueOf(((Number)lv).longValue());
} else if (rc == Float.class) {
lv = new Float(((Number)lv).floatValue());
} else if (rc == Double.class) {
lv = new Double(((Number)lv).doubleValue());
} else {
return Boolean.FALSE;
}
} else if (lc == Integer.class) {
if (rc == Long.class) {
lv = Long.valueOf(((Number) lv).longValue());
}
else if (rc == Float.class) {
lv = new Float(((Number) lv).floatValue());
}
else if (rc == Double.class) {
lv = new Double(((Number) lv).doubleValue());
}
else {
lv = Long.valueOf(((Number)lv).longValue());
} else if (rc == Float.class) {
lv = new Float(((Number)lv).floatValue());
} else if (rc == Double.class) {
lv = new Double(((Number)lv).doubleValue());
} else {
return Boolean.FALSE;
}
}
else if (lc == Long.class) {
} else if (lc == Long.class) {
if (rc == Integer.class) {
rv = Long.valueOf(((Number) rv).longValue());
}
else if (rc == Float.class) {
lv = new Float(((Number) lv).floatValue());
}
else if (rc == Double.class) {
lv = new Double(((Number) lv).doubleValue());
}
else {
rv = Long.valueOf(((Number)rv).longValue());
} else if (rc == Float.class) {
lv = new Float(((Number)lv).floatValue());
} else if (rc == Double.class) {
lv = new Double(((Number)lv).doubleValue());
} else {
return Boolean.FALSE;
}
}
else if (lc == Float.class) {
} else if (lc == Float.class) {
if (rc == Integer.class) {
rv = new Float(((Number) rv).floatValue());
}
else if (rc == Long.class) {
rv = new Float(((Number) rv).floatValue());
}
else if (rc == Double.class) {
lv = new Double(((Number) lv).doubleValue());
}
else {
rv = new Float(((Number)rv).floatValue());
} else if (rc == Long.class) {
rv = new Float(((Number)rv).floatValue());
} else if (rc == Double.class) {
lv = new Double(((Number)lv).doubleValue());
} else {
return Boolean.FALSE;
}
}
else if (lc == Double.class) {
} else if (lc == Double.class) {
if (rc == Integer.class) {
rv = new Double(((Number) rv).doubleValue());
}
else if (rc == Long.class) {
rv = new Double(((Number) rv).doubleValue());
}
else if (rc == Float.class) {
rv = new Float(((Number) rv).doubleValue());
}
else {
rv = new Double(((Number)rv).doubleValue());
} else if (rc == Long.class) {
rv = new Double(((Number)rv).doubleValue());
} else if (rc == Float.class) {
rv = new Float(((Number)rv).doubleValue());
} else {
return Boolean.FALSE;
}
}
else
} else
return Boolean.FALSE;
}
return asBoolean(lv.compareTo(rv)) ? Boolean.TRUE : Boolean.FALSE;
}
protected abstract boolean asBoolean(int answer);
public boolean matches(MessageEvaluationContext message) throws JMSException {
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) {
super(value);
}
public boolean matches(MessageEvaluationContext message) throws JMSException {
Object object = evaluate(message);
return object!=null && object==Boolean.TRUE;
}
return object != null && object == Boolean.TRUE;
}
}
public static final BooleanConstantExpression NULL = new BooleanConstantExpression(null);
@ -44,19 +45,19 @@ public class ConstantExpression implements Expression {
private Object value;
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;
try {
value = new Long(text);
} catch ( NumberFormatException e) {
// The number may be too big to fit in a long.
value = new BigDecimal(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;
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();
if (Integer.MIN_VALUE <= l && l <= Integer.MAX_VALUE) {
value = Integer.valueOf(value.intValue());
@ -97,7 +98,7 @@ public class ConstantExpression implements Expression {
public Object getValue() {
return value;
}
}
/**
* @see java.lang.Object#toString()
@ -107,17 +108,17 @@ public class ConstantExpression implements Expression {
return "NULL";
}
if (value instanceof Boolean) {
return ((Boolean) value).booleanValue() ? "TRUE" : "FALSE";
return ((Boolean)value).booleanValue() ? "TRUE" : "FALSE";
}
if (value instanceof String) {
return encodeString((String) value);
return encodeString((String)value);
}
return value.toString();
}
/**
* TODO: more efficient hashCode()
*
*
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
@ -126,7 +127,7 @@ public class ConstantExpression implements Expression {
/**
* TODO: more efficient hashCode()
*
*
* @see java.lang.Object#equals(java.lang.Object)
*/
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
* when it was provided in a selector.
*
* Encodes the value of string so that it looks like it would look like when
* it was provided in a selector.
*
* @param string
* @return
*/
@ -159,5 +159,5 @@ public class ConstantExpression implements Expression {
b.append('\'');
return b.toString();
}
}

View File

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

View File

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

View File

@ -29,7 +29,7 @@ import org.apache.activemq.command.TransactionId;
import org.apache.activemq.util.JMSExceptionSupport;
/**
* Represents a property expression
* Represents a property expression
*
* @version $Revision: 1.5 $
*/
@ -38,149 +38,151 @@ public class PropertyExpression implements Expression {
interface SubExpression {
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){
ActiveMQDestination dest=message.getOriginalDestination();
if(dest==null)
dest=message.getDestination();
if(dest==null)
static final private HashMap JMS_PROPERTY_EXPRESSIONS = new HashMap();
static {
JMS_PROPERTY_EXPRESSIONS.put("JMSDestination", new SubExpression() {
public Object evaluate(Message message) {
ActiveMQDestination dest = message.getOriginalDestination();
if (dest == null)
dest = message.getDestination();
if (dest == null)
return null;
return dest.toString();
}
});
JMS_PROPERTY_EXPRESSIONS.put("JMSReplyTo",new SubExpression(){
JMS_PROPERTY_EXPRESSIONS.put("JMSReplyTo", new SubExpression() {
public Object evaluate(Message message){
if(message.getReplyTo()==null)
public Object evaluate(Message message) {
if (message.getReplyTo() == null)
return null;
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();
}
});
JMS_PROPERTY_EXPRESSIONS.put("JMSDeliveryMode",new SubExpression(){
JMS_PROPERTY_EXPRESSIONS.put("JMSDeliveryMode", new SubExpression() {
public Object evaluate(Message message){
return Integer.valueOf(message.isPersistent()?DeliveryMode.PERSISTENT:DeliveryMode.NON_PERSISTENT);
public Object evaluate(Message message) {
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());
}
});
JMS_PROPERTY_EXPRESSIONS.put("JMSMessageID",new SubExpression(){
JMS_PROPERTY_EXPRESSIONS.put("JMSMessageID", new SubExpression() {
public Object evaluate(Message message){
if(message.getMessageId()==null)
public Object evaluate(Message message) {
if (message.getMessageId() == null)
return null;
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());
}
});
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();
}
});
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());
}
});
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());
}
});
JMS_PROPERTY_EXPRESSIONS.put("JMSXDeliveryCount",new SubExpression(){
JMS_PROPERTY_EXPRESSIONS.put("JMSXDeliveryCount", new SubExpression() {
public Object evaluate(Message message){
return Integer.valueOf(message.getRedeliveryCounter()+1);
public Object evaluate(Message message) {
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();
}
});
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());
}
});
JMS_PROPERTY_EXPRESSIONS.put("JMSXProducerTXID",new SubExpression(){
JMS_PROPERTY_EXPRESSIONS.put("JMSXProducerTXID", new SubExpression() {
public Object evaluate(Message message){
TransactionId txId=message.getOriginalTransactionId();
if(txId==null)
txId=message.getTransactionId();
if(txId==null)
public Object evaluate(Message message) {
TransactionId txId = message.getOriginalTransactionId();
if (txId == null)
txId = message.getTransactionId();
if (txId == null)
return null;
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());
}
});
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());
}
});
}
private final String name;
private final SubExpression jmsPropertyExpression;
public PropertyExpression(String 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 {
try {
if( message.isDropped() )
if (message.isDropped())
return null;
if( jmsPropertyExpression!=null )
if (jmsPropertyExpression != null)
return jmsPropertyExpression.evaluate(message.getMessage());
try {
return message.getMessage().getProperty(name);
} 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) {
throw JMSExceptionSupport.create(e);
}
}
public Object evaluate(Message message) throws JMSException {
if( jmsPropertyExpression!=null )
if (jmsPropertyExpression != null)
return jmsPropertyExpression.evaluate(message);
try {
return message.getProperty(name);
@ -193,7 +195,6 @@ public class PropertyExpression implements Expression {
return name;
}
/**
* @see java.lang.Object#toString()
*/
@ -216,7 +217,7 @@ public class PropertyExpression implements Expression {
if (o == null || !this.getClass().equals(o.getClass())) {
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;
}
if (rvalue instanceof Number) {
return negate((Number) rvalue);
return negate((Number)rvalue);
}
return null;
}
@ -53,83 +53,83 @@ public abstract class UnaryExpression implements Expression {
};
}
public static BooleanExpression createInExpression(PropertyExpression right, List elements, final boolean not) {
// Use a HashSet if there are many elements.
Collection t;
if( elements.size()==0 )
t=null;
else if( elements.size() < 5 )
t = elements;
else {
t = new HashSet(elements);
}
final Collection inList = t;
public static BooleanExpression createInExpression(PropertyExpression right, List elements,
final boolean not) {
// Use a HashSet if there are many elements.
Collection t;
if (elements.size() == 0)
t = null;
else if (elements.size() < 5)
t = elements;
else {
t = new HashSet(elements);
}
final Collection inList = t;
return new BooleanUnaryExpression(right) {
public Object evaluate(MessageEvaluationContext message) throws JMSException {
Object rvalue = right.evaluate(message);
if (rvalue == null) {
return null;
}
if( rvalue.getClass()!=String.class )
return null;
if( (inList!=null && inList.contains(rvalue)) ^ not ) {
return Boolean.TRUE;
if (rvalue.getClass() != String.class)
return null;
if ((inList != null && inList.contains(rvalue)) ^ not) {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
return Boolean.FALSE;
}
}
public String toString() {
StringBuffer answer = new StringBuffer();
answer.append(right);
answer.append(" ");
answer.append(getExpressionSymbol());
answer.append(" ( ");
StringBuffer answer = new StringBuffer();
answer.append(right);
answer.append(" ");
answer.append(getExpressionSymbol());
answer.append(" ( ");
int count=0;
for (Iterator i = inList.iterator(); i.hasNext();) {
Object o = (Object) i.next();
if( count!=0 ) {
answer.append(", ");
}
answer.append(o);
count++;
}
answer.append(" )");
int count = 0;
for (Iterator i = inList.iterator(); i.hasNext();) {
Object o = (Object)i.next();
if (count != 0) {
answer.append(", ");
}
answer.append(o);
count++;
}
answer.append(" )");
return answer.toString();
}
}
public String getExpressionSymbol() {
if( not )
return "NOT IN";
else
return "IN";
if (not)
return "NOT IN";
else
return "IN";
}
};
}
abstract static class BooleanUnaryExpression extends UnaryExpression implements BooleanExpression {
public BooleanUnaryExpression(Expression left) {
public BooleanUnaryExpression(Expression left) {
super(left);
}
public boolean matches(MessageEvaluationContext message) throws JMSException {
Object object = evaluate(message);
return object!=null && object==Boolean.TRUE;
return object != null && object == Boolean.TRUE;
}
};
public static BooleanExpression createNOT(BooleanExpression left) {
return new BooleanUnaryExpression(left) {
public Object evaluate(MessageEvaluationContext message) throws JMSException {
Boolean lvalue = (Boolean) right.evaluate(message);
Boolean lvalue = (Boolean)right.evaluate(message);
if (lvalue == null) {
return null;
}
@ -141,7 +141,7 @@ public abstract class UnaryExpression implements Expression {
}
};
}
public static BooleanExpression createXPath(final String xpath) {
return new XPathExpression(xpath);
}
@ -154,9 +154,9 @@ public abstract class UnaryExpression implements Expression {
return new BooleanUnaryExpression(left) {
public Object evaluate(MessageEvaluationContext message) throws JMSException {
Object rvalue = right.evaluate(message);
if (rvalue == null)
if (rvalue == null)
return null;
if (!rvalue.getClass().equals(Boolean.class))
if (!rvalue.getClass().equals(Boolean.class))
return 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) {
Class clazz = left.getClass();
Class clazz = left.getClass();
if (clazz == Integer.class) {
return new Integer(-left.intValue());
}
else if (clazz == Long.class) {
} else if (clazz == Long.class) {
return new Long(-left.longValue());
}
else if (clazz == Float.class) {
} else if (clazz == Float.class) {
return new Float(-left.floatValue());
}
else if (clazz == Double.class) {
} else if (clazz == Double.class) {
return new Double(-left.doubleValue());
}
else if (clazz == BigDecimal.class) {
// We ussually get a big deciamal when we have Long.MIN_VALUE constant in the
// Selector. Long.MIN_VALUE is too big to store in a Long as a positive so we store it
// as a Big decimal. But it gets Negated right away.. to here we try to covert it back
// to a Long.
BigDecimal bd = (BigDecimal)left;
bd = bd.negate();
if( BD_LONG_MIN_VALUE.compareTo(bd)==0 ) {
return Long.valueOf(Long.MIN_VALUE);
}
} else if (clazz == BigDecimal.class) {
// We ussually get a big deciamal when we have Long.MIN_VALUE
// constant in the
// Selector. Long.MIN_VALUE is too big to store in a Long as a
// positive so we store it
// as a Big decimal. But it gets Negated right away.. to here we try
// to covert it back
// to a Long.
BigDecimal bd = (BigDecimal)left;
bd = bd.negate();
if (BD_LONG_MIN_VALUE.compareTo(bd) == 0) {
return Long.valueOf(Long.MIN_VALUE);
}
return bd;
}
else {
throw new RuntimeException("Don't know how to negate: "+left);
} else {
throw new RuntimeException("Don't know how to negate: " + left);
}
}
@ -224,7 +222,7 @@ public abstract class UnaryExpression implements Expression {
/**
* TODO: more efficient hashCode()
*
*
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
@ -233,7 +231,7 @@ public abstract class UnaryExpression implements Expression {
/**
* TODO: more efficient hashCode()
*
*
* @see java.lang.Object#equals(java.lang.Object)
*/
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
* represented by "+"
*
* Returns the symbol that represents this binary expression. For example,
* addition is represented by "+"
*
* @return
*/
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 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;
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;
try {
try {
m = getXPathEvaluatorConstructor(cn);
} 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;
try {
m = getXPathEvaluatorConstructor(cn);
} catch (Throwable e2) {
log.error("Default XPath evaluator could not be loaded",e);
log.error("Default XPath evaluator could not be loaded", e);
}
}
} 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);
if( !XPathEvaluator.class.isAssignableFrom(c) ) {
throw new ClassCastException(""+c+" is not an instance of "+XPathEvaluator.class);
if (!XPathEvaluator.class.isAssignableFrom(c)) {
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 XPathEvaluator evaluator;
static public interface XPathEvaluator {
public boolean evaluate(Message message) throws JMSException;
}
}
XPathExpression(String xpath) {
this.xpath = xpath;
this.evaluator = createEvaluator(xpath);
@ -80,21 +82,21 @@ public final class XPathExpression implements BooleanExpression {
private XPathEvaluator createEvaluator(String xpath2) {
try {
return (XPathEvaluator)EVALUATOR_CONSTRUCTOR.newInstance(new Object[]{xpath});
return (XPathEvaluator)EVALUATOR_CONSTRUCTOR.newInstance(new Object[] {xpath});
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if( cause instanceof RuntimeException ) {
if (cause instanceof RuntimeException) {
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) {
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 {
try {
if( message.isDropped() )
if (message.isDropped())
return null;
return evaluator.evaluate(message.getMessage()) ? Boolean.TRUE : Boolean.FALSE;
} catch (IOException e) {
@ -104,9 +106,9 @@ public final class XPathExpression implements BooleanExpression {
}
public String toString() {
return "XPATH "+ConstantExpression.encodeString(xpath);
return "XPATH " + ConstantExpression.encodeString(xpath);
}
/**
* @param message
* @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 {
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() {
return "XQUERY "+ConstantExpression.encodeString(xpath);
return "XQUERY " + ConstantExpression.encodeString(xpath);
}
/**
* @param message
* @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 {
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;
public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator {
private final String xpath;
public XalanXPathEvaluator(String xpath) {
this.xpath = xpath;
}
public boolean evaluate(Message m) throws JMSException {
if( m instanceof TextMessage ) {
if (m instanceof TextMessage) {
String text = ((TextMessage)m).getText();
return evaluate(text);
} else if ( m instanceof BytesMessage ) {
BytesMessage bm = (BytesMessage) m;
byte data[] = new byte[(int) bm.getBodyLength()];
return evaluate(text);
} else if (m instanceof BytesMessage) {
BytesMessage bm = (BytesMessage)m;
byte data[] = new byte[(int)bm.getBodyLength()];
bm.readBytes(data);
return evaluate(data);
}
}
return false;
}
private boolean evaluate(byte[] data) {
try {
InputSource inputSource = new InputSource(new ByteArrayInputStream(data));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder dbuilder = factory.newDocumentBuilder();
Document doc = dbuilder.parse(inputSource);
CachedXPathAPI cachedXPathAPI = new CachedXPathAPI();
NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc,xpath);
return iterator.nextNode()!=null;
NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc, xpath);
return iterator.nextNode() != null;
} catch (Throwable e) {
return false;
}
@ -75,17 +75,18 @@ public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator {
private boolean evaluate(String text) {
try {
InputSource inputSource = new InputSource(new StringReader(text));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder dbuilder = factory.newDocumentBuilder();
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.
CachedXPathAPI cachedXPathAPI = new CachedXPathAPI();
NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc,xpath);
return iterator.nextNode()!=null;
NodeIterator iterator = cachedXPathAPI.selectNodeIterator(doc, xpath);
return iterator.nextNode() != null;
} catch (Throwable e) {
return false;
}

View File

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

View File

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

View File

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

View File

@ -18,16 +18,17 @@ import java.util.List;
import java.util.NoSuchElementException;
/**
* Represents a container of persistent objects in the store Acts as a map, but values can be retrieved in insertion
* order
* Represents a container of persistent objects in the store Acts as a map, but
* values can be retrieved in insertion order
*
* @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
* used etc and should be called before any operations on the container
* The container is created or retrieved in an unloaded state. load
* populates the container will all the indexes used etc and should be
* called before any operations on the container
*/
public void load();
@ -43,7 +44,8 @@ public interface ListContainer<V> extends List<V>{
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
*/
@ -67,8 +69,8 @@ public interface ListContainer<V> extends List<V>{
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
* only for consistency.)
* Appends the given element to the end of this list. (Identical in function
* to the <tt>add</tt> method; included only for consistency.)
*
* @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();
/**
* 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
* @return true if successful
@ -107,7 +110,8 @@ public interface ListContainer<V> extends List<V>{
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
* @return the location in the Store
@ -115,12 +119,13 @@ public interface ListContainer<V> extends List<V>{
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 object
*/
public void update(StoreEntry entry,V object);
public void update(StoreEntry entry, V object);
/**
* Retrieve an Object from the Store by its location
@ -167,10 +172,11 @@ public interface ListContainer<V> extends List<V>{
* @return true if successful
*/
public boolean remove(StoreEntry entry);
/**
* It's possible that a StoreEntry could be come stale
* this will return an upto date entry for the StoreEntry position
* It's possible that a StoreEntry could be come stale this will return an
* upto date entry for the StoreEntry position
*
* @param entry old entry
* @return a refreshed StoreEntry
*/

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -8,35 +8,32 @@ import org.apache.activemq.kaha.impl.data.RedoListener;
public interface DataManager {
String getName();
String getName();
Object readItem(Marshaller marshaller, StoreLocation item)
throws IOException;
Object readItem(Marshaller marshaller, StoreLocation item) throws IOException;
StoreLocation storeDataItem(Marshaller marshaller, Object payload)
throws IOException;
StoreLocation storeDataItem(Marshaller marshaller, Object payload) throws IOException;
StoreLocation storeRedoItem(Object payload) throws IOException;
StoreLocation storeRedoItem(Object payload) throws IOException;
void updateItem(StoreLocation location, Marshaller marshaller,
Object payload) throws IOException;
void updateItem(StoreLocation location, Marshaller marshaller, 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;
/**
* A container of roots for other Containers
*
* @version $Revision: 1.2 $
*/
* A container of roots for other Containers
*
* @version $Revision: 1.2 $
*/
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 IndexItem root;
protected IndexManager indexManager;
protected DataManager dataManager;
protected Map map = new ConcurrentHashMap();
protected LinkedList list = new LinkedList();
IndexRootContainer(IndexItem root,IndexManager im,DataManager dfm) throws IOException{
this.root=root;
this.indexManager=im;
this.dataManager=dfm;
long nextItem=root.getNextItem();
while(nextItem!=Item.POSITION_NOT_SET){
StoreEntry item=indexManager.getIndex(nextItem);
StoreLocation data=item.getKeyDataItem();
Object key = dataManager.readItem(rootMarshaller,data);
map.put(key,item);
IndexRootContainer(IndexItem root, IndexManager im, DataManager dfm) throws IOException {
this.root = root;
this.indexManager = im;
this.dataManager = dfm;
long nextItem = root.getNextItem();
while (nextItem != Item.POSITION_NOT_SET) {
StoreEntry item = indexManager.getIndex(nextItem);
StoreLocation data = item.getKeyDataItem();
Object key = dataManager.readItem(rootMarshaller, data);
map.put(key, item);
list.add(item);
nextItem=item.getNextItem();
nextItem = item.getNextItem();
dataManager.addInterestInFile(item.getKeyFile());
}
}
Set getKeys(){
Set getKeys() {
return map.keySet();
}
IndexItem addRoot(IndexManager containerIndexManager,ContainerId key) throws IOException{
if (map.containsKey(key)){
removeRoot(containerIndexManager,key);
IndexItem addRoot(IndexManager containerIndexManager, ContainerId key) throws IOException {
if (map.containsKey(key)) {
removeRoot(containerIndexManager, key);
}
StoreLocation data = dataManager.storeDataItem(rootMarshaller, key);
IndexItem newRoot = indexManager.createNewIndex();
newRoot.setKeyData(data);
IndexItem containerRoot = containerIndexManager.createNewIndex();
containerIndexManager.storeIndex(containerRoot);
newRoot.setValueOffset(containerRoot.getOffset());
IndexItem last=list.isEmpty()?null:(IndexItem) list.getLast();
last=last==null?root:last;
long prev=last.getOffset();
IndexItem last = list.isEmpty() ? null : (IndexItem)list.getLast();
last = last == null ? root : last;
long prev = last.getOffset();
newRoot.setPreviousItem(prev);
indexManager.storeIndex(newRoot);
last.setNextItem(newRoot.getOffset());
@ -95,25 +92,25 @@ class IndexRootContainer {
list.add(newRoot);
return containerRoot;
}
void removeRoot(IndexManager containerIndexManager,ContainerId key) throws IOException{
StoreEntry oldRoot=(StoreEntry)map.remove(key);
if(oldRoot!=null){
void removeRoot(IndexManager containerIndexManager, ContainerId key) throws IOException {
StoreEntry oldRoot = (StoreEntry)map.remove(key);
if (oldRoot != null) {
dataManager.removeInterestInFile(oldRoot.getKeyFile());
// get the container root
IndexItem containerRoot=containerIndexManager.getIndex(oldRoot.getValueOffset());
if(containerRoot!=null){
IndexItem containerRoot = containerIndexManager.getIndex(oldRoot.getValueOffset());
if (containerRoot != null) {
containerIndexManager.freeIndex(containerRoot);
}
int index=list.indexOf(oldRoot);
IndexItem prev=index>0?(IndexItem)list.get(index-1):root;
prev=prev==null?root:prev;
IndexItem next=index<(list.size()-1)?(IndexItem)list.get(index+1):null;
if(next!=null){
int index = list.indexOf(oldRoot);
IndexItem prev = index > 0 ? (IndexItem)list.get(index - 1) : root;
prev = prev == null ? root : prev;
IndexItem next = index < (list.size() - 1) ? (IndexItem)list.get(index + 1) : null;
if (next != null) {
prev.setNextItem(next.getOffset());
next.setPreviousItem(prev.getOffset());
indexManager.updateIndexes(next);
}else{
} else {
prev.setNextItem(Item.POSITION_NOT_SET);
}
indexManager.updateIndexes(prev);
@ -121,19 +118,17 @@ class IndexRootContainer {
indexManager.freeIndex((IndexItem)oldRoot);
}
}
IndexItem getRoot(IndexManager containerIndexManager,ContainerId key) throws IOException{
StoreEntry index = (StoreEntry) map.get(key);
if (index != null){
IndexItem getRoot(IndexManager containerIndexManager, ContainerId key) throws IOException {
StoreEntry index = (StoreEntry)map.get(key);
if (index != null) {
return containerIndexManager.getIndex(index.getValueOffset());
}
return null;
}
boolean doesRootExist(Object key){
boolean doesRootExist(Object key) {
return map.containsKey(key);
}
}

View File

@ -18,27 +18,25 @@ package org.apache.activemq.kaha.impl;
import java.io.IOException;
/**
* Exception thrown if the store is in use by another application
*
* @version $Revision: 1.1.1.1 $
*/
public class StoreLockedExcpetion extends IOException{
* Exception thrown if the store is in use by another application
*
* @version $Revision: 1.1.1.1 $
*/
public class StoreLockedExcpetion extends IOException {
private static final long serialVersionUID=3857646689671366926L;
private static final long serialVersionUID = 3857646689671366926L;
/**
* Default Constructor
*/
public StoreLockedExcpetion(){
public StoreLockedExcpetion() {
}
/**
* @param s
*/
public StoreLockedExcpetion(String s){
public StoreLockedExcpetion(String 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.WriteKey;
import org.apache.activemq.util.ByteSequence;
/**
* Optimized Store reader and updater. Single threaded and synchronous. Use in conjunction
* with the DataFileAccessorPool of concurrent use.
* Optimized Store reader and updater. Single threaded and synchronous. Use in
* conjunction with the DataFileAccessorPool of concurrent use.
*
* @version $Revision: 1.1.1.1 $
*/
final class DataFileAccessor {
private final DataFile dataFile;
private final ConcurrentHashMap<WriteKey, WriteCommand> inflightWrites;
private final RandomAccessFile file;
private boolean disposed;
private final DataFile dataFile;
private final ConcurrentHashMap<WriteKey, WriteCommand> inflightWrites;
private final RandomAccessFile file;
private boolean disposed;
/**
* Construct a Store reader
*
* @param fileId
* @throws IOException
* @throws IOException
*/
public DataFileAccessor(AsyncDataManager dataManager, DataFile dataFile) throws IOException{
this.dataFile = dataFile;
this.inflightWrites = dataManager.getInflightWrites();
this.file = dataFile.openRandomAccessFile(false);
public DataFileAccessor(AsyncDataManager dataManager, DataFile dataFile) throws IOException {
this.dataFile = dataFile;
this.inflightWrites = dataManager.getInflightWrites();
this.file = dataFile.openRandomAccessFile(false);
}
public DataFile getDataFile() {
return dataFile;
}
public DataFile getDataFile() {
return dataFile;
}
public void dispose() {
if( disposed )
return;
disposed=true;
public void dispose() {
if (disposed)
return;
disposed = true;
try {
dataFile.closeRandomAccessFile(file);
} catch (IOException e) {
e.printStackTrace();
}
dataFile.closeRandomAccessFile(file);
} catch (IOException e) {
e.printStackTrace();
}
}
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 ) {
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);
WriteCommand asyncWrite = (WriteCommand)inflightWrites.get(new WriteKey(location));
if (asyncWrite != null) {
return asyncWrite.data;
}
} catch (RuntimeException e) {
throw new IOException("Invalid location: "+location+", : "+e);
}
try {
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 {
WriteCommand asyncWrite = (WriteCommand) inflightWrites.get(new WriteKey(location));
if( asyncWrite!= null ) {
location.setSize(asyncWrite.location.getSize());
location.setType(asyncWrite.location.getType());
} else {
file.seek(location.getOffset());
location.setSize(file.readInt());
location.setType(file.readByte());
}
WriteCommand asyncWrite = (WriteCommand)inflightWrites.get(new WriteKey(location));
if (asyncWrite != null) {
location.setSize(asyncWrite.location.getSize());
location.setType(asyncWrite.location.getType());
} else {
file.seek(location.getOffset());
location.setSize(file.readInt());
location.setType(file.readByte());
}
}
public boolean readLocationDetailsAndValidate(Location location) {
try {
WriteCommand asyncWrite = (WriteCommand) inflightWrites.get(new WriteKey(location));
if( asyncWrite!= null ) {
location.setSize(asyncWrite.location.getSize());
location.setType(asyncWrite.location.getType());
} else {
file.seek(location.getOffset());
location.setSize(file.readInt());
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 boolean readLocationDetailsAndValidate(Location location) {
try {
WriteCommand asyncWrite = (WriteCommand)inflightWrites.get(new WriteKey(location));
if (asyncWrite != null) {
location.setSize(asyncWrite.location.getSize());
location.setType(asyncWrite.location.getType());
} else {
file.seek(location.getOffset());
location.setSize(file.readInt());
location.setType(file.readByte());
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();
}
}
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 {
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;
/**
* An optimized writer to do batch appends to a data file. This object is thread safe
* and gains throughput as you increase the number of concurrent writes it does.
* An optimized writer to do batch appends to a data file. This object is thread
* safe and gains throughput as you increase the number of concurrent writes it
* does.
*
* @version $Revision: 1.1.1.1 $
*/
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){
file = item.getDataFileId();
offset = item.getOffset();
// TODO: see if we can build a better hash
hash = (int) (file ^ 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;
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) {
file = item.getDataFileId();
offset = item.getOffset();
// TODO: see if we can build a better hash
hash = (int)(file ^ 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;
}
}
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 Object enqueueMutex = new Object();
protected WriteBatch nextWriteBatch;
protected WriteBatch nextWriteBatch;
private boolean running;
protected boolean shutdown;
protected IOException firstAsyncException;
protected final CountDownLatch shutdownDone = new CountDownLatch(1);
private Thread thread;
private Thread thread;
/**
* Construct a Store writer
*
* @param fileId
*/
public DataFileAppender(AsyncDataManager dataManager){
this.dataManager=dataManager;
public DataFileAppender(AsyncDataManager dataManager) {
this.dataManager = dataManager;
this.inflightWrites = this.dataManager.getInflightWrites();
}
/**
* @param type
* @param type
* @param marshaller
* @param payload
* @param type
* @param sync
* @param type
* @param sync
* @return
* @throws IOException
* @throws
* @throws
* @throws
* @throws
*/
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
// writes get equeued onto the executor in order that they were assigned by
// 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
// writes get equeued onto the executor in order that they were assigned
// by
// the data manager (which is basically just appending)
synchronized(this) {
synchronized (this) {
// Find the position where this item will land at.
DataFile dataFile=dataManager.allocateLocation(location);
batch = enqueue(dataFile, write);
DataFile dataFile = dataManager.allocateLocation(location);
batch = enqueue(dataFile, write);
}
location.setLatch(batch.latch);
if( sync ) {
try {
batch.latch.await();
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
} else {
if (sync) {
try {
batch.latch.await();
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
} else {
inflightWrites.put(new WriteKey(location), write);
}
}
return location;
}
private WriteBatch enqueue(DataFile dataFile, WriteCommand write) throws IOException {
synchronized(enqueueMutex) {
WriteBatch rc=null;
if( shutdown ) {
throw new IOException("Async Writter Thread Shutdown");
}
if( firstAsyncException !=null )
throw firstAsyncException;
if( !running ) {
running=true;
thread = new Thread() {
public void run() {
processQueue();
}
};
thread.setPriority(Thread.MAX_PRIORITY);
thread.setDaemon(true);
thread.setName("ActiveMQ Data File Writer");
thread.start();
}
if( nextWriteBatch == null ) {
nextWriteBatch = new WriteBatch(dataFile,write);
rc = nextWriteBatch;
enqueueMutex.notify();
} else {
// Append to current batch if possible..
if( nextWriteBatch.canAppend(dataFile, write) ) {
nextWriteBatch.append(write);
rc = nextWriteBatch;
} else {
// Otherwise wait for the queuedCommand to be null
try {
while( nextWriteBatch!=null ) {
enqueueMutex.wait();
}
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
if( shutdown ) {
throw new IOException("Async Writter Thread Shutdown");
}
// Start a new batch.
nextWriteBatch = new WriteBatch(dataFile,write);
rc = nextWriteBatch;
enqueueMutex.notify();
}
}
return rc;
}
}
synchronized (enqueueMutex) {
WriteBatch rc = null;
if (shutdown) {
throw new IOException("Async Writter Thread Shutdown");
}
if (firstAsyncException != null)
throw firstAsyncException;
if (!running) {
running = true;
thread = new Thread() {
public void run() {
processQueue();
}
};
thread.setPriority(Thread.MAX_PRIORITY);
thread.setDaemon(true);
thread.setName("ActiveMQ Data File Writer");
thread.start();
}
if (nextWriteBatch == null) {
nextWriteBatch = new WriteBatch(dataFile, write);
rc = nextWriteBatch;
enqueueMutex.notify();
} else {
// Append to current batch if possible..
if (nextWriteBatch.canAppend(dataFile, write)) {
nextWriteBatch.append(write);
rc = nextWriteBatch;
} else {
// Otherwise wait for the queuedCommand to be null
try {
while (nextWriteBatch != null) {
enqueueMutex.wait();
}
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
if (shutdown) {
throw new IOException("Async Writter Thread Shutdown");
}
// Start a new batch.
nextWriteBatch = new WriteBatch(dataFile, write);
rc = nextWriteBatch;
enqueueMutex.notify();
}
}
return rc;
}
}
public void close() throws IOException {
synchronized( enqueueMutex ) {
if( shutdown == false ) {
shutdown = true;
if( running ) {
enqueueMutex.notifyAll();
} else {
shutdownDone.countDown();
}
}
}
try {
shutdownDone.await();
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
synchronized (enqueueMutex) {
if (shutdown == false) {
shutdown = true;
if (running) {
enqueueMutex.notifyAll();
} else {
shutdownDone.countDown();
}
}
}
try {
shutdownDone.await();
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
/**
* The async processing loop that writes to the data files and
* 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,
* this algorithm tries to 'batch' or group together several file sync() requests
* into a single file sync() call. The batching is accomplished attaching the
* same CountDownLatch instance to every force request in a group.
* Since the file sync() call is the slowest of all the operations, this
* algorithm tries to 'batch' or group together several file sync() requests
* into a single file sync() call. The batching is accomplished attaching
* the same CountDownLatch instance to every force request in a group.
*
*/
protected void processQueue() {
DataFile dataFile=null;
RandomAccessFile file=null;
try {
DataByteArrayOutputStream buff = new DataByteArrayOutputStream(MAX_WRITE_BATCH_SIZE);
while( true ) {
Object o = null;
DataFile dataFile = null;
RandomAccessFile file = null;
try {
// Block till we get a command.
synchronized(enqueueMutex) {
while( true ) {
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);
}
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() ) {
// Just write it directly..
file.writeInt(write.location.getSize());
file.writeByte(write.location.getType());
file.write(RESERVED_SPACE);
file.write(AsyncDataManager.ITEM_HEAD_SOR);
file.write(write.data.getData(),write.data.getOffset(), write.data.getLength());
file.write(AsyncDataManager.ITEM_HEAD_EOR);
} else {
// Combine the smaller writes into 1 big buffer
while( write!=null ) {
buff.writeInt(write.location.getSize());
buff.writeByte(write.location.getType());
buff.write(RESERVED_SPACE);
buff.write(AsyncDataManager.ITEM_HEAD_SOR);
buff.write(write.data.getData(),write.data.getOffset(), write.data.getLength());
buff.write(AsyncDataManager.ITEM_HEAD_EOR);
write = (WriteCommand) write.getNext();
}
// Now do the 1 big write.
ByteSequence sequence = buff.toByteSequence();
file.write(sequence.getData(), sequence.getOffset(), sequence.getLength());
buff.reset();
}
file.getFD().sync();
WriteCommand lastWrite = (WriteCommand) wb.first.getTailNode();
dataManager.setLastAppendLocation( lastWrite.location );
// Signal any waiting threads that the write is on disk.
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();
}
}
buff.close();
} catch (IOException e) {
synchronized( enqueueMutex ) {
firstAsyncException = e;
}
} catch (InterruptedException e) {
} finally {
try {
if( file!=null ) {
dataFile.closeRandomAccessFile(file);
}
} catch (IOException e) {
}
shutdownDone.countDown();
}
DataByteArrayOutputStream buff = new DataByteArrayOutputStream(MAX_WRITE_BATCH_SIZE);
while (true) {
Object o = null;
// Block till we get a command.
synchronized (enqueueMutex) {
while (true) {
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);
}
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()) {
// Just write it directly..
file.writeInt(write.location.getSize());
file.writeByte(write.location.getType());
file.write(RESERVED_SPACE);
file.write(AsyncDataManager.ITEM_HEAD_SOR);
file.write(write.data.getData(), write.data.getOffset(), write.data.getLength());
file.write(AsyncDataManager.ITEM_HEAD_EOR);
} else {
// Combine the smaller writes into 1 big buffer
while (write != null) {
buff.writeInt(write.location.getSize());
buff.writeByte(write.location.getType());
buff.write(RESERVED_SPACE);
buff.write(AsyncDataManager.ITEM_HEAD_SOR);
buff.write(write.data.getData(), write.data.getOffset(), write.data.getLength());
buff.write(AsyncDataManager.ITEM_HEAD_EOR);
write = (WriteCommand)write.getNext();
}
// Now do the 1 big write.
ByteSequence sequence = buff.toByteSequence();
file.write(sequence.getData(), sequence.getOffset(), sequence.getLength());
buff.reset();
}
file.getFD().sync();
WriteCommand lastWrite = (WriteCommand)wb.first.getTailNode();
dataManager.setLastAppendLocation(lastWrite.location);
// Signal any waiting threads that the write is on disk.
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();
}
}
buff.close();
} catch (IOException e) {
synchronized (enqueueMutex) {
firstAsyncException = e;
}
} catch (InterruptedException e) {
} finally {
try {
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 {
private static class StoreLocationFacade implements StoreLocation {
private final Location location;
private static class StoreLocationFacade implements StoreLocation {
private final Location location;
public StoreLocationFacade(Location location) {
this.location = location;
}
public StoreLocationFacade(Location location) {
this.location = location;
}
public int getFile() {
return location.getDataFileId();
}
public int getFile() {
return location.getDataFileId();
}
public long getOffset() {
return location.getOffset();
}
public long getOffset() {
return location.getOffset();
}
public int getSize() {
return location.getSize();
}
public int getSize() {
return location.getSize();
}
public Location getLocation() {
return location;
}
}
public Location getLocation() {
return location;
}
}
static private StoreLocation convertToStoreLocation(Location location) {
if(location==null)
return null;
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 private StoreLocation convertToStoreLocation(Location location) {
if (location == null)
return null;
return new StoreLocationFacade(location);
}
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);
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'});
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);
}
}
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 {
final DataByteArrayOutputStream buffer = new DataByteArrayOutputStream();
marshaller.writePayload(payload,buffer);
ByteSequence data = buffer.toByteSequence();
return convertToStoreLocation(dataManager.write(data, (byte)1, false));
}
public void force() throws IOException {
dataManager.write(FORCE_COMMAND, (byte)2, true);
}
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 {
dataManager.write(FORCE_COMMAND, (byte)2, true);
}
public void close() throws IOException {
dataManager.close();
}
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 close() throws IOException {
dataManager.close();
}
public void consolidateDataFiles() throws IOException {
dataManager.consolidateDataFiles();
}
public void consolidateDataFiles() throws IOException {
dataManager.consolidateDataFiles();
}
public boolean delete() throws IOException {
return dataManager.delete();
}
public boolean delete() throws IOException {
return dataManager.delete();
}
public void addInterestInFile(int file) throws IOException {
dataManager.addInterestInFile(file);
}
public void removeInterestInFile(int file) throws IOException {
dataManager.removeInterestInFile(file);
}
public void addInterestInFile(int file) throws IOException {
dataManager.addInterestInFile(file);
}
public void recoverRedoItems(RedoListener listener) throws IOException {
throw new RuntimeException("Not Implemented..");
}
public StoreLocation storeRedoItem(Object payload) throws IOException {
throw new RuntimeException("Not Implemented..");
}
public void removeInterestInFile(int file) throws IOException {
dataManager.removeInterestInFile(file);
}
public Marshaller getRedoMarshaller() {
return redoMarshaller;
}
public void setRedoMarshaller(Marshaller redoMarshaller) {
this.redoMarshaller = redoMarshaller;
}
public void recoverRedoItems(RedoListener listener) throws IOException {
throw new RuntimeException("Not Implemented..");
}
public String getName() {
return name;
}
public StoreLocation storeRedoItem(Object payload) throws IOException {
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 static class RecordLocationFacade implements RecordLocation {
private final Location location;
public static class RecordLocationFacade implements RecordLocation {
private final Location location;
public RecordLocationFacade(Location location) {
this.location = location;
}
public RecordLocationFacade(Location location) {
this.location = location;
}
public Location getLocation() {
return location;
}
public Location getLocation() {
return location;
}
public int compareTo(Object o) {
RecordLocationFacade rlf = (RecordLocationFacade)o;
int rc = location.compareTo(rlf.location);
return rc;
}
}
public int compareTo(Object o) {
RecordLocationFacade rlf = (RecordLocationFacade)o;
int rc = location.compareTo(rlf.location);
return rc;
}
}
static private RecordLocation convertToRecordLocation(Location location) {
if(location==null)
return null;
return new RecordLocationFacade(location);
}
static private Location convertFromRecordLocation(RecordLocation location) {
if(location==null)
return null;
return ((RecordLocationFacade)location).getLocation();
}
static private RecordLocation convertToRecordLocation(Location location) {
if (location == null)
return null;
return new RecordLocationFacade(location);
}
AsyncDataManager dataManager;
public JournalFacade(AsyncDataManager dataManager) {
this.dataManager = dataManager;
}
static private Location convertFromRecordLocation(RecordLocation location) {
public void close() throws IOException {
dataManager.close();
}
if (location == null)
return null;
public RecordLocation getMark() throws IllegalStateException {
return convertToRecordLocation(dataManager.getMark());
}
return ((RecordLocationFacade)location).getLocation();
}
public RecordLocation getNextRecordLocation(RecordLocation location) throws InvalidRecordLocationException, IOException, IllegalStateException {
return convertToRecordLocation(dataManager.getNextLocation(convertFromRecordLocation(location)));
}
AsyncDataManager dataManager;
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 JournalFacade(AsyncDataManager dataManager) {
this.dataManager = dataManager;
}
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 {
dataManager.setMark(convertFromRecordLocation(location), sync);
}
public RecordLocation getMark() throws IllegalStateException {
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 $
*/
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;
private int offset=NOT_SET;
private int size=NOT_SET;
private byte type=NOT_SET_TYPE;
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;
private int offset = NOT_SET;
private int size = NOT_SET;
private byte type = NOT_SET_TYPE;
private CountDownLatch latch;
public Location(){}
public Location() {
}
Location(Location item) {
this.dataFileId = item.dataFileId;
this.offset = item.offset;
this.size = item.size;
this.type = item.type;
}
boolean isValid(){
boolean isValid() {
return dataFileId != NOT_SET;
}
/**
* @return the size of the data record including the header.
*/
public int getSize(){
public int getSize() {
return size;
}
/**
* @param size the size of the data record including the header.
*/
public void setSize(int size){
this.size=size;
public void setSize(int size) {
this.size = size;
}
/**
* @return the size of the payload of the record.
*/
public int getPaylodSize() {
return size-AsyncDataManager.ITEM_HEAD_FOOT_SPACE;
}
public int getOffset(){
return offset;
}
public void setOffset(int offset){
this.offset=offset;
return size - AsyncDataManager.ITEM_HEAD_FOOT_SPACE;
}
public int getDataFileId(){
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public int getDataFileId() {
return dataFileId;
}
public void setDataFileId(int file){
this.dataFileId=file;
public void setDataFileId(int file) {
this.dataFileId = file;
}
public byte getType() {
return type;
}
public byte getType() {
return type;
}
public void setType(byte type) {
this.type = type;
}
public void setType(byte type) {
this.type = type;
}
public String toString(){
String result="offset = "+offset+", file = " + dataFileId + ", size = "+size + ", type = "+type;
public String toString() {
String result = "offset = " + offset + ", file = " + dataFileId + ", size = " + size + ", type = "
+ type;
return result;
}
public void writeExternal(DataOutput dos) throws IOException {
dos.writeInt(dataFileId);
dos.writeInt(offset);
dos.writeInt(size);
dos.writeByte(type);
}
public void writeExternal(DataOutput dos) throws IOException {
dos.writeInt(dataFileId);
dos.writeInt(offset);
dos.writeInt(size);
dos.writeByte(type);
}
public void readExternal(DataInput dis) throws IOException {
dataFileId = dis.readInt();
offset = dis.readInt();
size = dis.readInt();
type = dis.readByte();
}
public void readExternal(DataInput dis) throws IOException {
dataFileId = dis.readInt();
offset = dis.readInt();
size = dis.readInt();
type = dis.readByte();
}
public CountDownLatch getLatch() {
return latch;
}
public void setLatch(CountDownLatch latch) {
this.latch = latch;
}
public CountDownLatch getLatch() {
return 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) {
boolean result = false;
if (o instanceof Location) {
result = compareTo((Location)o)==0;
result = compareTo((Location)o) == 0;
}
return result;
}
public int hashCode() {
return dataFileId ^ offset;
}
}

View File

@ -22,191 +22,194 @@ import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* An AsyncDataFileAppender that uses NIO ByteBuffers and File chanels to more efficently
* copy data to files.
* An AsyncDataFileAppender that uses NIO ByteBuffers and File chanels to more
* efficently copy data to files.
*
* @version $Revision: 1.1.1.1 $
*/
class NIODataFileAppender extends DataFileAppender {
public NIODataFileAppender(AsyncDataManager fileManager) {
super(fileManager);
}
/**
* The async processing loop that writes to the data files and
* does the force calls.
public NIODataFileAppender(AsyncDataManager fileManager) {
super(fileManager);
}
/**
* 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,
* this algorithm tries to 'batch' or group together several file sync() requests
* into a single file sync() call. The batching is accomplished attaching the
* same CountDownLatch instance to every force request in a group.
* Since the file sync() call is the slowest of all the operations, this
* algorithm tries to 'batch' or group together several file sync() requests
* into a single file sync() call. The batching is accomplished attaching
* the same CountDownLatch instance to every force request in a group.
*
*/
protected void processQueue() {
DataFile dataFile=null;
RandomAccessFile file=null;
FileChannel channel=null;
DataFile dataFile = null;
RandomAccessFile file = null;
FileChannel channel = null;
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;
try {
// Block till we get a command.
synchronized(enqueueMutex) {
while( true ) {
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();
ByteBuffer header = ByteBuffer.allocateDirect(AsyncDataManager.ITEM_HEAD_SPACE);
ByteBuffer footer = ByteBuffer.allocateDirect(AsyncDataManager.ITEM_FOOT_SPACE);
ByteBuffer buffer = ByteBuffer.allocateDirect(MAX_WRITE_BATCH_SIZE);
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);
// 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);
WriteCommand lastWrite = (WriteCommand) wb.first.getTailNode();
dataManager.setLastAppendLocation( lastWrite.location );
while (true) {
// 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();
}
Object o = null;
// Block till we get a command.
synchronized (enqueueMutex) {
while (true) {
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();
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.
*
* @param header - source of data
* @param channel - destination where the data will be written.
* @throws IOException
*/
private void transfer(ByteBuffer header, FileChannel channel) throws IOException {
while (header.hasRemaining()) {
channel.write(header);
}
}
private void transfer(ByteBuffer header, FileChannel channel) throws IOException {
while (header.hasRemaining()) {
channel.write(header);
}
}
private int copy(ByteBuffer src, ByteBuffer dest) {
int rc = Math.min(dest.remaining(), src.remaining());
if( rc > 0 ) {
// Adjust our limit so that we don't overflow the dest buffer.
int limit = src.limit();
src.limit(src.position()+rc);
private int copy(ByteBuffer src, ByteBuffer dest) {
int rc = Math.min(dest.remaining(), src.remaining());
if (rc > 0) {
// Adjust our limit so that we don't overflow the dest buffer.
int limit = src.limit();
src.limit(src.position() + rc);
dest.put(src);
// restore the limit.
src.limit(limit);
}
return rc;
}
src.limit(limit);
}
return rc;
}
}

View File

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

View File

@ -18,33 +18,33 @@ package org.apache.activemq.kaha.impl.container;
import java.util.Iterator;
/**
* An Iterator for a container entry Set
*
* @version $Revision: 1.2 $
*/
public class ContainerEntrySetIterator implements Iterator{
* An Iterator for a container entry Set
*
* @version $Revision: 1.2 $
*/
public class ContainerEntrySetIterator implements Iterator {
private MapContainerImpl container;
private Iterator iter;
private Iterator iter;
private ContainerMapEntry currentEntry;
ContainerEntrySetIterator(MapContainerImpl container,Iterator iter){
ContainerEntrySetIterator(MapContainerImpl container, Iterator iter) {
this.container = container;
this.iter = iter;
}
public boolean hasNext(){
public boolean hasNext() {
return iter.hasNext();
}
public Object next(){
currentEntry = (ContainerMapEntry) iter.next();
public Object next() {
currentEntry = (ContainerMapEntry)iter.next();
return currentEntry;
}
public void remove(){
if (currentEntry != null){
container.remove(currentEntry.getKey());
}
public void remove() {
if (currentEntry != null) {
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;
/**
* A Set of keys for the container
*
* @version $Revision: 1.2 $
*/
public class ContainerKeySet extends ContainerCollectionSupport implements Set{
ContainerKeySet(MapContainerImpl container){
* A Set of keys for the container
*
* @version $Revision: 1.2 $
*/
public class ContainerKeySet extends ContainerCollectionSupport implements Set {
ContainerKeySet(MapContainerImpl container) {
super(container);
}
public boolean contains(Object o){
public boolean contains(Object o) {
return container.containsKey(o);
}
public Iterator iterator(){
public Iterator iterator() {
return new ContainerKeySetIterator(container);
}
public Object[] toArray(){
public Object[] toArray() {
List list = new ArrayList();
IndexItem item = container.getInternalList().getRoot();
while ((item = container.getInternalList().getNextEntry(item)) != null) {
@ -54,7 +52,7 @@ public class ContainerKeySet extends ContainerCollectionSupport implements Set{
return list.toArray();
}
public Object[] toArray(Object[] a){
public Object[] toArray(Object[] a) {
List list = new ArrayList();
IndexItem item = container.getInternalList().getRoot();
while ((item = container.getInternalList().getNextEntry(item)) != null) {
@ -63,58 +61,58 @@ public class ContainerKeySet extends ContainerCollectionSupport implements Set{
return list.toArray(a);
}
public boolean add(Object o){
public boolean add(Object o) {
throw new UnsupportedOperationException("Cannot add here");
}
public boolean remove(Object o){
return container.remove(o) != null;
public boolean remove(Object o) {
return container.remove(o) != null;
}
public boolean containsAll(Collection c){
public boolean containsAll(Collection c) {
boolean result = true;
for (Object key:c) {
if (!(result&=container.containsKey(key))) {
for (Object key : c) {
if (!(result &= container.containsKey(key))) {
break;
}
}
return result;
return result;
}
public boolean addAll(Collection c){
public boolean addAll(Collection c) {
throw new UnsupportedOperationException("Cannot add here");
}
public boolean retainAll(Collection c){
public boolean retainAll(Collection c) {
List tmpList = new ArrayList();
for (Iterator i = c.iterator(); i.hasNext(); ){
for (Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();
if (!contains(o)){
if (!contains(o)) {
tmpList.add(o);
}
}
}
for(Iterator i = tmpList.iterator(); i.hasNext();){
for (Iterator i = tmpList.iterator(); i.hasNext();) {
remove(i.next());
}
return !tmpList.isEmpty();
}
public boolean removeAll(Collection c){
public boolean removeAll(Collection c) {
boolean result = true;
for (Iterator i = c.iterator(); i.hasNext(); ){
if (!remove(i.next())){
for (Iterator i = c.iterator(); i.hasNext();) {
if (!remove(i.next())) {
result = false;
}
}
return result;
}
public void clear(){
container.clear();
public void clear() {
container.clear();
}
public String toString() {
StringBuffer result =new StringBuffer(32);
StringBuffer result = new StringBuffer(32);
result.append("ContainerKeySet[");
IndexItem item = container.getInternalList().getRoot();
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.IndexLinkedList;
/**
*Iterator for the set of keys for a container
*
* @version $Revision: 1.2 $
*/
public class ContainerKeySetIterator implements Iterator{
* Iterator for the set of keys for a container
*
* @version $Revision: 1.2 $
*/
public class ContainerKeySetIterator implements Iterator {
private MapContainerImpl container;
private IndexLinkedList list;
protected IndexItem nextItem;
protected IndexItem currentItem;
ContainerKeySetIterator(MapContainerImpl container){
ContainerKeySetIterator(MapContainerImpl container) {
this.container = container;
this.list=container.getInternalList();
this.currentItem=list.getRoot();
this.nextItem=list.getNextEntry(currentItem);
}
public boolean hasNext(){
return nextItem!=null;
this.list = container.getInternalList();
this.currentItem = list.getRoot();
this.nextItem = list.getNextEntry(currentItem);
}
public Object next(){
currentItem=nextItem;
Object result=container.getKey(nextItem);
nextItem=list.getNextEntry(nextItem);
public boolean hasNext() {
return nextItem != null;
}
public Object next() {
currentItem = nextItem;
Object result = container.getKey(nextItem);
nextItem = list.getNextEntry(nextItem);
return result;
}
public void remove(){
if(currentItem!=null){
public void remove() {
if (currentItem != null) {
container.remove(currentItem);
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -18,27 +18,27 @@ package org.apache.activemq.kaha.impl.data;
import org.apache.activemq.kaha.StoreLocation;
/**
* A a wrapper for a data in the store
*
* @version $Revision: 1.2 $
*/
public final class DataItem implements Item, StoreLocation{
private int file=(int) POSITION_NOT_SET;
private long offset=POSITION_NOT_SET;
public final class DataItem implements Item, StoreLocation {
private int file = (int)POSITION_NOT_SET;
private long offset = POSITION_NOT_SET;
private int size;
public DataItem(){}
public DataItem() {
}
DataItem(DataItem item) {
this.file = item.file;
this.offset = item.offset;
this.size = item.size;
}
boolean isValid(){
boolean isValid() {
return file != POSITION_NOT_SET;
}
@ -46,52 +46,52 @@ public final class DataItem implements Item, StoreLocation{
* @return
* @see org.apache.activemq.kaha.StoreLocation#getSize()
*/
public int getSize(){
public int getSize() {
return size;
}
/**
* @param size The size to set.
*/
public void setSize(int size){
this.size=size;
public void setSize(int size) {
this.size = size;
}
/**
* @return
* @see org.apache.activemq.kaha.StoreLocation#getOffset()
*/
public long getOffset(){
public long getOffset() {
return offset;
}
/**
* @param offset The offset to set.
*/
public void setOffset(long offset){
this.offset=offset;
public void setOffset(long offset) {
this.offset = offset;
}
/**
* @return
* @see org.apache.activemq.kaha.StoreLocation#getFile()
*/
public int getFile(){
public int getFile() {
return file;
}
/**
* @param file The file to set.
*/
public void setFile(int file){
this.file=file;
public void setFile(int file) {
this.file = file;
}
/**
* @return a pretty print
*/
public String toString(){
String result="offset = "+offset+", file = " + file + ", size = "+size;
public String toString() {
String result = "offset = " + offset + ", file = " + file + ", size = " + size;
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.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Manages DataFiles
*
* @version $Revision: 1.1.1.1 $
*/
public final class DataManagerImpl implements DataManager {
private static final Log log=LogFactory.getLog(DataManagerImpl.class);
public static final long MAX_FILE_LENGTH=1024*1024*32;
private static final String NAME_PREFIX="data-";
private static final Log log = LogFactory.getLog(DataManagerImpl.class);
public static final long MAX_FILE_LENGTH = 1024 * 1024 * 32;
private static final String NAME_PREFIX = "data-";
private final File directory;
private final String name;
private SyncDataFileReader reader;
private SyncDataFileWriter writer;
private DataFile currentWriteFile;
private long maxFileLength = MAX_FILE_LENGTH;
Map fileMap=new HashMap();
public static final int ITEM_HEAD_SIZE=5; // type + length
public static final byte DATA_ITEM_TYPE=1;
public static final byte REDO_ITEM_TYPE=2;
Map fileMap = new HashMap();
public static final int ITEM_HEAD_SIZE = 5; // type + length
public static final byte DATA_ITEM_TYPE = 1;
public static final byte REDO_ITEM_TYPE = 2;
Marshaller redoMarshaller = RedoStoreIndexItem.MARSHALLER;
private String dataFilePrefix;
public DataManagerImpl(File dir, final String name){
this.directory=dir;
this.name=name;
dataFilePrefix = NAME_PREFIX+name+"-";
public DataManagerImpl(File dir, final String name) {
this.directory = dir;
this.name = name;
dataFilePrefix = NAME_PREFIX + name + "-";
// build up list of current dataFiles
File[] files=dir.listFiles(new FilenameFilter(){
public boolean accept(File dir,String n){
return dir.equals(directory)&&n.startsWith(dataFilePrefix);
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String n) {
return dir.equals(directory) && n.startsWith(dataFilePrefix);
}
});
if(files!=null){
for(int i=0;i<files.length;i++){
File file=files[i];
String n=file.getName();
String numStr=n.substring(dataFilePrefix.length(),n.length());
int num=Integer.parseInt(numStr);
DataFile dataFile=new DataFile(file,num);
fileMap.put(dataFile.getNumber(),dataFile);
if(currentWriteFile==null||currentWriteFile.getNumber().intValue()<num){
currentWriteFile=dataFile;
if (files != null) {
for (int i = 0; i < files.length; i++) {
File file = files[i];
String n = file.getName();
String numStr = n.substring(dataFilePrefix.length(), n.length());
int num = Integer.parseInt(numStr);
DataFile dataFile = new DataFile(file, num);
fileMap.put(dataFile.getNumber(), dataFile);
if (currentWriteFile == null || currentWriteFile.getNumber().intValue() < num) {
currentWriteFile = dataFile;
}
}
}
}
private DataFile createAndAddDataFile(int num){
String fileName=dataFilePrefix+num;
File file=new File(directory,fileName);
DataFile result=new DataFile(file,num);
fileMap.put(result.getNumber(),result);
private DataFile createAndAddDataFile(int num) {
String fileName = dataFilePrefix + num;
File file = new File(directory, fileName);
DataFile result = new DataFile(file, num);
fileMap.put(result.getNumber(), result);
return result;
}
/* (non-Javadoc)
* @see org.apache.activemq.kaha.impl.data.IDataManager#getName()
*/
public String getName(){
/*
* (non-Javadoc)
*
* @see org.apache.activemq.kaha.impl.data.IDataManager#getName()
*/
public String getName() {
return name;
}
synchronized DataFile findSpaceForData(DataItem item) throws IOException{
if(currentWriteFile==null||((currentWriteFile.getLength()+item.getSize())>maxFileLength)){
int nextNum=currentWriteFile!=null?currentWriteFile.getNumber().intValue()+1:1;
if(currentWriteFile!=null&&currentWriteFile.isUnused()){
synchronized DataFile findSpaceForData(DataItem item) throws IOException {
if (currentWriteFile == null || ((currentWriteFile.getLength() + item.getSize()) > maxFileLength)) {
int nextNum = currentWriteFile != null ? currentWriteFile.getNumber().intValue() + 1 : 1;
if (currentWriteFile != null && currentWriteFile.isUnused()) {
removeDataFile(currentWriteFile);
}
currentWriteFile=createAndAddDataFile(nextNum);
currentWriteFile = createAndAddDataFile(nextNum);
}
item.setOffset(currentWriteFile.getLength());
item.setFile(currentWriteFile.getNumber().intValue());
currentWriteFile.incrementLength(item.getSize()+ITEM_HEAD_SIZE);
item.setFile(currentWriteFile.getNumber().intValue());
currentWriteFile.incrementLength(item.getSize() + ITEM_HEAD_SIZE);
return currentWriteFile;
}
DataFile getDataFile(StoreLocation item) throws IOException{
Integer key=Integer.valueOf(item.getFile());
DataFile dataFile=(DataFile) fileMap.get(key);
if(dataFile==null){
DataFile getDataFile(StoreLocation item) throws IOException {
Integer key = Integer.valueOf(item.getFile());
DataFile dataFile = (DataFile)fileMap.get(key);
if (dataFile == null) {
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;
}
/* (non-Javadoc)
* @see org.apache.activemq.kaha.impl.data.IDataManager#readItem(org.apache.activemq.kaha.Marshaller, 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#readItem(org.apache.activemq.kaha.Marshaller,
* 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)
*/
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#storeDataItem(org.apache.activemq.kaha.Marshaller,
* 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)
*/
public synchronized StoreLocation storeRedoItem(Object payload) throws IOException{
/*
* (non-Javadoc)
*
* @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);
}
/* (non-Javadoc)
* @see org.apache.activemq.kaha.impl.data.IDataManager#updateItem(org.apache.activemq.kaha.StoreLocation, 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#updateItem(org.apache.activemq.kaha.StoreLocation,
* 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)
*/
public synchronized void recoverRedoItems(RedoListener listener) throws IOException{
/*
* (non-Javadoc)
*
* @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.
if( currentWriteFile == null )
if (currentWriteFile == null)
return;
DataItem item = new DataItem();
item.setFile(currentWriteFile.getNumber().intValue());
item.setOffset(0);
while( true ) {
while (true) {
byte type;
try {
type = getReader().readDataItemSize(item);
} 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;
}
if( type == REDO_ITEM_TYPE ) {
if (type == REDO_ITEM_TYPE) {
// Un-marshal the redo item
Object object;
try {
object = readItem(redoMarshaller, item);
} 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;
}
try {
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.
item = item.copy();
} catch (Exception e) {
throw IOExceptionSupport.create("Recovery handler failed: "+e,e);
throw IOExceptionSupport.create("Recovery handler failed: " + e, e);
}
}
// 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()
*/
public synchronized void close() throws IOException{
getWriter().close();
for(Iterator i=fileMap.values().iterator();i.hasNext();){
DataFile dataFile=(DataFile) i.next();
/*
* (non-Javadoc)
*
* @see org.apache.activemq.kaha.impl.data.IDataManager#close()
*/
public synchronized void close() throws IOException {
getWriter().close();
for (Iterator i = fileMap.values().iterator(); i.hasNext();) {
DataFile dataFile = (DataFile)i.next();
getWriter().force(dataFile);
dataFile.close();
}
fileMap.clear();
}
/* (non-Javadoc)
* @see org.apache.activemq.kaha.impl.data.IDataManager#force()
*/
public synchronized void force() throws IOException{
for(Iterator i=fileMap.values().iterator();i.hasNext();){
DataFile dataFile=(DataFile) i.next();
/*
* (non-Javadoc)
*
* @see org.apache.activemq.kaha.impl.data.IDataManager#force()
*/
public synchronized void force() throws IOException {
for (Iterator i = fileMap.values().iterator(); i.hasNext();) {
DataFile dataFile = (DataFile)i.next();
getWriter().force(dataFile);
}
}
/* (non-Javadoc)
* @see org.apache.activemq.kaha.impl.data.IDataManager#delete()
*/
public synchronized boolean delete() throws IOException{
boolean result=true;
for(Iterator i=fileMap.values().iterator();i.hasNext();){
DataFile dataFile=(DataFile) i.next();
result&=dataFile.delete();
/*
* (non-Javadoc)
*
* @see org.apache.activemq.kaha.impl.data.IDataManager#delete()
*/
public synchronized boolean delete() throws IOException {
boolean result = true;
for (Iterator i = fileMap.values().iterator(); i.hasNext();) {
DataFile dataFile = (DataFile)i.next();
result &= dataFile.delete();
}
fileMap.clear();
return result;
}
/* (non-Javadoc)
* @see org.apache.activemq.kaha.impl.data.IDataManager#addInterestInFile(int)
*/
public synchronized void addInterestInFile(int file) throws IOException{
if(file>=0){
Integer key=Integer.valueOf(file);
DataFile dataFile=(DataFile) fileMap.get(key);
if(dataFile==null){
dataFile=createAndAddDataFile(file);
/*
* (non-Javadoc)
*
* @see org.apache.activemq.kaha.impl.data.IDataManager#addInterestInFile(int)
*/
public synchronized void addInterestInFile(int file) throws IOException {
if (file >= 0) {
Integer key = Integer.valueOf(file);
DataFile dataFile = (DataFile)fileMap.get(key);
if (dataFile == null) {
dataFile = createAndAddDataFile(file);
}
addInterestInFile(dataFile);
}
}
synchronized void addInterestInFile(DataFile dataFile){
if(dataFile!=null){
synchronized void addInterestInFile(DataFile dataFile) {
if (dataFile != null) {
dataFile.increment();
}
}
/* (non-Javadoc)
* @see org.apache.activemq.kaha.impl.data.IDataManager#removeInterestInFile(int)
*/
public synchronized void removeInterestInFile(int file) throws IOException{
if(file>=0){
Integer key=Integer.valueOf(file);
DataFile dataFile=(DataFile) fileMap.get(key);
/*
* (non-Javadoc)
*
* @see org.apache.activemq.kaha.impl.data.IDataManager#removeInterestInFile(int)
*/
public synchronized void removeInterestInFile(int file) throws IOException {
if (file >= 0) {
Integer key = Integer.valueOf(file);
DataFile dataFile = (DataFile)fileMap.get(key);
removeInterestInFile(dataFile);
}
}
synchronized void removeInterestInFile(DataFile dataFile) throws IOException{
if(dataFile!=null){
if(dataFile.decrement()<=0){
if(dataFile!=currentWriteFile){
synchronized void removeInterestInFile(DataFile dataFile) throws IOException {
if (dataFile != null) {
if (dataFile.decrement() <= 0) {
if (dataFile != currentWriteFile) {
removeDataFile(dataFile);
}
}
}
}
/* (non-Javadoc)
* @see org.apache.activemq.kaha.impl.data.IDataManager#consolidateDataFiles()
*/
public synchronized void consolidateDataFiles() throws IOException{
List purgeList=new ArrayList();
for(Iterator i=fileMap.values().iterator();i.hasNext();){
DataFile dataFile=(DataFile) i.next();
if(dataFile.isUnused() && dataFile != currentWriteFile){
/*
* (non-Javadoc)
*
* @see org.apache.activemq.kaha.impl.data.IDataManager#consolidateDataFiles()
*/
public synchronized void consolidateDataFiles() throws IOException {
List purgeList = new ArrayList();
for (Iterator i = fileMap.values().iterator(); i.hasNext();) {
DataFile dataFile = (DataFile)i.next();
if (dataFile.isUnused() && dataFile != currentWriteFile) {
purgeList.add(dataFile);
}
}
for(int i=0;i<purgeList.size();i++){
DataFile dataFile=(DataFile) purgeList.get(i);
for (int i = 0; i < purgeList.size(); i++) {
DataFile dataFile = (DataFile)purgeList.get(i);
removeDataFile(dataFile);
}
}
private void removeDataFile(DataFile dataFile) throws IOException{
private void removeDataFile(DataFile dataFile) throws IOException {
fileMap.remove(dataFile.getNumber());
if(writer!=null){
if (writer != null) {
writer.force(dataFile);
}
boolean result=dataFile.delete();
log.debug("discarding data file "+dataFile+(result?"successful ":"failed"));
boolean result = dataFile.delete();
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() {
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) {
this.redoMarshaller = redoMarshaller;
}
@ -317,45 +349,49 @@ public final class DataManagerImpl implements DataManager {
/**
* @return the maxFileLength
*/
public long getMaxFileLength(){
public long getMaxFileLength() {
return maxFileLength;
}
/**
* @param maxFileLength the maxFileLength to set
*/
public void setMaxFileLength(long maxFileLength){
this.maxFileLength=maxFileLength;
}
public String toString(){
return "DataManager:("+NAME_PREFIX+name+")";
public void setMaxFileLength(long maxFileLength) {
this.maxFileLength = maxFileLength;
}
public synchronized SyncDataFileReader getReader() {
if( reader == null ) {
reader = createReader();
}
return reader;
}
protected synchronized SyncDataFileReader createReader() {
return new SyncDataFileReader(this);
}
public synchronized void setReader(SyncDataFileReader reader) {
this.reader = reader;
}
public String toString() {
return "DataManager:(" + NAME_PREFIX + name + ")";
}
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;
}
public synchronized SyncDataFileReader getReader() {
if (reader == null) {
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() {
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