You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@activemq.apache.org by gt...@apache.org on 2013/10/01 00:10:19 UTC
[1/6] https://issues.apache.org/jira/browse/AMQ-4757
activemq-jms-pool a generic jms xa pool derived from activemq-pool which
activemq-pool now extends with amq specifics
Updated Branches:
refs/heads/trunk 6b9662440 -> b66559ee0
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index ac3f6cd..64804c8 100755
--- a/pom.xml
+++ b/pom.xml
@@ -241,6 +241,7 @@
<module>activemq-jaas</module>
<module>activemq-karaf</module>
<module>activemq-openwire-generator</module>
+ <module>activemq-jms-pool</module>
<module>activemq-pool</module>
<module>activemq-ra</module>
<module>activemq-rar</module>
@@ -366,6 +367,11 @@
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
+ <artifactId>activemq-jms-pool</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
<version>${project.version}</version>
</dependency>
[5/6] https://issues.apache.org/jira/browse/AMQ-4757
activemq-jms-pool a generic jms xa pool derived from activemq-pool which
activemq-pool now extends with amq specifics
Posted by gt...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledProducer.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledProducer.java b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledProducer.java
new file mode 100644
index 0000000..817a1f1
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledProducer.java
@@ -0,0 +1,146 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import javax.jms.Destination;
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageProducer;
+
+/**
+ * A pooled {@link MessageProducer}
+ */
+public class PooledProducer implements MessageProducer {
+
+ private final MessageProducer messageProducer;
+ private final Destination destination;
+
+ private int deliveryMode;
+ private boolean disableMessageID;
+ private boolean disableMessageTimestamp;
+ private int priority;
+ private long timeToLive;
+
+ public PooledProducer(MessageProducer messageProducer, Destination destination) throws JMSException {
+ this.messageProducer = messageProducer;
+ this.destination = destination;
+
+ this.deliveryMode = messageProducer.getDeliveryMode();
+ this.disableMessageID = messageProducer.getDisableMessageID();
+ this.disableMessageTimestamp = messageProducer.getDisableMessageTimestamp();
+ this.priority = messageProducer.getPriority();
+ this.timeToLive = messageProducer.getTimeToLive();
+ }
+
+ @Override
+ public void close() throws JMSException {
+ }
+
+ @Override
+ public void send(Destination destination, Message message) throws JMSException {
+ send(destination, message, getDeliveryMode(), getPriority(), getTimeToLive());
+ }
+
+ @Override
+ public void send(Message message) throws JMSException {
+ send(destination, message, getDeliveryMode(), getPriority(), getTimeToLive());
+ }
+
+ @Override
+ public void send(Message message, int deliveryMode, int priority, long timeToLive) throws JMSException {
+ send(destination, message, deliveryMode, priority, timeToLive);
+ }
+
+ @Override
+ public void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive) throws JMSException {
+ if (destination == null) {
+ destination = this.destination;
+ }
+ MessageProducer messageProducer = getMessageProducer();
+
+ // just in case let only one thread send at once
+ synchronized (messageProducer) {
+ messageProducer.send(destination, message, deliveryMode, priority, timeToLive);
+ }
+ }
+
+ @Override
+ public Destination getDestination() {
+ return destination;
+ }
+
+ @Override
+ public int getDeliveryMode() {
+ return deliveryMode;
+ }
+
+ @Override
+ public void setDeliveryMode(int deliveryMode) {
+ this.deliveryMode = deliveryMode;
+ }
+
+ @Override
+ public boolean getDisableMessageID() {
+ return disableMessageID;
+ }
+
+ @Override
+ public void setDisableMessageID(boolean disableMessageID) {
+ this.disableMessageID = disableMessageID;
+ }
+
+ @Override
+ public boolean getDisableMessageTimestamp() {
+ return disableMessageTimestamp;
+ }
+
+ @Override
+ public void setDisableMessageTimestamp(boolean disableMessageTimestamp) {
+ this.disableMessageTimestamp = disableMessageTimestamp;
+ }
+
+ @Override
+ public int getPriority() {
+ return priority;
+ }
+
+ @Override
+ public void setPriority(int priority) {
+ this.priority = priority;
+ }
+
+ @Override
+ public long getTimeToLive() {
+ return timeToLive;
+ }
+
+ @Override
+ public void setTimeToLive(long timeToLive) {
+ this.timeToLive = timeToLive;
+ }
+
+ // Implementation methods
+ // -------------------------------------------------------------------------
+ protected MessageProducer getMessageProducer() {
+ return messageProducer;
+ }
+
+ @Override
+ public String toString() {
+ return "PooledProducer { " + messageProducer + " }";
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledQueueSender.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledQueueSender.java b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledQueueSender.java
new file mode 100644
index 0000000..62f9d81
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledQueueSender.java
@@ -0,0 +1,52 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import javax.jms.Destination;
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.Queue;
+import javax.jms.QueueSender;
+
+/**
+ * {@link QueueSender} instance that is created and managed by the PooledConnection.
+ */
+public class PooledQueueSender extends PooledProducer implements QueueSender {
+
+ public PooledQueueSender(QueueSender messageProducer, Destination destination) throws JMSException {
+ super(messageProducer, destination);
+ }
+
+ @Override
+ public void send(Queue queue, Message message, int i, int i1, long l) throws JMSException {
+ getQueueSender().send(queue, message, i, i1, l);
+ }
+
+ @Override
+ public void send(Queue queue, Message message) throws JMSException {
+ getQueueSender().send(queue, message);
+ }
+
+ @Override
+ public Queue getQueue() throws JMSException {
+ return (Queue) getDestination();
+ }
+
+ protected QueueSender getQueueSender() {
+ return (QueueSender) getMessageProducer();
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledSession.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledSession.java b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledSession.java
new file mode 100644
index 0000000..d0e4a09
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledSession.java
@@ -0,0 +1,445 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import java.io.Serializable;
+import java.util.Iterator;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import javax.jms.BytesMessage;
+import javax.jms.Destination;
+import javax.jms.JMSException;
+import javax.jms.MapMessage;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+import javax.jms.MessageProducer;
+import javax.jms.ObjectMessage;
+import javax.jms.Queue;
+import javax.jms.QueueBrowser;
+import javax.jms.QueueReceiver;
+import javax.jms.QueueSender;
+import javax.jms.QueueSession;
+import javax.jms.Session;
+import javax.jms.StreamMessage;
+import javax.jms.TemporaryQueue;
+import javax.jms.TemporaryTopic;
+import javax.jms.TextMessage;
+import javax.jms.Topic;
+import javax.jms.TopicPublisher;
+import javax.jms.TopicSession;
+import javax.jms.TopicSubscriber;
+import javax.jms.XASession;
+import javax.transaction.xa.XAResource;
+
+import org.apache.commons.pool.KeyedObjectPool;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class PooledSession implements Session, TopicSession, QueueSession, XASession {
+ private static final transient Logger LOG = LoggerFactory.getLogger(PooledSession.class);
+
+ private final SessionKey key;
+ private final KeyedObjectPool<SessionKey, PooledSession> sessionPool;
+ private final CopyOnWriteArrayList<MessageConsumer> consumers = new CopyOnWriteArrayList<MessageConsumer>();
+ private final CopyOnWriteArrayList<QueueBrowser> browsers = new CopyOnWriteArrayList<QueueBrowser>();
+ private final CopyOnWriteArrayList<PooledSessionEventListener> sessionEventListeners =
+ new CopyOnWriteArrayList<PooledSessionEventListener>();
+
+ private Session session;
+ private MessageProducer messageProducer;
+ private QueueSender queueSender;
+ private TopicPublisher topicPublisher;
+ private boolean transactional = true;
+ private boolean ignoreClose;
+ private boolean isXa;
+
+ public PooledSession(SessionKey key, Session session, KeyedObjectPool<SessionKey, PooledSession> sessionPool, boolean transactional) {
+ this.key = key;
+ this.session = session;
+ this.sessionPool = sessionPool;
+ this.transactional = transactional;
+ }
+
+ public void addSessionEventListener(PooledSessionEventListener listener) {
+ // only add if really needed
+ if (!sessionEventListeners.contains(listener)) {
+ this.sessionEventListeners.add(listener);
+ }
+ }
+
+ protected boolean isIgnoreClose() {
+ return ignoreClose;
+ }
+
+ protected void setIgnoreClose(boolean ignoreClose) {
+ this.ignoreClose = ignoreClose;
+ }
+
+ @Override
+ public void close() throws JMSException {
+ if (!ignoreClose) {
+ boolean invalidate = false;
+ try {
+ // lets reset the session
+ getInternalSession().setMessageListener(null);
+
+ // Close any consumers and browsers that may have been created.
+ for (Iterator<MessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
+ MessageConsumer consumer = iter.next();
+ consumer.close();
+ }
+
+ for (Iterator<QueueBrowser> iter = browsers.iterator(); iter.hasNext();) {
+ QueueBrowser browser = iter.next();
+ browser.close();
+ }
+
+ if (transactional && !isXa) {
+ try {
+ getInternalSession().rollback();
+ } catch (JMSException e) {
+ invalidate = true;
+ LOG.warn("Caught exception trying rollback() when putting session back into the pool, will invalidate. " + e, e);
+ }
+ }
+ } catch (JMSException ex) {
+ invalidate = true;
+ LOG.warn("Caught exception trying close() when putting session back into the pool, will invalidate. " + ex, ex);
+ } finally {
+ consumers.clear();
+ browsers.clear();
+ for (PooledSessionEventListener listener : this.sessionEventListeners) {
+ listener.onSessionClosed(this);
+ }
+ sessionEventListeners.clear();
+ }
+
+ if (invalidate) {
+ // lets close the session and not put the session back into the pool
+ // instead invalidate it so the pool can create a new one on demand.
+ if (session != null) {
+ try {
+ session.close();
+ } catch (JMSException e1) {
+ LOG.trace("Ignoring exception on close as discarding session: " + e1, e1);
+ }
+ session = null;
+ }
+ try {
+ sessionPool.invalidateObject(key, this);
+ } catch (Exception e) {
+ LOG.trace("Ignoring exception on invalidateObject as discarding session: " + e, e);
+ }
+ } else {
+ try {
+ sessionPool.returnObject(key, this);
+ } catch (Exception e) {
+ javax.jms.IllegalStateException illegalStateException = new javax.jms.IllegalStateException(e.toString());
+ illegalStateException.initCause(e);
+ throw illegalStateException;
+ }
+ }
+ }
+ }
+
+ @Override
+ public void commit() throws JMSException {
+ getInternalSession().commit();
+ }
+
+ @Override
+ public BytesMessage createBytesMessage() throws JMSException {
+ return getInternalSession().createBytesMessage();
+ }
+
+ @Override
+ public MapMessage createMapMessage() throws JMSException {
+ return getInternalSession().createMapMessage();
+ }
+
+ @Override
+ public Message createMessage() throws JMSException {
+ return getInternalSession().createMessage();
+ }
+
+ @Override
+ public ObjectMessage createObjectMessage() throws JMSException {
+ return getInternalSession().createObjectMessage();
+ }
+
+ @Override
+ public ObjectMessage createObjectMessage(Serializable serializable) throws JMSException {
+ return getInternalSession().createObjectMessage(serializable);
+ }
+
+ @Override
+ public Queue createQueue(String s) throws JMSException {
+ return getInternalSession().createQueue(s);
+ }
+
+ @Override
+ public StreamMessage createStreamMessage() throws JMSException {
+ return getInternalSession().createStreamMessage();
+ }
+
+ @Override
+ public TemporaryQueue createTemporaryQueue() throws JMSException {
+ TemporaryQueue result;
+
+ result = getInternalSession().createTemporaryQueue();
+
+ // Notify all of the listeners of the created temporary Queue.
+ for (PooledSessionEventListener listener : this.sessionEventListeners) {
+ listener.onTemporaryQueueCreate(result);
+ }
+
+ return result;
+ }
+
+ @Override
+ public TemporaryTopic createTemporaryTopic() throws JMSException {
+ TemporaryTopic result;
+
+ result = getInternalSession().createTemporaryTopic();
+
+ // Notify all of the listeners of the created temporary Topic.
+ for (PooledSessionEventListener listener : this.sessionEventListeners) {
+ listener.onTemporaryTopicCreate(result);
+ }
+
+ return result;
+ }
+
+ @Override
+ public void unsubscribe(String s) throws JMSException {
+ getInternalSession().unsubscribe(s);
+ }
+
+ @Override
+ public TextMessage createTextMessage() throws JMSException {
+ return getInternalSession().createTextMessage();
+ }
+
+ @Override
+ public TextMessage createTextMessage(String s) throws JMSException {
+ return getInternalSession().createTextMessage(s);
+ }
+
+ @Override
+ public Topic createTopic(String s) throws JMSException {
+ return getInternalSession().createTopic(s);
+ }
+
+ @Override
+ public int getAcknowledgeMode() throws JMSException {
+ return getInternalSession().getAcknowledgeMode();
+ }
+
+ @Override
+ public boolean getTransacted() throws JMSException {
+ return getInternalSession().getTransacted();
+ }
+
+ @Override
+ public void recover() throws JMSException {
+ getInternalSession().recover();
+ }
+
+ @Override
+ public void rollback() throws JMSException {
+ getInternalSession().rollback();
+ }
+
+ @Override
+ public XAResource getXAResource() {
+ if (session instanceof XASession) {
+ return ((XASession)session).getXAResource();
+ }
+ return null;
+ }
+
+ @Override
+ public Session getSession() {
+ return this;
+ }
+
+ @Override
+ public void run() {
+ if (session != null) {
+ session.run();
+ }
+ }
+
+ // Consumer related methods
+ // -------------------------------------------------------------------------
+ @Override
+ public QueueBrowser createBrowser(Queue queue) throws JMSException {
+ return addQueueBrowser(getInternalSession().createBrowser(queue));
+ }
+
+ @Override
+ public QueueBrowser createBrowser(Queue queue, String selector) throws JMSException {
+ return addQueueBrowser(getInternalSession().createBrowser(queue, selector));
+ }
+
+ @Override
+ public MessageConsumer createConsumer(Destination destination) throws JMSException {
+ return addConsumer(getInternalSession().createConsumer(destination));
+ }
+
+ @Override
+ public MessageConsumer createConsumer(Destination destination, String selector) throws JMSException {
+ return addConsumer(getInternalSession().createConsumer(destination, selector));
+ }
+
+ @Override
+ public MessageConsumer createConsumer(Destination destination, String selector, boolean noLocal) throws JMSException {
+ return addConsumer(getInternalSession().createConsumer(destination, selector, noLocal));
+ }
+
+ @Override
+ public TopicSubscriber createDurableSubscriber(Topic topic, String selector) throws JMSException {
+ return addTopicSubscriber(getInternalSession().createDurableSubscriber(topic, selector));
+ }
+
+ @Override
+ public TopicSubscriber createDurableSubscriber(Topic topic, String name, String selector, boolean noLocal) throws JMSException {
+ return addTopicSubscriber(getInternalSession().createDurableSubscriber(topic, name, selector, noLocal));
+ }
+
+ @Override
+ public MessageListener getMessageListener() throws JMSException {
+ return getInternalSession().getMessageListener();
+ }
+
+ @Override
+ public void setMessageListener(MessageListener messageListener) throws JMSException {
+ getInternalSession().setMessageListener(messageListener);
+ }
+
+ @Override
+ public TopicSubscriber createSubscriber(Topic topic) throws JMSException {
+ return addTopicSubscriber(((TopicSession)getInternalSession()).createSubscriber(topic));
+ }
+
+ @Override
+ public TopicSubscriber createSubscriber(Topic topic, String selector, boolean local) throws JMSException {
+ return addTopicSubscriber(((TopicSession)getInternalSession()).createSubscriber(topic, selector, local));
+ }
+
+ @Override
+ public QueueReceiver createReceiver(Queue queue) throws JMSException {
+ return addQueueReceiver(((QueueSession)getInternalSession()).createReceiver(queue));
+ }
+
+ @Override
+ public QueueReceiver createReceiver(Queue queue, String selector) throws JMSException {
+ return addQueueReceiver(((QueueSession)getInternalSession()).createReceiver(queue, selector));
+ }
+
+ // Producer related methods
+ // -------------------------------------------------------------------------
+ @Override
+ public MessageProducer createProducer(Destination destination) throws JMSException {
+ return new PooledProducer(getMessageProducer(), destination);
+ }
+
+ @Override
+ public QueueSender createSender(Queue queue) throws JMSException {
+ return new PooledQueueSender(getQueueSender(), queue);
+ }
+
+ @Override
+ public TopicPublisher createPublisher(Topic topic) throws JMSException {
+ return new PooledTopicPublisher(getTopicPublisher(), topic);
+ }
+
+ /**
+ * Callback invoked when the consumer is closed.
+ * <p/>
+ * This is used to keep track of an explicit closed consumer created by this
+ * session, by which we know do not need to keep track of the consumer, as
+ * its already closed.
+ *
+ * @param consumer
+ * the consumer which is being closed
+ */
+ protected void onConsumerClose(MessageConsumer consumer) {
+ consumers.remove(consumer);
+ }
+
+ public Session getInternalSession() throws IllegalStateException {
+ if (session == null) {
+ throw new IllegalStateException("The session has already been closed");
+ }
+ return session;
+ }
+
+ public MessageProducer getMessageProducer() throws JMSException {
+ if (messageProducer == null) {
+ messageProducer = getInternalSession().createProducer(null);
+ }
+ return messageProducer;
+ }
+
+ public QueueSender getQueueSender() throws JMSException {
+ if (queueSender == null) {
+ queueSender = ((QueueSession)getInternalSession()).createSender(null);
+ }
+ return queueSender;
+ }
+
+ public TopicPublisher getTopicPublisher() throws JMSException {
+ if (topicPublisher == null) {
+ topicPublisher = ((TopicSession)getInternalSession()).createPublisher(null);
+ }
+ return topicPublisher;
+ }
+
+ private QueueBrowser addQueueBrowser(QueueBrowser browser) {
+ browsers.add(browser);
+ return browser;
+ }
+
+ private MessageConsumer addConsumer(MessageConsumer consumer) {
+ consumers.add(consumer);
+ // must wrap in PooledMessageConsumer to ensure the onConsumerClose method is
+ // invoked when the returned consumer is closed, to avoid memory leak in this
+ // session class in case many consumers is created
+ return new PooledMessageConsumer(this, consumer);
+ }
+
+ private TopicSubscriber addTopicSubscriber(TopicSubscriber subscriber) {
+ consumers.add(subscriber);
+ return subscriber;
+ }
+
+ private QueueReceiver addQueueReceiver(QueueReceiver receiver) {
+ consumers.add(receiver);
+ return receiver;
+ }
+
+ public void setIsXa(boolean isXa) {
+ this.isXa = isXa;
+ }
+
+ @Override
+ public String toString() {
+ return "PooledSession { " + session + " }";
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledSessionEventListener.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledSessionEventListener.java b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledSessionEventListener.java
new file mode 100644
index 0000000..e450817
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledSessionEventListener.java
@@ -0,0 +1,49 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.jms.pool;
+
+import javax.jms.TemporaryQueue;
+import javax.jms.TemporaryTopic;
+
+interface PooledSessionEventListener {
+
+ /**
+ * Called on successful creation of a new TemporaryQueue.
+ *
+ * @param tempQueue
+ * The TemporaryQueue just created.
+ */
+ void onTemporaryQueueCreate(TemporaryQueue tempQueue);
+
+ /**
+ * Called on successful creation of a new TemporaryTopic.
+ *
+ * @param tempTopic
+ * The TemporaryTopic just created.
+ */
+ void onTemporaryTopicCreate(TemporaryTopic tempTopic);
+
+ /**
+ * Called when the PooledSession is closed.
+ *
+ * @param session
+ * The PooledSession that has been closed.
+ */
+ void onSessionClosed(PooledSession session);
+
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledTopicPublisher.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledTopicPublisher.java b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledTopicPublisher.java
new file mode 100644
index 0000000..8099e68
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledTopicPublisher.java
@@ -0,0 +1,62 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import javax.jms.Destination;
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.Topic;
+import javax.jms.TopicPublisher;
+
+/**
+ * A {@link TopicPublisher} instance that is created and managed by a PooledConnection.
+ */
+public class PooledTopicPublisher extends PooledProducer implements TopicPublisher {
+
+ public PooledTopicPublisher(TopicPublisher messageProducer, Destination destination) throws JMSException {
+ super(messageProducer, destination);
+ }
+
+ @Override
+ public Topic getTopic() throws JMSException {
+ return (Topic) getDestination();
+ }
+
+ @Override
+ public void publish(Message message) throws JMSException {
+ getTopicPublisher().publish((Topic) getDestination(), message);
+ }
+
+ @Override
+ public void publish(Message message, int i, int i1, long l) throws JMSException {
+ getTopicPublisher().publish((Topic) getDestination(), message, i, i1, l);
+ }
+
+ @Override
+ public void publish(Topic topic, Message message) throws JMSException {
+ getTopicPublisher().publish(topic, message);
+ }
+
+ @Override
+ public void publish(Topic topic, Message message, int i, int i1, long l) throws JMSException {
+ getTopicPublisher().publish(topic, message, i, i1, l);
+ }
+
+ protected TopicPublisher getTopicPublisher() {
+ return (TopicPublisher) getMessageProducer();
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/SessionKey.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/SessionKey.java b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/SessionKey.java
new file mode 100644
index 0000000..3a95693
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/SessionKey.java
@@ -0,0 +1,63 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+/**
+ * A cache key for the session details used to locate PooledSession intances.
+ */
+public class SessionKey {
+
+ private final boolean transacted;
+ private final int ackMode;
+
+ private int hash;
+
+ public SessionKey(boolean transacted, int ackMode) {
+ this.transacted = transacted;
+ this.ackMode = ackMode;
+ hash = ackMode;
+ if (transacted) {
+ hash = 31 * hash + 1;
+ }
+ }
+
+ public int hashCode() {
+ return hash;
+ }
+
+ public boolean equals(Object that) {
+ if (this == that) {
+ return true;
+ }
+ if (that instanceof SessionKey) {
+ return equals((SessionKey) that);
+ }
+ return false;
+ }
+
+ public boolean equals(SessionKey that) {
+ return this.transacted == that.transacted && this.ackMode == that.ackMode;
+ }
+
+ public boolean isTransacted() {
+ return transacted;
+ }
+
+ public int getAckMode() {
+ return ackMode;
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/XaConnectionPool.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/XaConnectionPool.java b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/XaConnectionPool.java
new file mode 100644
index 0000000..f4205c8
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/XaConnectionPool.java
@@ -0,0 +1,115 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import javax.jms.Connection;
+import javax.jms.JMSException;
+import javax.jms.Session;
+import javax.jms.XAConnection;
+import javax.transaction.RollbackException;
+import javax.transaction.Status;
+import javax.transaction.SystemException;
+import javax.transaction.TransactionManager;
+import javax.transaction.xa.XAResource;
+
+/**
+ * An XA-aware connection pool. When a session is created and an xa transaction is active,
+ * the session will automatically be enlisted in the current transaction.
+ *
+ * @author gnodet
+ */
+public class XaConnectionPool extends ConnectionPool {
+
+ private final TransactionManager transactionManager;
+
+ public XaConnectionPool(Connection connection, TransactionManager transactionManager) {
+ super(connection);
+ this.transactionManager = transactionManager;
+ }
+
+ @Override
+ protected Session makeSession(SessionKey key) throws JMSException {
+ return ((XAConnection)connection).createXASession();
+ }
+
+ @Override
+ public Session createSession(boolean transacted, int ackMode) throws JMSException {
+ try {
+ boolean isXa = (transactionManager != null && transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION);
+ if (isXa) {
+ // if the xa tx aborts inflight we don't want to auto create a local transaction or auto ack
+ transacted = false;
+ ackMode = Session.CLIENT_ACKNOWLEDGE;
+ } else if (transactionManager != null) {
+ // cmt or transactionManager managed
+ transacted = false;
+ if (ackMode == Session.SESSION_TRANSACTED) {
+ ackMode = Session.AUTO_ACKNOWLEDGE;
+ }
+ }
+ PooledSession session = (PooledSession) super.createSession(transacted, ackMode);
+ if (isXa) {
+ session.setIgnoreClose(true);
+ session.setIsXa(true);
+ transactionManager.getTransaction().registerSynchronization(new Synchronization(session));
+ incrementReferenceCount();
+ transactionManager.getTransaction().enlistResource(createXaResource(session));
+ } else {
+ session.setIgnoreClose(false);
+ }
+ return session;
+ } catch (RollbackException e) {
+ final JMSException jmsException = new JMSException("Rollback Exception");
+ jmsException.initCause(e);
+ throw jmsException;
+ } catch (SystemException e) {
+ final JMSException jmsException = new JMSException("System Exception");
+ jmsException.initCause(e);
+ throw jmsException;
+ }
+ }
+
+ protected XAResource createXaResource(PooledSession session) throws JMSException {
+ return session.getXAResource();
+ }
+
+ protected class Synchronization implements javax.transaction.Synchronization {
+ private final PooledSession session;
+
+ private Synchronization(PooledSession session) {
+ this.session = session;
+ }
+
+ @Override
+ public void beforeCompletion() {
+ }
+
+ @Override
+ public void afterCompletion(int status) {
+ try {
+ // This will return session to the pool.
+ session.setIgnoreClose(false);
+ session.close();
+ session.setIgnoreClose(true);
+ session.setIsXa(false);
+ decrementReferenceCount();
+ } catch (JMSException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/XaPooledConnectionFactory.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/XaPooledConnectionFactory.java b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/XaPooledConnectionFactory.java
new file mode 100644
index 0000000..0567509
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/XaPooledConnectionFactory.java
@@ -0,0 +1,145 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import java.io.Serializable;
+import java.util.Hashtable;
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.JMSException;
+import javax.jms.QueueConnection;
+import javax.jms.QueueConnectionFactory;
+import javax.jms.TopicConnection;
+import javax.jms.TopicConnectionFactory;
+import javax.jms.XAConnectionFactory;
+import javax.naming.Binding;
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.Name;
+import javax.naming.NamingEnumeration;
+import javax.naming.spi.ObjectFactory;
+import javax.transaction.TransactionManager;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A pooled connection factory that automatically enlists
+ * sessions in the current active XA transaction if any.
+ */
+public class XaPooledConnectionFactory extends PooledConnectionFactory implements ObjectFactory,
+ Serializable, QueueConnectionFactory, TopicConnectionFactory {
+
+ private static final transient Logger LOG = LoggerFactory.getLogger(XaPooledConnectionFactory.class);
+ private TransactionManager transactionManager;
+ private boolean tmFromJndi = false;
+ private String tmJndiName = "java:/TransactionManager";
+
+ public TransactionManager getTransactionManager() {
+ if (transactionManager == null && tmFromJndi) {
+ try {
+ transactionManager = (TransactionManager) new InitialContext().lookup(getTmJndiName());
+ } catch (Throwable ignored) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("exception on tmFromJndi: " + getTmJndiName(), ignored);
+ }
+ }
+ }
+ return transactionManager;
+ }
+
+ public void setTransactionManager(TransactionManager transactionManager) {
+ this.transactionManager = transactionManager;
+ }
+
+ @Override
+ protected ConnectionPool createConnectionPool(Connection connection) {
+ return new XaConnectionPool(connection, getTransactionManager());
+ }
+
+ @Override
+ public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
+ setTmFromJndi(true);
+ configFromJndiConf(obj);
+ if (environment != null) {
+ IntrospectionSupport.setProperties(this, environment);
+ }
+ return this;
+ }
+
+ private void configFromJndiConf(Object rootContextName) {
+ if (rootContextName instanceof String) {
+ String name = (String) rootContextName;
+ name = name.substring(0, name.lastIndexOf('/')) + "/conf" + name.substring(name.lastIndexOf('/'));
+ try {
+ InitialContext ctx = new InitialContext();
+ NamingEnumeration bindings = ctx.listBindings(name);
+
+ while (bindings.hasMore()) {
+ Binding bd = (Binding)bindings.next();
+ IntrospectionSupport.setProperty(this, bd.getName(), bd.getObject());
+ }
+
+ } catch (Exception ignored) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("exception on config from jndi: " + name, ignored);
+ }
+ }
+ }
+ }
+
+ public String getTmJndiName() {
+ return tmJndiName;
+ }
+
+ public void setTmJndiName(String tmJndiName) {
+ this.tmJndiName = tmJndiName;
+ }
+
+ public boolean isTmFromJndi() {
+ return tmFromJndi;
+ }
+
+ /**
+ * Allow transaction manager resolution from JNDI (ee deployment)
+ * @param tmFromJndi
+ */
+ public void setTmFromJndi(boolean tmFromJndi) {
+ this.tmFromJndi = tmFromJndi;
+ }
+
+ @Override
+ public QueueConnection createQueueConnection() throws JMSException {
+ return (QueueConnection) createConnection();
+ }
+
+ @Override
+ public QueueConnection createQueueConnection(String userName, String password) throws JMSException {
+ return (QueueConnection) createConnection(userName, password);
+ }
+
+ @Override
+ public TopicConnection createTopicConnection() throws JMSException {
+ return (TopicConnection) createConnection();
+ }
+
+ @Override
+ public TopicConnection createTopicConnection(String userName, String password) throws JMSException {
+ return (TopicConnection) createConnection(userName, password);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/package.html
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/package.html b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/package.html
new file mode 100755
index 0000000..6cfb281
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/package.html
@@ -0,0 +1,25 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<html>
+<head>
+</head>
+<body>
+
+A JMS provider which pools Connection, Session and MessageProducer instances so it can be used with tools like
+Spring's <a href="http://activemq.org/Spring+Support">JmsTemplate</a>.
+</body>
+</html>
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/ConnectionExpiryEvictsFromPoolTest.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/ConnectionExpiryEvictsFromPoolTest.java b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/ConnectionExpiryEvictsFromPoolTest.java
new file mode 100644
index 0000000..d0eb78f
--- /dev/null
+++ b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/ConnectionExpiryEvictsFromPoolTest.java
@@ -0,0 +1,115 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import java.util.concurrent.TimeUnit;
+
+import javax.jms.Connection;
+import javax.jms.Session;
+
+import org.apache.activemq.ActiveMQConnectionFactory;
+import org.apache.activemq.broker.BrokerService;
+import org.apache.activemq.broker.TransportConnector;
+import org.apache.activemq.test.TestSupport;
+
+public class ConnectionExpiryEvictsFromPoolTest extends TestSupport {
+
+ private BrokerService broker;
+ private ActiveMQConnectionFactory factory;
+ private PooledConnectionFactory pooledFactory;
+
+ @Override
+ protected void setUp() throws Exception {
+ broker = new BrokerService();
+ broker.setUseJmx(false);
+ broker.setPersistent(false);
+ TransportConnector connector = broker.addConnector("tcp://localhost:0");
+ broker.start();
+ factory = new ActiveMQConnectionFactory("mock:" + connector.getConnectUri());
+ pooledFactory = new PooledConnectionFactory();
+ pooledFactory.setConnectionFactory(factory);
+ pooledFactory.setMaxConnections(1);
+ }
+
+ public void testEvictionOfIdle() throws Exception {
+ pooledFactory.setIdleTimeout(10);
+ PooledConnection connection = (PooledConnection) pooledFactory.createConnection();
+ Connection amq1 = connection.getConnection();
+
+ connection.close();
+ // let it idle timeout
+ TimeUnit.SECONDS.sleep(1);
+
+ PooledConnection connection2 = (PooledConnection) pooledFactory.createConnection();
+ Connection amq2 = connection2.getConnection();
+ assertTrue("not equal", !amq1.equals(amq2));
+ }
+
+ public void testEvictionOfExpired() throws Exception {
+ pooledFactory.setExpiryTimeout(10);
+ Connection connection = pooledFactory.createConnection();
+ Connection amq1 = ((PooledConnection) connection).getConnection();
+
+ // let it expire while in use
+ TimeUnit.SECONDS.sleep(1);
+ connection.close();
+
+ Connection connection2 = pooledFactory.createConnection();
+ Connection amq2 = ((PooledConnection) connection2).getConnection();
+ assertTrue("not equal", !amq1.equals(amq2));
+ }
+
+ public void testNotIdledWhenInUse() throws Exception {
+ pooledFactory.setIdleTimeout(10);
+ PooledConnection connection = (PooledConnection) pooledFactory.createConnection();
+ Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+ // let connection to get idle
+ TimeUnit.SECONDS.sleep(1);
+
+ // get a connection from pool again, it should be the same underlying connection
+ // as before and should not be idled out since an open session exists.
+ PooledConnection connection2 = (PooledConnection) pooledFactory.createConnection();
+ assertSame(connection.getConnection(), connection2.getConnection());
+
+ // now the session is closed even when it should not be
+ try {
+ // any operation on session first checks whether session is closed
+ s.getTransacted();
+ } catch (javax.jms.IllegalStateException e) {
+ assertTrue("Session should be fine, instead: " + e.getMessage(), false);
+ }
+
+ Connection original = connection.getConnection();
+
+ connection.close();
+ connection2.close();
+
+ // let connection to get idle
+ TimeUnit.SECONDS.sleep(1);
+
+ // get a connection from pool again, it should be a new Connection instance as the
+ // old one should have been inactive and idled out.
+ PooledConnection connection3 = (PooledConnection) pooledFactory.createConnection();
+ assertNotSame(original, connection3.getConnection());
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ broker.stop();
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionFactoryMaximumActiveTest.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionFactoryMaximumActiveTest.java b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionFactoryMaximumActiveTest.java
new file mode 100644
index 0000000..895b482
--- /dev/null
+++ b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionFactoryMaximumActiveTest.java
@@ -0,0 +1,151 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import javax.jms.Connection;
+import javax.jms.JMSException;
+import javax.jms.Session;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+import org.apache.activemq.ActiveMQConnectionFactory;
+import org.apache.log4j.Logger;
+
+/**
+ * Checks the behavior of the PooledConnectionFactory when the maximum amount of sessions is being reached
+ * (maximumActive). When using setBlockIfSessionPoolIsFull(true) on the ConnectionFactory, further requests for sessions
+ * should block. If it does not block, its a bug.
+ *
+ * @author: tmielke
+ */
+public class PooledConnectionFactoryMaximumActiveTest extends TestCase {
+ public final static Logger LOG = Logger.getLogger(PooledConnectionFactoryMaximumActiveTest.class);
+ public static Connection conn = null;
+ public static int sleepTimeout = 5000;
+
+ private static ConcurrentHashMap<Integer, Session> sessions = new ConcurrentHashMap<Integer, Session>();
+
+ /**
+ * Create the test case
+ *
+ * @param testName
+ * name of the test case
+ */
+ public PooledConnectionFactoryMaximumActiveTest(String testName) {
+ super(testName);
+ }
+
+ public static void addSession(Session s) {
+ sessions.put(s.hashCode(), s);
+ }
+
+ /**
+ * @return the suite of tests being tested
+ */
+ public static Test suite() {
+ return new TestSuite(PooledConnectionFactoryMaximumActiveTest.class);
+ }
+
+ /**
+ * Tests the behavior of the sessionPool of the PooledConnectionFactory when maximum number of sessions are reached.
+ * This test uses maximumActive=1. When creating two threads that both try to create a JMS session from the same JMS
+ * connection, the thread that is second to call createSession() should block (as only 1 session is allowed) until
+ * the session is returned to pool. If it does not block, its a bug.
+ *
+ */
+ public void testApp() throws Exception {
+ // Initialize JMS connection
+ ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory("vm://broker1?marshal=false&broker.persistent=false");
+ PooledConnectionFactory cf = new PooledConnectionFactory();
+ cf.setConnectionFactory(amq);
+ cf.setMaxConnections(3);
+ cf.setMaximumActiveSessionPerConnection(1);
+ cf.setBlockIfSessionPoolIsFull(true);
+ conn = cf.createConnection();
+
+ // start test runner threads. It is expected that the second thread
+ // blocks on the call to createSession()
+
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ executor.submit(new TestRunner2());
+ // Thread.sleep(100);
+ Future<Boolean> result2 = executor.submit(new TestRunner2());
+
+ // sleep to allow threads to run
+ Thread.sleep(sleepTimeout);
+
+ // second task should not have finished, instead wait on getting a
+ // JMS Session
+ assertEquals(false, result2.isDone());
+
+ // Only 1 session should have been created
+ assertEquals(1, sessions.size());
+
+ // Take all threads down
+ executor.shutdownNow();
+ }
+}
+
+class TestRunner2 implements Callable<Boolean> {
+
+ public final static Logger LOG = Logger.getLogger(TestRunner2.class);
+
+ /**
+ * @return true if test succeeded, false otherwise
+ */
+ @Override
+ public Boolean call() {
+
+ Session one = null;
+
+ // wait at most 5 seconds for the call to createSession
+ try {
+
+ if (PooledConnectionFactoryMaximumActiveTest.conn == null) {
+ LOG.error("Connection not yet initialized. Aborting test.");
+ return new Boolean(false);
+ }
+
+ one = PooledConnectionFactoryMaximumActiveTest.conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ LOG.info("Created new Session with id" + one);
+ PooledConnectionFactoryMaximumActiveTest.addSession(one);
+ Thread.sleep(2 * PooledConnectionFactoryMaximumActiveTest.sleepTimeout);
+ } catch (Exception ex) {
+ LOG.error(ex.getMessage());
+ return new Boolean(false);
+
+ } finally {
+ if (one != null)
+ try {
+ one.close();
+ } catch (JMSException e) {
+ LOG.error(e.getMessage());
+ }
+ }
+
+ // all good, test succeeded
+ return new Boolean(true);
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionFactoryTest.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionFactoryTest.java b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionFactoryTest.java
new file mode 100644
index 0000000..3c39ac4
--- /dev/null
+++ b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionFactoryTest.java
@@ -0,0 +1,284 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import javax.jms.Connection;
+import javax.jms.JMSException;
+import javax.jms.Session;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+import org.apache.activemq.ActiveMQConnectionFactory;
+import org.apache.activemq.util.Wait;
+import org.apache.log4j.Logger;
+
+/**
+ * Checks the behavior of the PooledConnectionFactory when the maximum amount of
+ * sessions is being reached.
+ *
+ * Older versions simply block in the call to Connection.getSession(), which
+ * isn't good. An exception being returned is the better option, so JMS clients
+ * don't block. This test succeeds if an exception is returned and fails if the
+ * call to getSession() blocks.
+ */
+public class PooledConnectionFactoryTest extends TestCase {
+
+ public final static Logger LOG = Logger.getLogger(PooledConnectionFactoryTest.class);
+
+ /**
+ * Create the test case
+ *
+ * @param testName
+ * name of the test case
+ */
+ public PooledConnectionFactoryTest(String testName) {
+ super(testName);
+ }
+
+ /**
+ * @return the suite of tests being tested
+ */
+ public static Test suite() {
+ return new TestSuite(PooledConnectionFactoryTest.class);
+ }
+
+ public void testClearAllConnections() throws Exception {
+
+ ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory("vm://broker1?marshal=false&broker.persistent=false");
+ PooledConnectionFactory cf = new PooledConnectionFactory();
+ cf.setConnectionFactory(amq);
+ cf.setMaxConnections(3);
+
+ PooledConnection conn1 = (PooledConnection) cf.createConnection();
+ PooledConnection conn2 = (PooledConnection) cf.createConnection();
+ PooledConnection conn3 = (PooledConnection) cf.createConnection();
+
+ assertNotSame(conn1.getConnection(), conn2.getConnection());
+ assertNotSame(conn1.getConnection(), conn3.getConnection());
+ assertNotSame(conn2.getConnection(), conn3.getConnection());
+
+ assertEquals(3, cf.getNumConnections());
+
+ cf.clear();
+
+ assertEquals(0, cf.getNumConnections());
+
+ conn1 = (PooledConnection) cf.createConnection();
+ conn2 = (PooledConnection) cf.createConnection();
+ conn3 = (PooledConnection) cf.createConnection();
+
+ assertNotSame(conn1.getConnection(), conn2.getConnection());
+ assertNotSame(conn1.getConnection(), conn3.getConnection());
+ assertNotSame(conn2.getConnection(), conn3.getConnection());
+ }
+
+ public void testMaxConnectionsAreCreated() throws Exception {
+
+ ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory("vm://broker1?marshal=false&broker.persistent=false");
+ PooledConnectionFactory cf = new PooledConnectionFactory();
+ cf.setConnectionFactory(amq);
+ cf.setMaxConnections(3);
+
+ PooledConnection conn1 = (PooledConnection) cf.createConnection();
+ PooledConnection conn2 = (PooledConnection) cf.createConnection();
+ PooledConnection conn3 = (PooledConnection) cf.createConnection();
+
+ assertNotSame(conn1.getConnection(), conn2.getConnection());
+ assertNotSame(conn1.getConnection(), conn3.getConnection());
+ assertNotSame(conn2.getConnection(), conn3.getConnection());
+
+ assertEquals(3, cf.getNumConnections());
+ }
+
+ public void testConnectionsAreRotated() throws Exception {
+
+ ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory("vm://broker1?marshal=false&broker.persistent=false");
+ PooledConnectionFactory cf = new PooledConnectionFactory();
+ cf.setConnectionFactory(amq);
+ cf.setMaxConnections(10);
+
+ Connection previous = null;
+
+ // Front load the pool.
+ for (int i = 0; i < 10; ++i) {
+ cf.createConnection();
+ }
+
+ for (int i = 0; i < 100; ++i) {
+ Connection current = ((PooledConnection) cf.createConnection()).getConnection();
+ assertNotSame(previous, current);
+ previous = current;
+ }
+ }
+
+ public void testConnectionsArePooled() throws Exception {
+
+ ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory("vm://broker1?marshal=false&broker.persistent=false");
+ PooledConnectionFactory cf = new PooledConnectionFactory();
+ cf.setConnectionFactory(amq);
+ cf.setMaxConnections(1);
+
+ PooledConnection conn1 = (PooledConnection) cf.createConnection();
+ PooledConnection conn2 = (PooledConnection) cf.createConnection();
+ PooledConnection conn3 = (PooledConnection) cf.createConnection();
+
+ assertSame(conn1.getConnection(), conn2.getConnection());
+ assertSame(conn1.getConnection(), conn3.getConnection());
+ assertSame(conn2.getConnection(), conn3.getConnection());
+
+ assertEquals(1, cf.getNumConnections());
+ }
+
+ public void testConnectionsArePooledAsyncCreate() throws Exception {
+
+ final ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory("vm://broker1?marshal=false&broker.persistent=false");
+ final PooledConnectionFactory cf = new PooledConnectionFactory();
+ cf.setConnectionFactory(amq);
+ cf.setMaxConnections(1);
+
+ final ConcurrentLinkedQueue<PooledConnection> connections = new ConcurrentLinkedQueue<PooledConnection>();
+
+ final PooledConnection primary = (PooledConnection) cf.createConnection();
+ final ExecutorService executor = Executors.newFixedThreadPool(10);
+ final int numConnections = 100;
+
+ for (int i = 0; i < numConnections; ++i) {
+ executor.execute(new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ connections.add((PooledConnection) cf.createConnection());
+ } catch (JMSException e) {
+ }
+ }
+ });
+ }
+
+ assertTrue("", Wait.waitFor(new Wait.Condition() {
+ @Override
+ public boolean isSatisified() throws Exception {
+ return connections.size() == numConnections;
+ }
+ }));
+
+ executor.shutdown();
+ assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
+
+ for(PooledConnection connection : connections) {
+ assertSame(primary.getConnection(), connection.getConnection());
+ }
+
+ connections.clear();
+ }
+
+ /**
+ * Tests the behavior of the sessionPool of the PooledConnectionFactory when
+ * maximum number of sessions are reached.
+ */
+ public void testApp() throws Exception {
+ // using separate thread for testing so that we can interrupt the test
+ // if the call to get a new session blocks.
+
+ // start test runner thread
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ Future<Boolean> result = executor.submit(new TestRunner());
+
+ // test should not take > 5secs, so test fails i
+ Thread.sleep(5 * 1000);
+
+ if (!result.isDone() || !result.get().booleanValue()) {
+ PooledConnectionFactoryTest.LOG.error("2nd call to createSession() " +
+ "is blocking but should have returned an error instead.");
+
+ executor.shutdownNow();
+
+ fail("SessionPool inside PooledConnectionFactory is blocking if " +
+ "limit is exceeded but should return an exception instead.");
+ }
+ }
+
+ static class TestRunner implements Callable<Boolean> {
+
+ public final static Logger LOG = Logger.getLogger(TestRunner.class);
+
+ /**
+ * @return true if test succeeded, false otherwise
+ */
+ @Override
+ public Boolean call() {
+
+ Connection conn = null;
+ Session one = null;
+
+ // wait at most 5 seconds for the call to createSession
+ try {
+ ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory("vm://broker1?marshal=false&broker.persistent=false");
+ PooledConnectionFactory cf = new PooledConnectionFactory();
+ cf.setConnectionFactory(amq);
+ cf.setMaxConnections(3);
+ cf.setMaximumActiveSessionPerConnection(1);
+ cf.setBlockIfSessionPoolIsFull(false);
+
+ conn = cf.createConnection();
+ one = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+ Session two = null;
+ try {
+ // this should raise an exception as we called
+ // setMaximumActive(1)
+ two = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ two.close();
+
+ LOG.error("Expected JMSException wasn't thrown.");
+ fail("seconds call to Connection.createSession() was supposed" +
+ "to raise an JMSException as internal session pool" +
+ "is exhausted. This did not happen and indiates a problem");
+ return new Boolean(false);
+ } catch (JMSException ex) {
+ if (ex.getCause().getClass() == java.util.NoSuchElementException.class) {
+ // expected, ignore but log
+ LOG.info("Caught expected " + ex);
+ } else {
+ LOG.error(ex);
+ return new Boolean(false);
+ }
+ } finally {
+ if (one != null)
+ one.close();
+ if (conn != null)
+ conn.close();
+ }
+ } catch (Exception ex) {
+ LOG.error(ex.getMessage());
+ return new Boolean(false);
+ }
+
+ // all good, test succeeded
+ return new Boolean(true);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionFactoryWithTemporaryDestinationsTest.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionFactoryWithTemporaryDestinationsTest.java b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionFactoryWithTemporaryDestinationsTest.java
new file mode 100644
index 0000000..9438828
--- /dev/null
+++ b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionFactoryWithTemporaryDestinationsTest.java
@@ -0,0 +1,125 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.Topic;
+import javax.jms.Connection;
+
+import org.apache.activemq.broker.BrokerService;
+import org.apache.activemq.broker.TransportConnector;
+import org.apache.activemq.broker.region.RegionBroker;
+import org.apache.activemq.test.TestSupport;
+import org.apache.activemq.ActiveMQConnectionFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * @version $Revision: 1.1 $
+ */
+public class PooledConnectionFactoryWithTemporaryDestinationsTest extends TestSupport {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PooledConnectionFactoryWithTemporaryDestinationsTest.class);
+
+ private BrokerService broker;
+ private ActiveMQConnectionFactory factory;
+ private PooledConnectionFactory pooledFactory;
+
+ protected void setUp() throws Exception {
+ broker = new BrokerService();
+ broker.setUseJmx(false);
+ broker.setPersistent(false);
+ TransportConnector connector = broker.addConnector("tcp://localhost:0");
+ broker.start();
+ factory = new ActiveMQConnectionFactory("mock:" + connector.getConnectUri() + "?closeAsync=false");
+ pooledFactory = new PooledConnectionFactory();
+ pooledFactory.setConnectionFactory(factory);
+ }
+
+ protected void tearDown() throws Exception {
+ broker.stop();
+ }
+
+ public void testTemporaryQueueWithMultipleConnectionUsers() throws Exception {
+ Connection pooledConnection = null;
+ Connection pooledConnection2 = null;
+ Session session = null;
+ Session session2 = null;
+ Queue tempQueue = null;
+ Queue normalQueue = null;
+
+ pooledConnection = pooledFactory.createConnection();
+ session = pooledConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ tempQueue = session.createTemporaryQueue();
+ LOG.info("Created queue named: " + tempQueue.getQueueName());
+
+ assertEquals(1, countBrokerTemporaryQueues());
+
+ pooledConnection2 = pooledFactory.createConnection();
+ session2 = pooledConnection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ normalQueue = session2.createQueue("queue:FOO.TEST");
+ LOG.info("Created queue named: " + normalQueue.getQueueName());
+
+ // didn't create a temp queue on pooledConnection2 so we should still have a temp queue
+ pooledConnection2.close();
+ assertEquals(1, countBrokerTemporaryQueues());
+
+ // after closing pooledConnection, where we created the temp queue, there should
+ // be no temp queues left
+ pooledConnection.close();
+ assertEquals(0, countBrokerTemporaryQueues());
+ }
+
+ public void testTemporaryQueueLeakAfterConnectionClose() throws Exception {
+ Connection pooledConnection = null;
+ Session session = null;
+ Queue tempQueue = null;
+ for (int i = 0; i < 2; i++) {
+ pooledConnection = pooledFactory.createConnection();
+ session = pooledConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ tempQueue = session.createTemporaryQueue();
+ LOG.info("Created queue named: " + tempQueue.getQueueName());
+ pooledConnection.close();
+ }
+
+ assertEquals(0, countBrokerTemporaryQueues());
+ }
+
+ public void testTemporaryTopicLeakAfterConnectionClose() throws Exception {
+ Connection pooledConnection = null;
+ Session session = null;
+ Topic tempTopic = null;
+ for (int i = 0; i < 2; i++) {
+ pooledConnection = pooledFactory.createConnection();
+ session = pooledConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ tempTopic = session.createTemporaryTopic();
+ LOG.info("Created topic named: " + tempTopic.getTopicName());
+ pooledConnection.close();
+ }
+
+ assertEquals(0, countBrokerTemporaryTopics());
+ }
+
+ private int countBrokerTemporaryQueues() throws Exception {
+ return ((RegionBroker) broker.getRegionBroker()).getTempQueueRegion().getDestinationMap().size();
+ }
+
+ private int countBrokerTemporaryTopics() throws Exception {
+ return ((RegionBroker) broker.getRegionBroker()).getTempTopicRegion().getDestinationMap().size();
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionSessionCleanupTest.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionSessionCleanupTest.java b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionSessionCleanupTest.java
new file mode 100644
index 0000000..ec6b5b2
--- /dev/null
+++ b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionSessionCleanupTest.java
@@ -0,0 +1,229 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.jms.pool;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.concurrent.TimeUnit;
+
+import javax.jms.Connection;
+import javax.jms.JMSException;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Session;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+
+import org.apache.activemq.ActiveMQConnectionFactory;
+import org.apache.activemq.broker.BrokerService;
+import org.apache.activemq.broker.jmx.QueueViewMBean;
+import org.apache.activemq.command.ActiveMQQueue;
+import org.apache.activemq.util.Wait;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class PooledConnectionSessionCleanupTest {
+
+ @SuppressWarnings("unused")
+ private static final Logger LOG = LoggerFactory.getLogger(PooledConnectionSessionCleanupTest.class);
+
+ protected BrokerService service;
+
+ protected ActiveMQConnectionFactory directConnFact;
+ protected Connection directConn1;
+ protected Connection directConn2;
+
+ protected PooledConnectionFactory pooledConnFact;
+ protected Connection pooledConn1;
+ protected Connection pooledConn2;
+
+ private final ActiveMQQueue queue = new ActiveMQQueue("ContendedQueue");
+ private final int MESSAGE_COUNT = 50;
+
+ /**
+ * Prepare to run a test case: create, configure, and start the embedded
+ * broker, as well as creating the client connections to the broker.
+ */
+ @Before
+ public void prepTest() throws java.lang.Exception {
+ service = new BrokerService();
+ service.setBrokerName("PooledConnectionSessionCleanupTestBroker");
+ service.setUseJmx(true);
+ service.setPersistent(false);
+ service.setSchedulerSupport(false);
+ service.start();
+ service.waitUntilStarted();
+
+ // Create the ActiveMQConnectionFactory and the PooledConnectionFactory.
+ // Set a long idle timeout on the pooled connections to better show the
+ // problem of holding onto created resources on close.
+ directConnFact = new ActiveMQConnectionFactory(service.getVmConnectorURI());
+ pooledConnFact = new PooledConnectionFactory();
+ pooledConnFact.setConnectionFactory(directConnFact);
+ pooledConnFact.setIdleTimeout((int)TimeUnit.MINUTES.toMillis(60));
+ pooledConnFact.setMaxConnections(1);
+
+ // Prepare the connections
+ directConn1 = directConnFact.createConnection();
+ directConn1.start();
+ directConn2 = directConnFact.createConnection();
+ directConn2.start();
+
+ // The pooled Connections should have the same underlying connection
+ pooledConn1 = pooledConnFact.createConnection();
+ pooledConn1.start();
+ pooledConn2 = pooledConnFact.createConnection();
+ pooledConn2.start();
+ }
+
+ @After
+ public void cleanupTest() throws java.lang.Exception {
+ try {
+ if (pooledConn1 != null) {
+ pooledConn1.close();
+ }
+ } catch (JMSException jms_exc) {
+ }
+ try {
+ if (pooledConn2 != null) {
+ pooledConn2.close();
+ }
+ } catch (JMSException jms_exc) {
+ }
+ try {
+ if (directConn1 != null) {
+ directConn1.close();
+ }
+ } catch (JMSException jms_exc) {
+ }
+ try {
+ if (directConn2 != null) {
+ directConn2.close();
+ }
+ } catch (JMSException jms_exc) {
+ }
+ try {
+ if (service != null) {
+ service.stop();
+ service.waitUntilStopped();
+ service = null;
+ }
+ } catch (JMSException jms_exc) {
+ }
+ }
+
+ private void produceMessages() throws Exception {
+
+ Session session = directConn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ MessageProducer producer = session.createProducer(queue);
+ for (int i = 0; i < MESSAGE_COUNT; ++i) {
+ producer.send(session.createTextMessage("Test Message: " + i));
+ }
+ producer.close();
+ }
+
+ private QueueViewMBean getProxyToQueue(String name) throws MalformedObjectNameException, JMSException {
+ ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq"
+ + ":destinationType=Queue,destinationName=" + name
+ + ",type=Broker,brokerName=" + service.getBrokerName());
+ QueueViewMBean proxy = (QueueViewMBean) service.getManagementContext()
+ .newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true);
+ return proxy;
+ }
+
+ @Test
+ public void testLingeringPooledSessionsHoldingPrefetchedMessages() throws Exception {
+
+ produceMessages();
+
+ Session pooledSession1 = pooledConn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ pooledSession1.createConsumer(queue);
+
+ final QueueViewMBean view = getProxyToQueue(queue.getPhysicalName());
+
+ assertTrue("Should have all sent messages in flight:", Wait.waitFor(new Wait.Condition() {
+
+ @Override
+ public boolean isSatisified() throws Exception {
+ return view.getInFlightCount() == MESSAGE_COUNT;
+ }
+ }));
+
+ // While all the message are in flight we should get anything on this consumer.
+ Session session = directConn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ MessageConsumer consumer = session.createConsumer(queue);
+ assertNull(consumer.receive(2000));
+
+ pooledConn1.close();
+
+ assertTrue("Should have only one consumer now:", Wait.waitFor(new Wait.Condition() {
+
+ @Override
+ public boolean isSatisified() throws Exception {
+ return view.getSubscriptions().length == 1;
+ }
+ }));
+
+ // Now we'd expect that the message stuck in the prefetch of the pooled session's
+ // consumer would be rerouted to the non-pooled session's consumer.
+ assertNotNull(consumer.receive(10000));
+ }
+
+ @Test
+ public void testNonPooledConnectionCloseNotHoldingPrefetchedMessages() throws Exception {
+
+ produceMessages();
+
+ Session directSession = directConn2.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ directSession.createConsumer(queue);
+
+ final QueueViewMBean view = getProxyToQueue(queue.getPhysicalName());
+
+ assertTrue("Should have all sent messages in flight:", Wait.waitFor(new Wait.Condition() {
+
+ @Override
+ public boolean isSatisified() throws Exception {
+ return view.getInFlightCount() == MESSAGE_COUNT;
+ }
+ }));
+
+ // While all the message are in flight we should get anything on this consumer.
+ Session session = directConn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ MessageConsumer consumer = session.createConsumer(queue);
+ assertNull(consumer.receive(2000));
+
+ directConn2.close();
+
+ assertTrue("Should have only one consumer now:", Wait.waitFor(new Wait.Condition() {
+
+ @Override
+ public boolean isSatisified() throws Exception {
+ return view.getSubscriptions().length == 1;
+ }
+ }));
+
+ // Now we'd expect that the message stuck in the prefetch of the first session's
+ // consumer would be rerouted to the alternate session's consumer.
+ assertNotNull(consumer.receive(10000));
+ }
+}
[6/6] git commit: https://issues.apache.org/jira/browse/AMQ-4757
activemq-jms-pool a generic jms xa pool derived from activemq-pool which
activemq-pool now extends with amq specifics
Posted by gt...@apache.org.
https://issues.apache.org/jira/browse/AMQ-4757 activemq-jms-pool a generic jms xa pool derived from activemq-pool which activemq-pool now extends with amq specifics
Project: http://git-wip-us.apache.org/repos/asf/activemq/repo
Commit: http://git-wip-us.apache.org/repos/asf/activemq/commit/b66559ee
Tree: http://git-wip-us.apache.org/repos/asf/activemq/tree/b66559ee
Diff: http://git-wip-us.apache.org/repos/asf/activemq/diff/b66559ee
Branch: refs/heads/trunk
Commit: b66559ee079bd55bfc49daae6b95b79706147fbe
Parents: 6b96624
Author: gtully <ga...@gmail.com>
Authored: Mon Sep 30 23:08:40 2013 +0100
Committer: gtully <ga...@gmail.com>
Committed: Mon Sep 30 23:09:25 2013 +0100
----------------------------------------------------------------------
activemq-arquillian/javaee/jca-remote/pom.xml | 4 +-
activemq-arquillian/javaee/pom.xml | 4 +
.../component/JmsSimpleRequestReplyTest.java | 1 -
.../resources/org/apache/activemq/camel/dlq.xml | 2 +-
.../activemq/ActiveMQConnectionFactory.java | 1 +
.../apache/activemq/ActiveMQXAConnection.java | 16 +-
.../activemq/ActiveMQXAConnectionFactory.java | 20 +
activemq-jms-pool/pom.xml | 108 ++++
.../apache/activemq/jms/pool/ConnectionKey.java | 75 +++
.../activemq/jms/pool/ConnectionPool.java | 294 +++++++++++
.../jms/pool/GenericResourceManager.java | 194 +++++++
.../activemq/jms/pool/IntrospectionSupport.java | 118 +++++
.../activemq/jms/pool/JcaConnectionPool.java | 43 ++
.../jms/pool/JcaPooledConnectionFactory.java | 35 ++
.../activemq/jms/pool/PooledConnection.java | 286 +++++++++++
.../jms/pool/PooledConnectionFactory.java | 479 +++++++++++++++++
.../jms/pool/PooledMessageConsumer.java | 84 +++
.../activemq/jms/pool/PooledProducer.java | 146 ++++++
.../activemq/jms/pool/PooledQueueSender.java | 52 ++
.../apache/activemq/jms/pool/PooledSession.java | 445 ++++++++++++++++
.../jms/pool/PooledSessionEventListener.java | 49 ++
.../activemq/jms/pool/PooledTopicPublisher.java | 62 +++
.../apache/activemq/jms/pool/SessionKey.java | 63 +++
.../activemq/jms/pool/XaConnectionPool.java | 115 +++++
.../jms/pool/XaPooledConnectionFactory.java | 145 ++++++
.../org/apache/activemq/jms/pool/package.html | 25 +
.../ConnectionExpiryEvictsFromPoolTest.java | 115 +++++
...ooledConnectionFactoryMaximumActiveTest.java | 151 ++++++
.../jms/pool/PooledConnectionFactoryTest.java | 284 ++++++++++
...ionFactoryWithTemporaryDestinationsTest.java | 125 +++++
.../PooledConnectionSessionCleanupTest.java | 229 +++++++++
.../PooledConnectionTempDestCleanupTest.java | 223 ++++++++
.../activemq/jms/pool/PooledConnectionTest.java | 114 +++++
.../jms/pool/PooledSessionExhaustionTest.java | 120 +++++
.../activemq/jms/pool/PooledSessionTest.java | 71 +++
.../jms/pool/PooledTopicPublisherTest.java | 106 ++++
.../activemq/jms/pool/XAConnectionPoolTest.java | 348 +++++++++++++
.../activemq/jms/pool/bugs/AMQ4441Test.java | 86 ++++
.../src/test/resources/activemq-spring-jdbc.xml | 69 +++
.../src/test/resources/log4j.properties | 38 ++
.../apache/activemq/karaf/commands/spring.xml | 2 +-
activemq-pool/pom.xml | 11 +-
.../activemq/pool/ActiveMQResourceManager.java | 165 +-----
.../pool/AmqJNDIPooledConnectionFactory.java | 113 ----
.../org/apache/activemq/pool/ConnectionKey.java | 75 ---
.../apache/activemq/pool/ConnectionPool.java | 314 ------------
.../apache/activemq/pool/JcaConnectionPool.java | 43 --
.../pool/JcaPooledConnectionFactory.java | 71 ++-
.../apache/activemq/pool/PooledConnection.java | 275 +---------
.../activemq/pool/PooledConnectionFactory.java | 512 +++----------------
.../activemq/pool/PooledMessageConsumer.java | 84 ---
.../apache/activemq/pool/PooledProducer.java | 148 ------
.../apache/activemq/pool/PooledQueueSender.java | 54 --
.../org/apache/activemq/pool/PooledSession.java | 449 ----------------
.../pool/PooledSessionEventListener.java | 49 --
.../activemq/pool/PooledTopicPublisher.java | 64 ---
.../org/apache/activemq/pool/SessionKey.java | 63 ---
.../apache/activemq/pool/XaConnectionPool.java | 110 ----
.../pool/XaPooledConnectionFactory.java | 226 ++++----
.../java/org/apache/activemq/pool/package.html | 28 -
.../ConnectionExpiryEvictsFromPoolTest.java | 115 -----
.../ConnectionFailureEvictsFromPoolTest.java | 46 +-
...ooledConnectionFactoryMaximumActiveTest.java | 150 ------
.../pool/PooledConnectionFactoryTest.java | 279 ----------
...ionFactoryWithTemporaryDestinationsTest.java | 124 -----
.../PooledConnectionSessionCleanupTest.java | 228 ---------
.../PooledConnectionTempDestCleanupTest.java | 222 --------
.../activemq/pool/PooledConnectionTest.java | 112 ----
.../pool/PooledSessionExhaustionTest.java | 119 -----
.../apache/activemq/pool/PooledSessionTest.java | 70 ---
.../activemq/pool/PooledTopicPublisherTest.java | 106 ----
.../activemq/pool/XAConnectionPoolTest.java | 11 +-
.../apache/activemq/pool/bugs/AMQ4441Test.java | 84 ---
.../src/test/resources/activemq-spring-jdbc.xml | 69 ---
.../src/test/resources/log4j.properties | 38 --
.../pool/PooledConnectionFactoryBean.java | 4 +-
.../test/java/org/apache/bugs/AMQ2754Test.java | 1 -
assembly/pom.xml | 8 +
assembly/src/main/descriptors/common-bin.xml | 1 +
pom.xml | 6 +
80 files changed, 5246 insertions(+), 4348 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-arquillian/javaee/jca-remote/pom.xml
----------------------------------------------------------------------
diff --git a/activemq-arquillian/javaee/jca-remote/pom.xml b/activemq-arquillian/javaee/jca-remote/pom.xml
index 3a204fe..042ea33 100644
--- a/activemq-arquillian/javaee/jca-remote/pom.xml
+++ b/activemq-arquillian/javaee/jca-remote/pom.xml
@@ -45,7 +45,7 @@
<overwrite>true</overwrite>
<resources>
<resource>
- <directory>${jboss.home}</directory>
+ <directory>${ee.install.home}</directory>
<excludes>
<exclude>standalone/data</exclude>
<exclude>standalone/log</exclude>
@@ -74,4 +74,4 @@
</plugin>
</plugins>
</build>
-</project>
\ No newline at end of file
+</project>
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-arquillian/javaee/pom.xml
----------------------------------------------------------------------
diff --git a/activemq-arquillian/javaee/pom.xml b/activemq-arquillian/javaee/pom.xml
index b32b19c..5827cef 100644
--- a/activemq-arquillian/javaee/pom.xml
+++ b/activemq-arquillian/javaee/pom.xml
@@ -49,6 +49,10 @@
</dependencyManagement>
<dependencies>
<dependency>
+ <groupId>org.jboss.arquillian.junit</groupId>
+ <artifactId>arquillian-junit-container</artifactId>
+ </dependency>
+ <dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-6.0</artifactId>
<version>1.0.0.Final</version>
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-camel/src/test/java/org/apache/activemq/camel/component/JmsSimpleRequestReplyTest.java
----------------------------------------------------------------------
diff --git a/activemq-camel/src/test/java/org/apache/activemq/camel/component/JmsSimpleRequestReplyTest.java b/activemq-camel/src/test/java/org/apache/activemq/camel/component/JmsSimpleRequestReplyTest.java
index cd1dd3f..099448c 100644
--- a/activemq-camel/src/test/java/org/apache/activemq/camel/component/JmsSimpleRequestReplyTest.java
+++ b/activemq-camel/src/test/java/org/apache/activemq/camel/component/JmsSimpleRequestReplyTest.java
@@ -22,7 +22,6 @@ import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.pool.PooledConnectionFactory;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
-import org.apache.camel.ExchangePattern;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-camel/src/test/resources/org/apache/activemq/camel/dlq.xml
----------------------------------------------------------------------
diff --git a/activemq-camel/src/test/resources/org/apache/activemq/camel/dlq.xml b/activemq-camel/src/test/resources/org/apache/activemq/camel/dlq.xml
index be04ee8..b1d9881 100644
--- a/activemq-camel/src/test/resources/org/apache/activemq/camel/dlq.xml
+++ b/activemq-camel/src/test/resources/org/apache/activemq/camel/dlq.xml
@@ -61,7 +61,7 @@
</bean>
<!-- only for jta - not jms tm
- bean id="resourceManager" class="org.apache.activemq.pool.ActiveMQResourceManager" init-method="recoverResource">
+ bean id="resourceManager" class="org.apache.activemq.jms.pool.GenericResourceManager" init-method="recoverResource">
<property name="transactionManager" ref="transactionManager" />
<property name="connectionFactory" ref="activemqConnectionFactory" />
<property name="resourceName" value="activemq.default" />
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-client/src/main/java/org/apache/activemq/ActiveMQConnectionFactory.java
----------------------------------------------------------------------
diff --git a/activemq-client/src/main/java/org/apache/activemq/ActiveMQConnectionFactory.java b/activemq-client/src/main/java/org/apache/activemq/ActiveMQConnectionFactory.java
index 056aa65..fbbfc2b 100755
--- a/activemq-client/src/main/java/org/apache/activemq/ActiveMQConnectionFactory.java
+++ b/activemq-client/src/main/java/org/apache/activemq/ActiveMQConnectionFactory.java
@@ -122,6 +122,7 @@ public class ActiveMQConnectionFactory extends JNDIBaseStorable implements Conne
private int maxThreadPoolSize = ActiveMQConnection.DEFAULT_THREAD_POOL_SIZE;
private TaskRunnerFactory sessionTaskRunner;
private RejectedExecutionHandler rejectedTaskHandler = null;
+ protected int xaAckMode = -1; // ensure default init before setting via brokerUrl introspection in sub class
// /////////////////////////////////////////////
//
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-client/src/main/java/org/apache/activemq/ActiveMQXAConnection.java
----------------------------------------------------------------------
diff --git a/activemq-client/src/main/java/org/apache/activemq/ActiveMQXAConnection.java b/activemq-client/src/main/java/org/apache/activemq/ActiveMQXAConnection.java
index e32af82..20b376d 100755
--- a/activemq-client/src/main/java/org/apache/activemq/ActiveMQXAConnection.java
+++ b/activemq-client/src/main/java/org/apache/activemq/ActiveMQXAConnection.java
@@ -50,6 +50,8 @@ import org.apache.activemq.util.IdGenerator;
*/
public class ActiveMQXAConnection extends ActiveMQConnection implements XATopicConnection, XAQueueConnection, XAConnection {
+ private int xaAckMode;
+
protected ActiveMQXAConnection(Transport transport, IdGenerator clientIdGenerator,
IdGenerator connectionIdGenerator, JMSStatsImpl factoryStats) throws Exception {
super(transport, clientIdGenerator, connectionIdGenerator, factoryStats);
@@ -70,6 +72,18 @@ public class ActiveMQXAConnection extends ActiveMQConnection implements XATopicC
public Session createSession(boolean transacted, int acknowledgeMode) throws JMSException {
checkClosedOrFailed();
ensureConnectionInfoSent();
- return new ActiveMQXASession(this, getNextSessionId(), Session.SESSION_TRANSACTED, isDispatchAsync());
+ return new ActiveMQXASession(this, getNextSessionId(), getAckMode(), isDispatchAsync());
+ }
+
+ private int getAckMode() {
+ return xaAckMode > 0 ? xaAckMode : Session.SESSION_TRANSACTED;
+ }
+
+ public void setXaAckMode(int xaAckMode) {
+ this.xaAckMode = xaAckMode;
+ }
+
+ public int getXaAckMode() {
+ return xaAckMode;
}
}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-client/src/main/java/org/apache/activemq/ActiveMQXAConnectionFactory.java
----------------------------------------------------------------------
diff --git a/activemq-client/src/main/java/org/apache/activemq/ActiveMQXAConnectionFactory.java b/activemq-client/src/main/java/org/apache/activemq/ActiveMQXAConnectionFactory.java
index b2a715b..c383685 100644
--- a/activemq-client/src/main/java/org/apache/activemq/ActiveMQXAConnectionFactory.java
+++ b/activemq-client/src/main/java/org/apache/activemq/ActiveMQXAConnectionFactory.java
@@ -17,6 +17,7 @@
package org.apache.activemq;
import java.net.URI;
+import java.util.Properties;
import javax.jms.JMSException;
import javax.jms.XAConnection;
@@ -81,6 +82,25 @@ public class ActiveMQXAConnectionFactory extends ActiveMQConnectionFactory imple
protected ActiveMQConnection createActiveMQConnection(Transport transport, JMSStatsImpl stats) throws Exception {
ActiveMQXAConnection connection = new ActiveMQXAConnection(transport, getClientIdGenerator(), getConnectionIdGenerator(), stats);
+ configureXAConnection(connection);
return connection;
}
+
+ private void configureXAConnection(ActiveMQXAConnection connection) {
+ connection.setXaAckMode(xaAckMode);
+ }
+
+ public int getXaAckMode() {
+ return xaAckMode;
+ }
+
+ public void setXaAckMode(int xaAckMode) {
+ this.xaAckMode = xaAckMode;
+ }
+
+ @Override
+ public void populateProperties(Properties props) {
+ super.populateProperties(props);
+ props.put("xaAckMode", Integer.toString(xaAckMode));
+ }
}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/pom.xml
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/pom.xml b/activemq-jms-pool/pom.xml
new file mode 100755
index 0000000..ba77a3e
--- /dev/null
+++ b/activemq-jms-pool/pom.xml
@@ -0,0 +1,108 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.activemq</groupId>
+ <artifactId>activemq-parent</artifactId>
+ <version>5.9-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>activemq-jms-pool</artifactId>
+ <name>ActiveMQ :: Generic JMS Pool</name>
+ <description>Generic JMS Pooled ConnectionFactory</description>
+
+ <properties>
+ <activemq.osgi.import.pkg>
+ javax.transaction*;resolution:=optional,
+ org.apache.geronimo.transaction.manager*;resolution:=optional,
+ *
+ </activemq.osgi.import.pkg>
+ <activemq.osgi.export>
+ org.apache.activemq.jms.pool*;version=${project.version};-noimport:=true,
+ </activemq.osgi.export>
+ </properties>
+
+ <dependencies>
+
+ <!-- =============================== -->
+ <!-- Required Dependencies -->
+ <!-- =============================== -->
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.geronimo.specs</groupId>
+ <artifactId>geronimo-jms_1.1_spec</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.geronimo.components</groupId>
+ <artifactId>geronimo-transaction</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.geronimo.specs</groupId>
+ <artifactId>geronimo-jta_1.0.1B_spec</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.geronimo.specs</groupId>
+ <artifactId>geronimo-annotation_1.0_spec</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>commons-pool</groupId>
+ <artifactId>commons-pool</artifactId>
+ </dependency>
+ <!-- for testing use amq -->
+ <dependency>
+ <groupId>org.apache.activemq</groupId>
+ <artifactId>activemq-broker</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.activemq</groupId>
+ <artifactId>activemq-kahadb-store</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>activemq-broker</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+</project>
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/ConnectionKey.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/ConnectionKey.java b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/ConnectionKey.java
new file mode 100644
index 0000000..952c009
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/ConnectionKey.java
@@ -0,0 +1,75 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+/**
+ * A cache key for the connection details
+ */
+public class ConnectionKey {
+
+ private final String userName;
+ private final String password;
+ private int hash;
+
+ public ConnectionKey(String userName, String password) {
+ this.password = password;
+ this.userName = userName;
+ hash = 31;
+ if (userName != null) {
+ hash += userName.hashCode();
+ }
+ hash *= 31;
+ if (password != null) {
+ hash += password.hashCode();
+ }
+ }
+
+ @Override
+ public int hashCode() {
+ return hash;
+ }
+
+ @Override
+ public boolean equals(Object that) {
+ if (this == that) {
+ return true;
+ }
+ if (that instanceof ConnectionKey) {
+ return equals((ConnectionKey) that);
+ }
+ return false;
+ }
+
+ public boolean equals(ConnectionKey that) {
+ return isEqual(this.userName, that.userName) && isEqual(this.password, that.password);
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public String getUserName() {
+ return userName;
+ }
+
+ public static boolean isEqual(Object o1, Object o2) {
+ if (o1 == o2) {
+ return true;
+ }
+ return o1 != null && o2 != null && o1.equals(o2);
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/ConnectionPool.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/ConnectionPool.java b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/ConnectionPool.java
new file mode 100644
index 0000000..df2da17
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/ConnectionPool.java
@@ -0,0 +1,294 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.jms.pool;
+
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import javax.jms.Connection;
+import javax.jms.JMSException;
+import javax.jms.Session;
+import javax.jms.IllegalStateException;
+
+import org.apache.commons.pool.KeyedPoolableObjectFactory;
+import org.apache.commons.pool.impl.GenericKeyedObjectPool;
+import org.apache.commons.pool.impl.GenericObjectPool;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Holds a real JMS connection along with the session pools associated with it.
+ * <p/>
+ * Instances of this class are shared amongst one or more PooledConnection object and must
+ * track the session objects that are loaned out for cleanup on close as well as ensuring
+ * that the temporary destinations of the managed Connection are purged when all references
+ * to this ConnectionPool are released.
+ */
+public class ConnectionPool {
+
+ private static final transient Logger LOG = LoggerFactory.getLogger(ConnectionPool.class);
+
+ protected Connection connection;
+ private int referenceCount;
+ private long lastUsed = System.currentTimeMillis();
+ private final long firstUsed = lastUsed;
+ private boolean hasExpired;
+ private int idleTimeout = 30 * 1000;
+ private long expiryTimeout = 0l;
+
+ private final AtomicBoolean started = new AtomicBoolean(false);
+ private final GenericKeyedObjectPool<SessionKey, PooledSession> sessionPool;
+ private final List<PooledSession> loanedSessions = new CopyOnWriteArrayList<PooledSession>();
+
+ public ConnectionPool(Connection connection) {
+
+ this.connection = wrap(connection);
+
+ // Create our internal Pool of session instances.
+ this.sessionPool = new GenericKeyedObjectPool<SessionKey, PooledSession>(
+ new KeyedPoolableObjectFactory<SessionKey, PooledSession>() {
+
+ @Override
+ public void activateObject(SessionKey key, PooledSession session) throws Exception {
+ ConnectionPool.this.loanedSessions.add(session);
+ }
+
+ @Override
+ public void destroyObject(SessionKey key, PooledSession session) throws Exception {
+ ConnectionPool.this.loanedSessions.remove(session);
+ session.getInternalSession().close();
+ }
+
+ @Override
+ public PooledSession makeObject(SessionKey key) throws Exception {
+ Session session = makeSession(key);
+ return new PooledSession(key, session, sessionPool, key.isTransacted());
+ }
+
+ @Override
+ public void passivateObject(SessionKey key, PooledSession session) throws Exception {
+ ConnectionPool.this.loanedSessions.remove(session);
+ }
+
+ @Override
+ public boolean validateObject(SessionKey key, PooledSession session) {
+ return true;
+ }
+ }
+ );
+ }
+
+ // useful when external failure needs to force expiry
+ public void setHasExpired(boolean val) {
+ hasExpired = val;
+ }
+
+ protected Session makeSession(SessionKey key) throws JMSException {
+ return connection.createSession(key.isTransacted(), key.getAckMode());
+ }
+
+ protected Connection wrap(Connection connection) {
+ return connection;
+ }
+
+ protected void unWrap(Connection connection) {
+ }
+
+ public void start() throws JMSException {
+ if (started.compareAndSet(false, true)) {
+ try {
+ connection.start();
+ } catch (JMSException e) {
+ started.set(false);
+ throw(e);
+ }
+ }
+ }
+
+ public synchronized Connection getConnection() {
+ return connection;
+ }
+
+ public Session createSession(boolean transacted, int ackMode) throws JMSException {
+ SessionKey key = new SessionKey(transacted, ackMode);
+ PooledSession session;
+ try {
+ session = sessionPool.borrowObject(key);
+ } catch (Exception e) {
+ IllegalStateException illegalStateException = new IllegalStateException(e.toString());
+ illegalStateException.initCause(e);
+ throw illegalStateException;
+ }
+ return session;
+ }
+
+ public synchronized void close() {
+ if (connection != null) {
+ try {
+ sessionPool.close();
+ } catch (Exception e) {
+ } finally {
+ try {
+ connection.close();
+ } catch (Exception e) {
+ } finally {
+ connection = null;
+ }
+ }
+ }
+ }
+
+ public synchronized void incrementReferenceCount() {
+ referenceCount++;
+ lastUsed = System.currentTimeMillis();
+ }
+
+ public synchronized void decrementReferenceCount() {
+ referenceCount--;
+ lastUsed = System.currentTimeMillis();
+ if (referenceCount == 0) {
+ // Loaned sessions are those that are active in the sessionPool and
+ // have not been closed by the client before closing the connection.
+ // These need to be closed so that all session's reflect the fact
+ // that the parent Connection is closed.
+ for (PooledSession session : this.loanedSessions) {
+ try {
+ session.close();
+ } catch (Exception e) {
+ }
+ }
+ this.loanedSessions.clear();
+
+ unWrap(getConnection());
+
+ expiredCheck();
+ }
+ }
+
+ /**
+ * Determines if this Connection has expired.
+ * <p/>
+ * A ConnectionPool is considered expired when all references to it are released AND either
+ * the configured idleTimeout has elapsed OR the configured expiryTimeout has elapsed.
+ * Once a ConnectionPool is determined to have expired its underlying Connection is closed.
+ *
+ * @return true if this connection has expired.
+ */
+ public synchronized boolean expiredCheck() {
+
+ boolean expired = false;
+
+ if (connection == null) {
+ return true;
+ }
+
+ if (hasExpired) {
+ if (referenceCount == 0) {
+ close();
+ expired = true;
+ }
+ }
+
+ if (expiryTimeout > 0 && System.currentTimeMillis() > firstUsed + expiryTimeout) {
+ hasExpired = true;
+ if (referenceCount == 0) {
+ close();
+ expired = true;
+ }
+ }
+
+ // Only set hasExpired here is no references, as a Connection with references is by
+ // definition not idle at this time.
+ if (referenceCount == 0 && idleTimeout > 0 && System.currentTimeMillis() > lastUsed + idleTimeout) {
+ hasExpired = true;
+ close();
+ expired = true;
+ }
+
+ return expired;
+ }
+
+ public int getIdleTimeout() {
+ return idleTimeout;
+ }
+
+ public void setIdleTimeout(int idleTimeout) {
+ this.idleTimeout = idleTimeout;
+ }
+
+ public void setExpiryTimeout(long expiryTimeout) {
+ this.expiryTimeout = expiryTimeout;
+ }
+
+ public long getExpiryTimeout() {
+ return expiryTimeout;
+ }
+
+ public int getMaximumActiveSessionPerConnection() {
+ return this.sessionPool.getMaxActive();
+ }
+
+ public void setMaximumActiveSessionPerConnection(int maximumActiveSessionPerConnection) {
+ this.sessionPool.setMaxActive(maximumActiveSessionPerConnection);
+ }
+
+ /**
+ * @return the total number of Pooled session including idle sessions that are not
+ * currently loaned out to any client.
+ */
+ public int getNumSessions() {
+ return this.sessionPool.getNumIdle() + this.sessionPool.getNumActive();
+ }
+
+ /**
+ * @return the total number of Sessions that are in the Session pool but not loaned out.
+ */
+ public int getNumIdleSessions() {
+ return this.sessionPool.getNumIdle();
+ }
+
+ /**
+ * @return the total number of Session's that have been loaned to PooledConnection instances.
+ */
+ public int getNumActiveSessions() {
+ return this.sessionPool.getNumActive();
+ }
+
+ /**
+ * Configure whether the createSession method should block when there are no more idle sessions and the
+ * pool already contains the maximum number of active sessions. If false the create method will fail
+ * and throw an exception.
+ *
+ * @param block
+ * Indicates whether blocking should be used to wait for more space to create a session.
+ */
+ public void setBlockIfSessionPoolIsFull(boolean block) {
+ this.sessionPool.setWhenExhaustedAction(
+ (block ? GenericObjectPool.WHEN_EXHAUSTED_BLOCK : GenericObjectPool.WHEN_EXHAUSTED_FAIL));
+ }
+
+ public boolean isBlockIfSessionPoolIsFull() {
+ return this.sessionPool.getWhenExhaustedAction() == GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
+ }
+
+ @Override
+ public String toString() {
+ return "ConnectionPool[" + connection + "]";
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/GenericResourceManager.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/GenericResourceManager.java b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/GenericResourceManager.java
new file mode 100644
index 0000000..b903906
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/GenericResourceManager.java
@@ -0,0 +1,194 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import java.io.IOException;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.XAConnection;
+import javax.jms.XAConnectionFactory;
+import javax.jms.XASession;
+import javax.transaction.SystemException;
+import javax.transaction.TransactionManager;
+
+import javax.transaction.xa.XAResource;
+import org.apache.geronimo.transaction.manager.NamedXAResourceFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.apache.geronimo.transaction.manager.RecoverableTransactionManager;
+import org.apache.geronimo.transaction.manager.NamedXAResource;
+import org.apache.geronimo.transaction.manager.WrapperNamedXAResource;
+
+
+/**
+ * This class allows wiring the ActiveMQ broker and the Geronimo transaction manager
+ * in a way that will allow the transaction manager to correctly recover XA transactions.
+ *
+ * For example, it can be used the following way:
+ * <pre>
+ * <bean id="activemqConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
+ * <property name="brokerURL" value="tcp://localhost:61616" />
+ * </bean>
+ *
+ * <bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactoryFactoryBean">
+ * <property name="maxConnections" value="8" />
+ * <property name="transactionManager" ref="transactionManager" />
+ * <property name="connectionFactory" ref="activemqConnectionFactory" />
+ * <property name="resourceName" value="activemq.broker" />
+ * </bean>
+ *
+ * <bean id="resourceManager" class="org.apache.activemq.jms.pool.GenericResourceManager" init-method="recoverResource">
+ * <property name="transactionManager" ref="transactionManager" />
+ * <property name="connectionFactory" ref="activemqConnectionFactory" />
+ * <property name="resourceName" value="activemq.broker" />
+ * </bean>
+ * </pre>
+ */
+public class GenericResourceManager {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(GenericResourceManager.class);
+
+ private String resourceName;
+
+ private String userName;
+ private String password;
+
+ private TransactionManager transactionManager;
+
+ private ConnectionFactory connectionFactory;
+
+ public void recoverResource() {
+ try {
+ if (!Recovery.recover(this)) {
+ LOGGER.info("Resource manager is unrecoverable");
+ }
+ } catch (NoClassDefFoundError e) {
+ LOGGER.info("Resource manager is unrecoverable due to missing classes: " + e);
+ } catch (Throwable e) {
+ LOGGER.warn("Error while recovering resource manager", e);
+ }
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ public String getUserName() {
+ return userName;
+ }
+
+ public void setUserName(String userName) {
+ this.userName = userName;
+ }
+
+ public String getResourceName() {
+ return resourceName;
+ }
+
+ public void setResourceName(String resourceName) {
+ this.resourceName = resourceName;
+ }
+
+ public TransactionManager getTransactionManager() {
+ return transactionManager;
+ }
+
+ public void setTransactionManager(TransactionManager transactionManager) {
+ this.transactionManager = transactionManager;
+ }
+
+ public ConnectionFactory getConnectionFactory() {
+ return connectionFactory;
+ }
+
+ public void setConnectionFactory(ConnectionFactory connectionFactory) {
+ this.connectionFactory = connectionFactory;
+ }
+
+ /**
+ * This class will ensure the broker is properly recovered when wired with
+ * the Geronimo transaction manager.
+ */
+ public static class Recovery {
+
+ public static boolean isRecoverable(GenericResourceManager rm) {
+ return rm.getConnectionFactory() instanceof XAConnectionFactory &&
+ rm.getTransactionManager() instanceof RecoverableTransactionManager &&
+ rm.getResourceName() != null && !"".equals(rm.getResourceName());
+ }
+
+ public static boolean recover(final GenericResourceManager rm) throws IOException {
+ if (isRecoverable(rm)) {
+ final XAConnectionFactory connFactory = (XAConnectionFactory) rm.getConnectionFactory();
+
+ RecoverableTransactionManager rtxManager = (RecoverableTransactionManager) rm.getTransactionManager();
+ rtxManager.registerNamedXAResourceFactory(new NamedXAResourceFactory() {
+
+ @Override
+ public String getName() {
+ return rm.getResourceName();
+ }
+
+ @Override
+ public NamedXAResource getNamedXAResource() throws SystemException {
+ try {
+ final XAConnection xaConnection = connFactory.createXAConnection(rm.getUserName(), rm.getPassword());
+ final XASession session = xaConnection.createXASession();
+ xaConnection.start();
+ LOGGER.debug("new namedXAResource's connection: " + xaConnection);
+
+ return new ConnectionAndWrapperNamedXAResource(session.getXAResource(), getName(), xaConnection);
+ } catch (Exception e) {
+ SystemException se = new SystemException("Failed to create ConnectionAndWrapperNamedXAResource, " + e.getLocalizedMessage());
+ se.initCause(e);
+ LOGGER.error(se.getLocalizedMessage(), se);
+ throw se;
+ }
+ }
+
+ @Override
+ public void returnNamedXAResource(NamedXAResource namedXaResource) {
+ if (namedXaResource instanceof ConnectionAndWrapperNamedXAResource) {
+ try {
+ LOGGER.debug("closing returned namedXAResource's connection: " + ((ConnectionAndWrapperNamedXAResource)namedXaResource).connection);
+ ((ConnectionAndWrapperNamedXAResource)namedXaResource).connection.close();
+ } catch (Exception ignored) {
+ LOGGER.debug("failed to close returned namedXAResource: " + namedXaResource, ignored);
+ }
+ }
+ }
+ });
+ return true;
+ } else {
+ return false;
+ }
+ }
+ }
+
+ public static class ConnectionAndWrapperNamedXAResource extends WrapperNamedXAResource {
+ final Connection connection;
+ public ConnectionAndWrapperNamedXAResource(XAResource xaResource, String name, Connection connection) {
+ super(xaResource, name);
+ this.connection = connection;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/IntrospectionSupport.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/IntrospectionSupport.java b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/IntrospectionSupport.java
new file mode 100755
index 0000000..a86fe64
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/IntrospectionSupport.java
@@ -0,0 +1,118 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import java.lang.reflect.Method;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import javax.net.ssl.SSLServerSocket;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public final class IntrospectionSupport {
+
+ private static final Logger LOG = LoggerFactory.getLogger(IntrospectionSupport.class);
+
+ private IntrospectionSupport() {
+ }
+
+ public static boolean setProperties(Object target, Map props) {
+ boolean rc = false;
+
+ if (target == null) {
+ throw new IllegalArgumentException("target was null.");
+ }
+ if (props == null) {
+ throw new IllegalArgumentException("props was null.");
+ }
+
+ for (Iterator<?> iter = props.entrySet().iterator(); iter.hasNext();) {
+ Entry<?,?> entry = (Entry<?,?>)iter.next();
+ if (setProperty(target, (String)entry.getKey(), entry.getValue())) {
+ iter.remove();
+ rc = true;
+ }
+ }
+
+ return rc;
+ }
+
+ public static boolean setProperty(Object target, String name, Object value) {
+ try {
+ Class<?> clazz = target.getClass();
+ if (target instanceof SSLServerSocket) {
+ // overcome illegal access issues with internal implementation class
+ clazz = SSLServerSocket.class;
+ }
+ Method setter = findSetterMethod(clazz, name);
+ if (setter == null) {
+ return false;
+ }
+
+ // If the type is null or it matches the needed type, just use the
+ // value directly
+ if (value == null || value.getClass() == setter.getParameterTypes()[0]) {
+ setter.invoke(target, value);
+ } else {
+ // We need to convert it
+ setter.invoke(target, convert(value, setter.getParameterTypes()[0]));
+ }
+ return true;
+ } catch (Exception e) {
+ LOG.error(String.format("Could not set property %s on %s", name, target), e);
+ return false;
+ }
+ }
+
+ private static Object convert(Object value, Class to) {
+ if (value == null) {
+ // lets avoid NullPointerException when converting to boolean for null values
+ if (boolean.class.isAssignableFrom(to)) {
+ return Boolean.FALSE;
+ }
+ return null;
+ }
+
+ // eager same instance type test to avoid the overhead of invoking the type converter
+ // if already same type
+ if (to.isAssignableFrom(value.getClass())) {
+ return to.cast(value);
+ }
+
+ if (boolean.class.isAssignableFrom(to) && value instanceof String) {
+ return Boolean.valueOf((String)value);
+ }
+
+ throw new IllegalArgumentException("Cannot convert from " + value.getClass()
+ + " to " + to + " with value " + value);
+ }
+
+ private static Method findSetterMethod(Class clazz, String name) {
+ // Build the method name.
+ name = "set" + Character.toUpperCase(name.charAt(0)) + name.substring(1);
+ Method[] methods = clazz.getMethods();
+ for (Method method : methods) {
+ Class<?> params[] = method.getParameterTypes();
+ if (method.getName().equals(name) && params.length == 1 ) {
+ return method;
+ }
+ }
+ return null;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/JcaConnectionPool.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/JcaConnectionPool.java b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/JcaConnectionPool.java
new file mode 100644
index 0000000..80ec2b9
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/JcaConnectionPool.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2006 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import javax.jms.Connection;
+import javax.jms.JMSException;
+import javax.jms.XASession;
+import javax.transaction.TransactionManager;
+import javax.transaction.xa.XAResource;
+
+import org.apache.geronimo.transaction.manager.WrapperNamedXAResource;
+
+public class JcaConnectionPool extends XaConnectionPool {
+
+ private final String name;
+
+ public JcaConnectionPool(Connection connection, TransactionManager transactionManager, String name) {
+ super(connection, transactionManager);
+ this.name = name;
+ }
+
+ @Override
+ protected XAResource createXaResource(PooledSession session) throws JMSException {
+ XAResource xares = ((XASession)session.getInternalSession()).getXAResource();
+ if (name != null) {
+ xares = new WrapperNamedXAResource(xares, name);
+ }
+ return xares;
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/JcaPooledConnectionFactory.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/JcaPooledConnectionFactory.java b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/JcaPooledConnectionFactory.java
new file mode 100644
index 0000000..901faa4
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/JcaPooledConnectionFactory.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2006 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import javax.jms.Connection;
+
+public class JcaPooledConnectionFactory extends XaPooledConnectionFactory {
+
+ private String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ protected ConnectionPool createConnectionPool(Connection connection) {
+ return new JcaConnectionPool(connection, getTransactionManager(), getName());
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledConnection.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledConnection.java b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledConnection.java
new file mode 100755
index 0000000..b268862
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledConnection.java
@@ -0,0 +1,286 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionConsumer;
+import javax.jms.ConnectionMetaData;
+import javax.jms.Destination;
+import javax.jms.ExceptionListener;
+import javax.jms.JMSException;
+import javax.jms.Queue;
+import javax.jms.QueueConnection;
+import javax.jms.QueueSession;
+import javax.jms.ServerSessionPool;
+import javax.jms.Session;
+import javax.jms.TemporaryQueue;
+import javax.jms.TemporaryTopic;
+import javax.jms.Topic;
+import javax.jms.TopicConnection;
+import javax.jms.TopicSession;
+import javax.jms.IllegalStateException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Represents a proxy {@link Connection} which is-a {@link TopicConnection} and
+ * {@link QueueConnection} which is pooled and on {@link #close()} will return
+ * its reference to the ConnectionPool backing it.
+ *
+ * <b>NOTE</b> this implementation is only intended for use when sending
+ * messages. It does not deal with pooling of consumers; for that look at a
+ * library like <a href="http://jencks.org/">Jencks</a> such as in <a
+ * href="http://jencks.org/Message+Driven+POJOs">this example</a>
+ *
+ */
+public class PooledConnection implements TopicConnection, QueueConnection, PooledSessionEventListener {
+ private static final transient Logger LOG = LoggerFactory.getLogger(PooledConnection.class);
+
+ protected ConnectionPool pool;
+ private volatile boolean stopped;
+ private final List<TemporaryQueue> connTempQueues = new CopyOnWriteArrayList<TemporaryQueue>();
+ private final List<TemporaryTopic> connTempTopics = new CopyOnWriteArrayList<TemporaryTopic>();
+ private final List<PooledSession> loanedSessions = new CopyOnWriteArrayList<PooledSession>();
+
+ /**
+ * Creates a new PooledConnection instance that uses the given ConnectionPool to create
+ * and manage its resources. The ConnectionPool instance can be shared amongst many
+ * PooledConnection instances.
+ *
+ * @param pool
+ * The connection and pool manager backing this proxy connection object.
+ */
+ public PooledConnection(ConnectionPool pool) {
+ this.pool = pool;
+ }
+
+ /**
+ * Factory method to create a new instance.
+ */
+ public PooledConnection newInstance() {
+ return new PooledConnection(pool);
+ }
+
+ @Override
+ public void close() throws JMSException {
+ this.cleanupConnectionTemporaryDestinations();
+ this.cleanupAllLoanedSessions();
+ if (this.pool != null) {
+ this.pool.decrementReferenceCount();
+ this.pool = null;
+ }
+ }
+
+ @Override
+ public void start() throws JMSException {
+ assertNotClosed();
+ pool.start();
+ }
+
+ @Override
+ public void stop() throws JMSException {
+ stopped = true;
+ }
+
+ @Override
+ public ConnectionConsumer createConnectionConsumer(Destination destination, String selector, ServerSessionPool serverSessionPool, int maxMessages) throws JMSException {
+ return getConnection().createConnectionConsumer(destination, selector, serverSessionPool, maxMessages);
+ }
+
+ @Override
+ public ConnectionConsumer createConnectionConsumer(Topic topic, String s, ServerSessionPool serverSessionPool, int maxMessages) throws JMSException {
+ return getConnection().createConnectionConsumer(topic, s, serverSessionPool, maxMessages);
+ }
+
+ @Override
+ public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String selector, String s1, ServerSessionPool serverSessionPool, int i) throws JMSException {
+ return getConnection().createDurableConnectionConsumer(topic, selector, s1, serverSessionPool, i);
+ }
+
+ @Override
+ public String getClientID() throws JMSException {
+ return getConnection().getClientID();
+ }
+
+ @Override
+ public ExceptionListener getExceptionListener() throws JMSException {
+ return getConnection().getExceptionListener();
+ }
+
+ @Override
+ public ConnectionMetaData getMetaData() throws JMSException {
+ return getConnection().getMetaData();
+ }
+
+ @Override
+ public void setExceptionListener(ExceptionListener exceptionListener) throws JMSException {
+ getConnection().setExceptionListener(exceptionListener);
+ }
+
+ @Override
+ public void setClientID(String clientID) throws JMSException {
+ // ignore repeated calls to setClientID() with the same client id
+ // this could happen when a JMS component such as Spring that uses a
+ // PooledConnectionFactory shuts down and reinitializes.
+ if (this.getConnection().getClientID() == null || !this.getClientID().equals(clientID)) {
+ getConnection().setClientID(clientID);
+ }
+ }
+
+ @Override
+ public ConnectionConsumer createConnectionConsumer(Queue queue, String selector, ServerSessionPool serverSessionPool, int maxMessages) throws JMSException {
+ return getConnection().createConnectionConsumer(queue, selector, serverSessionPool, maxMessages);
+ }
+
+ // Session factory methods
+ // -------------------------------------------------------------------------
+ @Override
+ public QueueSession createQueueSession(boolean transacted, int ackMode) throws JMSException {
+ return (QueueSession) createSession(transacted, ackMode);
+ }
+
+ @Override
+ public TopicSession createTopicSession(boolean transacted, int ackMode) throws JMSException {
+ return (TopicSession) createSession(transacted, ackMode);
+ }
+
+ @Override
+ public Session createSession(boolean transacted, int ackMode) throws JMSException {
+ PooledSession result;
+ result = (PooledSession) pool.createSession(transacted, ackMode);
+
+ // Store the session so we can close the sessions that this PooledConnection
+ // created in order to ensure that consumers etc are closed per the JMS contract.
+ loanedSessions.add(result);
+
+ // Add a event listener to the session that notifies us when the session
+ // creates / destroys temporary destinations and closes etc.
+ result.addSessionEventListener(this);
+ return result;
+ }
+
+ // Implementation methods
+ // -------------------------------------------------------------------------
+
+ @Override
+ public void onTemporaryQueueCreate(TemporaryQueue tempQueue) {
+ connTempQueues.add(tempQueue);
+ }
+
+ @Override
+ public void onTemporaryTopicCreate(TemporaryTopic tempTopic) {
+ connTempTopics.add(tempTopic);
+ }
+
+ @Override
+ public void onSessionClosed(PooledSession session) {
+ if (session != null) {
+ this.loanedSessions.remove(session);
+ }
+ }
+
+ public Connection getConnection() throws JMSException {
+ assertNotClosed();
+ return pool.getConnection();
+ }
+
+ protected void assertNotClosed() throws javax.jms.IllegalStateException {
+ if (stopped || pool == null) {
+ throw new IllegalStateException("Connection closed");
+ }
+ }
+
+ protected Session createSession(SessionKey key) throws JMSException {
+ return getConnection().createSession(key.isTransacted(), key.getAckMode());
+ }
+
+ @Override
+ public String toString() {
+ return "PooledConnection { " + pool + " }";
+ }
+
+ /**
+ * Remove all of the temporary destinations created for this connection.
+ * This is important since the underlying connection may be reused over a
+ * long period of time, accumulating all of the temporary destinations from
+ * each use. However, from the perspective of the lifecycle from the
+ * client's view, close() closes the connection and, therefore, deletes all
+ * of the temporary destinations created.
+ */
+ protected void cleanupConnectionTemporaryDestinations() {
+
+ for (TemporaryQueue tempQueue : connTempQueues) {
+ try {
+ tempQueue.delete();
+ } catch (JMSException ex) {
+ LOG.info("failed to delete Temporary Queue \"" + tempQueue.toString() + "\" on closing pooled connection: " + ex.getMessage());
+ }
+ }
+ connTempQueues.clear();
+
+ for (TemporaryTopic tempTopic : connTempTopics) {
+ try {
+ tempTopic.delete();
+ } catch (JMSException ex) {
+ LOG.info("failed to delete Temporary Topic \"" + tempTopic.toString() + "\" on closing pooled connection: " + ex.getMessage());
+ }
+ }
+ connTempTopics.clear();
+ }
+
+ /**
+ * The PooledSession tracks all Sessions that it created and now we close them. Closing the
+ * PooledSession will return the internal Session to the Pool of Session after cleaning up
+ * all the resources that the Session had allocated for this PooledConnection.
+ */
+ protected void cleanupAllLoanedSessions() {
+
+ for (PooledSession session : loanedSessions) {
+ try {
+ session.close();
+ } catch (JMSException ex) {
+ LOG.info("failed to close laoned Session \"" + session + "\" on closing pooled connection: " + ex.getMessage());
+ }
+ }
+ loanedSessions.clear();
+ }
+
+ /**
+ * @return the total number of Pooled session including idle sessions that are not
+ * currently loaned out to any client.
+ */
+ public int getNumSessions() {
+ return this.pool.getNumSessions();
+ }
+
+ /**
+ * @return the number of Sessions that are currently checked out of this Connection's session pool.
+ */
+ public int getNumActiveSessions() {
+ return this.pool.getNumActiveSessions();
+ }
+
+ /**
+ * @return the number of Sessions that are idle in this Connection's sessions pool.
+ */
+ public int getNumtIdleSessions() {
+ return this.pool.getNumIdleSessions();
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledConnectionFactory.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledConnectionFactory.java b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledConnectionFactory.java
new file mode 100644
index 0000000..bf49f2d
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledConnectionFactory.java
@@ -0,0 +1,479 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.JMSException;
+
+import javax.jms.XAConnectionFactory;
+import org.apache.commons.pool.KeyedPoolableObjectFactory;
+import org.apache.commons.pool.impl.GenericKeyedObjectPool;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A JMS provider which pools Connection, Session and MessageProducer instances
+ * so it can be used with tools like <a href="http://camel.apache.org/activemq.html">Camel</a> and Spring's
+ * <a href="http://activemq.apache.org/spring-support.html">JmsTemplate and MessagListenerContainer</a>.
+ * Connections, sessions and producers are returned to a pool after use so that they can be reused later
+ * without having to undergo the cost of creating them again.
+ *
+ * b>NOTE:</b> while this implementation does allow the creation of a collection of active consumers,
+ * it does not 'pool' consumers. Pooling makes sense for connections, sessions and producers, which
+ * are expensive to create and can remain idle a minimal cost. Consumers, on the other hand, are usually
+ * just created at startup and left active, handling incoming messages as they come. When a consumer is
+ * complete, it is best to close it rather than return it to a pool for later reuse: this is because,
+ * even if a consumer is idle, ActiveMQ will keep delivering messages to the consumer's prefetch buffer,
+ * where they'll get held until the consumer is active again.
+ *
+ * If you are creating a collection of consumers (for example, for multi-threaded message consumption), you
+ * might want to consider using a lower prefetch value for each consumer (e.g. 10 or 20), to ensure that
+ * all messages don't end up going to just one of the consumers. See this FAQ entry for more detail:
+ * http://activemq.apache.org/i-do-not-receive-messages-in-my-second-consumer.html
+ *
+ * Optionally, one may configure the pool to examine and possibly evict objects as they sit idle in the
+ * pool. This is performed by an "idle object eviction" thread, which runs asynchronously. Caution should
+ * be used when configuring this optional feature. Eviction runs contend with client threads for access
+ * to objects in the pool, so if they run too frequently performance issues may result. The idle object
+ * eviction thread may be configured using the {@link org.apache.activemq.jms.pool.PooledConnectionFactory#setTimeBetweenExpirationCheckMillis} method. By
+ * default the value is -1 which means no eviction thread will be run. Set to a non-negative value to
+ * configure the idle eviction thread to run.
+ *
+ */
+public class PooledConnectionFactory implements ConnectionFactory {
+ private static final transient Logger LOG = LoggerFactory.getLogger(PooledConnectionFactory.class);
+
+ protected final AtomicBoolean stopped = new AtomicBoolean(false);
+ private GenericKeyedObjectPool<ConnectionKey, ConnectionPool> connectionsPool;
+
+ private ConnectionFactory connectionFactory;
+
+ private int maximumActiveSessionPerConnection = 500;
+ private int idleTimeout = 30 * 1000;
+ private boolean blockIfSessionPoolIsFull = true;
+ private long expiryTimeout = 0l;
+ private boolean createConnectionOnStartup = true;
+
+
+ public void initConnectionsPool() {
+ if (this.connectionsPool == null) {
+ this.connectionsPool = new GenericKeyedObjectPool<ConnectionKey, ConnectionPool>(
+ new KeyedPoolableObjectFactory<ConnectionKey, ConnectionPool>() {
+
+ @Override
+ public void activateObject(ConnectionKey key, ConnectionPool connection) throws Exception {
+ }
+
+ @Override
+ public void destroyObject(ConnectionKey key, ConnectionPool connection) throws Exception {
+ try {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Destroying connection: {}", connection);
+ }
+ connection.close();
+ } catch (Exception e) {
+ LOG.warn("Close connection failed for connection: " + connection + ". This exception will be ignored.",e);
+ }
+ }
+
+ @Override
+ public ConnectionPool makeObject(ConnectionKey key) throws Exception {
+ Connection delegate = createConnection(key);
+
+ ConnectionPool connection = createConnectionPool(delegate);
+ connection.setIdleTimeout(getIdleTimeout());
+ connection.setExpiryTimeout(getExpiryTimeout());
+ connection.setMaximumActiveSessionPerConnection(getMaximumActiveSessionPerConnection());
+ connection.setBlockIfSessionPoolIsFull(isBlockIfSessionPoolIsFull());
+
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Created new connection: {}", connection);
+ }
+
+ return connection;
+ }
+
+ @Override
+ public void passivateObject(ConnectionKey key, ConnectionPool connection) throws Exception {
+ }
+
+ @Override
+ public boolean validateObject(ConnectionKey key, ConnectionPool connection) {
+ if (connection != null && connection.expiredCheck()) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Connection has expired: {} and will be destroyed", connection);
+ }
+
+ return false;
+ }
+
+ return true;
+ }
+ });
+
+ // Set max idle (not max active) since our connections always idle in the pool.
+ this.connectionsPool.setMaxIdle(1);
+
+ // We always want our validate method to control when idle objects are evicted.
+ this.connectionsPool.setTestOnBorrow(true);
+ this.connectionsPool.setTestWhileIdle(true);
+ }
+ }
+
+ /**
+ * @return the currently configured ConnectionFactory used to create the pooled Connections.
+ */
+ public ConnectionFactory getConnectionFactory() {
+ return connectionFactory;
+ }
+
+ /**
+ * Sets the ConnectionFactory used to create new pooled Connections.
+ * <p/>
+ * Updates to this value do not affect Connections that were previously created and placed
+ * into the pool. In order to allocate new Connections based off this new ConnectionFactory
+ * it is first necessary to {@link clear} the pooled Connections.
+ *
+ * @param toUse
+ * The factory to use to create pooled Connections.
+ */
+ public void setConnectionFactory(final ConnectionFactory toUse) {
+ if (toUse instanceof XAConnectionFactory) {
+ connectionFactory = new ConnectionFactory() {
+ public Connection createConnection() throws JMSException {
+ return ((XAConnectionFactory)toUse).createXAConnection();
+ }
+ public Connection createConnection(String userName, String password) throws JMSException {
+ return ((XAConnectionFactory)toUse).createXAConnection(userName, password);
+ }
+ };
+ } else {
+ this.connectionFactory = toUse;
+ }
+ }
+
+ @Override
+ public Connection createConnection() throws JMSException {
+ return createConnection(null, null);
+ }
+
+ @Override
+ public synchronized Connection createConnection(String userName, String password) throws JMSException {
+ if (stopped.get()) {
+ LOG.debug("PooledConnectionFactory is stopped, skip create new connection.");
+ return null;
+ }
+
+ ConnectionPool connection = null;
+ ConnectionKey key = new ConnectionKey(userName, password);
+
+ // This will either return an existing non-expired ConnectionPool or it
+ // will create a new one to meet the demand.
+ if (getConnectionsPool().getNumIdle(key) < getMaxConnections()) {
+ try {
+ // we want borrowObject to return the one we added.
+ connectionsPool.setLifo(true);
+ connectionsPool.addObject(key);
+ } catch (Exception e) {
+ throw createJmsException("Error while attempting to add new Connection to the pool", e);
+ }
+ } else {
+ // now we want the oldest one in the pool.
+ connectionsPool.setLifo(false);
+ }
+
+ try {
+
+ // We can race against other threads returning the connection when there is an
+ // expiration or idle timeout. We keep pulling out ConnectionPool instances until
+ // we win and get a non-closed instance and then increment the reference count
+ // under lock to prevent another thread from triggering an expiration check and
+ // pulling the rug out from under us.
+ while (connection == null) {
+ connection = connectionsPool.borrowObject(key);
+ synchronized (connection) {
+ if (connection.getConnection() != null) {
+ connection.incrementReferenceCount();
+ break;
+ }
+
+ // Return the bad one to the pool and let if get destroyed as normal.
+ connectionsPool.returnObject(key, connection);
+ connection = null;
+ }
+ }
+ } catch (Exception e) {
+ throw createJmsException("Error while attempting to retrieve a connection from the pool", e);
+ }
+
+ try {
+ connectionsPool.returnObject(key, connection);
+ } catch (Exception e) {
+ throw createJmsException("Error when returning connection to the pool", e);
+ }
+
+ return newPooledConnection(connection);
+ }
+
+ protected Connection newPooledConnection(ConnectionPool connection) {
+ return new PooledConnection(connection);
+ }
+
+ private JMSException createJmsException(String msg, Exception cause) {
+ JMSException exception = new JMSException(msg);
+ exception.setLinkedException(cause);
+ exception.initCause(cause);
+ return exception;
+ }
+
+ protected Connection createConnection(ConnectionKey key) throws JMSException {
+ if (key.getUserName() == null && key.getPassword() == null) {
+ return connectionFactory.createConnection();
+ } else {
+ return connectionFactory.createConnection(key.getUserName(), key.getPassword());
+ }
+ }
+
+ public void start() {
+ LOG.debug("Staring the PooledConnectionFactory: create on start = {}", isCreateConnectionOnStartup());
+ stopped.set(false);
+ if (isCreateConnectionOnStartup()) {
+ try {
+ // warm the pool by creating a connection during startup
+ createConnection();
+ } catch (JMSException e) {
+ LOG.warn("Create pooled connection during start failed. This exception will be ignored.", e);
+ }
+ }
+ }
+
+ public void stop() {
+ if (stopped.compareAndSet(false, true)) {
+ LOG.debug("Stopping the PooledConnectionFactory, number of connections in cache: {}",
+ connectionsPool != null ? connectionsPool.getNumActive() : 0);
+ try {
+ if (connectionsPool != null) {
+ connectionsPool.close();
+ }
+ } catch (Exception e) {
+ }
+ }
+ }
+
+ /**
+ * Clears all connections from the pool. Each connection that is currently in the pool is
+ * closed and removed from the pool. A new connection will be created on the next call to
+ * {@link createConnection}. Care should be taken when using this method as Connections that
+ * are in use be client's will be closed.
+ */
+ public void clear() {
+
+ if (stopped.get()) {
+ return;
+ }
+
+ getConnectionsPool().clear();
+ }
+
+ /**
+ * Returns the currently configured maximum number of sessions a pooled Connection will
+ * create before it either blocks or throws an exception when a new session is requested,
+ * depending on configuration.
+ *
+ * @return the number of session instances that can be taken from a pooled connection.
+ */
+ public int getMaximumActiveSessionPerConnection() {
+ return maximumActiveSessionPerConnection;
+ }
+
+ /**
+ * Sets the maximum number of active sessions per connection
+ *
+ * @param maximumActiveSessionPerConnection
+ * The maximum number of active session per connection in the pool.
+ */
+ public void setMaximumActiveSessionPerConnection(int maximumActiveSessionPerConnection) {
+ this.maximumActiveSessionPerConnection = maximumActiveSessionPerConnection;
+ }
+
+ /**
+ * Controls the behavior of the internal session pool. By default the call to
+ * Connection.getSession() will block if the session pool is full. If the
+ * argument false is given, it will change the default behavior and instead the
+ * call to getSession() will throw a JMSException.
+ *
+ * The size of the session pool is controlled by the @see #maximumActive
+ * property.
+ *
+ * @param block - if true, the call to getSession() blocks if the pool is full
+ * until a session object is available. defaults to true.
+ */
+ public void setBlockIfSessionPoolIsFull(boolean block) {
+ this.blockIfSessionPoolIsFull = block;
+ }
+
+ /**
+ * Returns whether a pooled Connection will enter a blocked state or will throw an Exception
+ * once the maximum number of sessions has been borrowed from the the Session Pool.
+ *
+ * @return true if the pooled Connection createSession method will block when the limit is hit.
+ * @see setBlockIfSessionPoolIsFull
+ */
+ public boolean isBlockIfSessionPoolIsFull() {
+ return this.blockIfSessionPoolIsFull;
+ }
+
+ /**
+ * Returns the maximum number to pooled Connections that this factory will allow before it
+ * begins to return connections from the pool on calls to ({@link createConnection}.
+ *
+ * @return the maxConnections that will be created for this pool.
+ */
+ public int getMaxConnections() {
+ return getConnectionsPool().getMaxIdle();
+ }
+
+ /**
+ * Sets the maximum number of pooled Connections (defaults to one). Each call to
+ * {@link createConnection} will result in a new Connection being create up to the max
+ * connections value.
+ *
+ * @param maxConnections the maxConnections to set
+ */
+ public void setMaxConnections(int maxConnections) {
+ getConnectionsPool().setMaxIdle(maxConnections);
+ }
+
+ /**
+ * Gets the Idle timeout value applied to new Connection's that are created by this pool.
+ * <p/>
+ * The idle timeout is used determine if a Connection instance has sat to long in the pool unused
+ * and if so is closed and removed from the pool. The default value is 30 seconds.
+ *
+ * @return idle timeout value (milliseconds)
+ */
+ public int getIdleTimeout() {
+ return idleTimeout;
+ }
+
+ /**
+ * Sets the idle timeout value for Connection's that are created by this pool in Milliseconds,
+ * defaults to 30 seconds.
+ * <p/>
+ * For a Connection that is in the pool but has no current users the idle timeout determines how
+ * long the Connection can live before it is eligible for removal from the pool. Normally the
+ * connections are tested when an attempt to check one out occurs so a Connection instance can sit
+ * in the pool much longer than its idle timeout if connections are used infrequently.
+ *
+ * @param idleTimeout
+ * The maximum time a pooled Connection can sit unused before it is eligible for removal.
+ */
+ public void setIdleTimeout(int idleTimeout) {
+ this.idleTimeout = idleTimeout;
+ }
+
+ /**
+ * allow connections to expire, irrespective of load or idle time. This is useful with failover
+ * to force a reconnect from the pool, to reestablish load balancing or use of the master post recovery
+ *
+ * @param expiryTimeout non zero in milliseconds
+ */
+ public void setExpiryTimeout(long expiryTimeout) {
+ this.expiryTimeout = expiryTimeout;
+ }
+
+ /**
+ * @return the configured expiration timeout for connections in the pool.
+ */
+ public long getExpiryTimeout() {
+ return expiryTimeout;
+ }
+
+ /**
+ * @return true if a Connection is created immediately on a call to {@link start}.
+ */
+ public boolean isCreateConnectionOnStartup() {
+ return createConnectionOnStartup;
+ }
+
+ /**
+ * Whether to create a connection on starting this {@link PooledConnectionFactory}.
+ * <p/>
+ * This can be used to warm-up the pool on startup. Notice that any kind of exception
+ * happens during startup is logged at WARN level and ignored.
+ *
+ * @param createConnectionOnStartup <tt>true</tt> to create a connection on startup
+ */
+ public void setCreateConnectionOnStartup(boolean createConnectionOnStartup) {
+ this.createConnectionOnStartup = createConnectionOnStartup;
+ }
+
+ /**
+ * Gets the Pool of ConnectionPool instances which are keyed by different ConnectionKeys.
+ *
+ * @return this factories pool of ConnectionPool instances.
+ */
+ protected GenericKeyedObjectPool<ConnectionKey, ConnectionPool> getConnectionsPool() {
+ initConnectionsPool();
+ return this.connectionsPool;
+ }
+
+ /**
+ * Sets the number of milliseconds to sleep between runs of the idle Connection eviction thread.
+ * When non-positive, no idle object eviction thread will be run, and Connections will only be
+ * checked on borrow to determine if they have sat idle for too long or have failed for some
+ * other reason.
+ * <p/>
+ * By default this value is set to -1 and no expiration thread ever runs.
+ *
+ * @param timeBetweenExpirationCheckMillis
+ * The time to wait between runs of the idle Connection eviction thread.
+ */
+ public void setTimeBetweenExpirationCheckMillis(long timeBetweenExpirationCheckMillis) {
+ getConnectionsPool().setTimeBetweenEvictionRunsMillis(timeBetweenExpirationCheckMillis);
+ }
+
+ /**
+ * @return the number of milliseconds to sleep between runs of the idle connection eviction thread.
+ */
+ public long getTimeBetweenExpirationCheckMillis() {
+ return getConnectionsPool().getTimeBetweenEvictionRunsMillis();
+ }
+
+ /**
+ * @return the number of Connections currently in the Pool
+ */
+ public int getNumConnections() {
+ return getConnectionsPool().getNumIdle();
+ }
+
+ /**
+ * Delegate that creates each instance of an ConnectionPool object. Subclasses can override
+ * this method to customize the type of connection pool returned.
+ *
+ * @param connection
+ *
+ * @return instance of a new ConnectionPool.
+ */
+ protected ConnectionPool createConnectionPool(Connection connection) {
+ return new ConnectionPool(connection);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledMessageConsumer.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledMessageConsumer.java b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledMessageConsumer.java
new file mode 100644
index 0000000..3d8b6c5
--- /dev/null
+++ b/activemq-jms-pool/src/main/java/org/apache/activemq/jms/pool/PooledMessageConsumer.java
@@ -0,0 +1,84 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+
+/**
+ * A {@link MessageConsumer} which was created by {@link PooledSession}.
+ */
+public class PooledMessageConsumer implements MessageConsumer {
+
+ private final PooledSession session;
+ private final MessageConsumer delegate;
+
+ /**
+ * Wraps the message consumer.
+ *
+ * @param session the pooled session
+ * @param delegate the created consumer to wrap
+ */
+ public PooledMessageConsumer(PooledSession session, MessageConsumer delegate) {
+ this.session = session;
+ this.delegate = delegate;
+ }
+
+ @Override
+ public void close() throws JMSException {
+ // ensure session removes consumer as its closed now
+ session.onConsumerClose(delegate);
+ delegate.close();
+ }
+
+ @Override
+ public MessageListener getMessageListener() throws JMSException {
+ return delegate.getMessageListener();
+ }
+
+ @Override
+ public String getMessageSelector() throws JMSException {
+ return delegate.getMessageSelector();
+ }
+
+ @Override
+ public Message receive() throws JMSException {
+ return delegate.receive();
+ }
+
+ @Override
+ public Message receive(long timeout) throws JMSException {
+ return delegate.receive(timeout);
+ }
+
+ @Override
+ public Message receiveNoWait() throws JMSException {
+ return delegate.receiveNoWait();
+ }
+
+ @Override
+ public void setMessageListener(MessageListener listener) throws JMSException {
+ delegate.setMessageListener(listener);
+ }
+
+ @Override
+ public String toString() {
+ return "PooledMessageConsumer { " + delegate + " }";
+ }
+}
[2/6] https://issues.apache.org/jira/browse/AMQ-4757
activemq-jms-pool a generic jms xa pool derived from activemq-pool which
activemq-pool now extends with amq specifics
Posted by gt...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/package.html
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/package.html b/activemq-pool/src/main/java/org/apache/activemq/pool/package.html
deleted file mode 100755
index 8eb8f0c..0000000
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/package.html
+++ /dev/null
@@ -1,28 +0,0 @@
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<html>
-<head>
-</head>
-<body>
-
-A JMS provider which pools Connection, Session and MessageProducer instances so it can be used with tools like
-Spring's <a href="http://activemq.org/Spring+Support">JmsTemplate</a>. <b>Note</b> that this package
-does not deal with pooling of consumers; for that look at a library like <a href="http://jencks.org/">Jencks</a>
-such as in <a href="http://jencks.org/Message+Driven+POJOs">this example</a>
-
-</body>
-</html>
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/test/java/org/apache/activemq/pool/ConnectionExpiryEvictsFromPoolTest.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/test/java/org/apache/activemq/pool/ConnectionExpiryEvictsFromPoolTest.java b/activemq-pool/src/test/java/org/apache/activemq/pool/ConnectionExpiryEvictsFromPoolTest.java
deleted file mode 100644
index 3f66ece..0000000
--- a/activemq-pool/src/test/java/org/apache/activemq/pool/ConnectionExpiryEvictsFromPoolTest.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-import java.util.concurrent.TimeUnit;
-
-import javax.jms.Connection;
-import javax.jms.Session;
-
-import org.apache.activemq.ActiveMQConnection;
-import org.apache.activemq.ActiveMQConnectionFactory;
-import org.apache.activemq.broker.BrokerService;
-import org.apache.activemq.broker.TransportConnector;
-import org.apache.activemq.test.TestSupport;
-
-public class ConnectionExpiryEvictsFromPoolTest extends TestSupport {
-
- private BrokerService broker;
- private ActiveMQConnectionFactory factory;
- private PooledConnectionFactory pooledFactory;
-
- @Override
- protected void setUp() throws Exception {
- broker = new BrokerService();
- broker.setUseJmx(false);
- broker.setPersistent(false);
- TransportConnector connector = broker.addConnector("tcp://localhost:0");
- broker.start();
- factory = new ActiveMQConnectionFactory("mock:" + connector.getConnectUri());
- pooledFactory = new PooledConnectionFactory(factory);
- pooledFactory.setMaxConnections(1);
- }
-
- public void testEvictionOfIdle() throws Exception {
- pooledFactory.setIdleTimeout(10);
- PooledConnection connection = (PooledConnection) pooledFactory.createConnection();
- ActiveMQConnection amq1 = connection.getConnection();
-
- connection.close();
- // let it idle timeout
- TimeUnit.SECONDS.sleep(1);
-
- PooledConnection connection2 = (PooledConnection) pooledFactory.createConnection();
- ActiveMQConnection amq2 = connection2.getConnection();
- assertTrue("not equal", !amq1.equals(amq2));
- }
-
- public void testEvictionOfExpired() throws Exception {
- pooledFactory.setExpiryTimeout(10);
- Connection connection = pooledFactory.createConnection();
- ActiveMQConnection amq1 = ((PooledConnection) connection).getConnection();
-
- // let it expire while in use
- TimeUnit.SECONDS.sleep(1);
- connection.close();
-
- Connection connection2 = pooledFactory.createConnection();
- ActiveMQConnection amq2 = ((PooledConnection) connection2).getConnection();
- assertTrue("not equal", !amq1.equals(amq2));
- }
-
- public void testNotIdledWhenInUse() throws Exception {
- pooledFactory.setIdleTimeout(10);
- PooledConnection connection = (PooledConnection) pooledFactory.createConnection();
- Session s = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- // let connection to get idle
- TimeUnit.SECONDS.sleep(1);
-
- // get a connection from pool again, it should be the same underlying connection
- // as before and should not be idled out since an open session exists.
- PooledConnection connection2 = (PooledConnection) pooledFactory.createConnection();
- assertSame(connection.getConnection(), connection2.getConnection());
-
- // now the session is closed even when it should not be
- try {
- // any operation on session first checks whether session is closed
- s.getTransacted();
- } catch (javax.jms.IllegalStateException e) {
- assertTrue("Session should be fine, instead: " + e.getMessage(), false);
- }
-
- ActiveMQConnection original = connection.getConnection();
-
- connection.close();
- connection2.close();
-
- // let connection to get idle
- TimeUnit.SECONDS.sleep(1);
-
- // get a connection from pool again, it should be a new Connection instance as the
- // old one should have been inactive and idled out.
- PooledConnection connection3 = (PooledConnection) pooledFactory.createConnection();
- assertNotSame(original, connection3.getConnection());
- }
-
- @Override
- protected void tearDown() throws Exception {
- broker.stop();
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/test/java/org/apache/activemq/pool/ConnectionFailureEvictsFromPoolTest.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/test/java/org/apache/activemq/pool/ConnectionFailureEvictsFromPoolTest.java b/activemq-pool/src/test/java/org/apache/activemq/pool/ConnectionFailureEvictsFromPoolTest.java
index c02eb18..8c07111 100644
--- a/activemq-pool/src/test/java/org/apache/activemq/pool/ConnectionFailureEvictsFromPoolTest.java
+++ b/activemq-pool/src/test/java/org/apache/activemq/pool/ConnectionFailureEvictsFromPoolTest.java
@@ -21,15 +21,21 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
+import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
+import org.apache.activemq.ActiveMQXAConnectionFactory;
+import org.apache.activemq.EnhancedConnection;
+import org.apache.activemq.advisory.DestinationSource;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.command.ActiveMQQueue;
+import org.apache.activemq.jms.pool.PooledConnection;
import org.apache.activemq.test.TestSupport;
import org.apache.activemq.transport.TransportListener;
import org.apache.activemq.transport.mock.MockTransport;
@@ -39,22 +45,44 @@ import org.slf4j.LoggerFactory;
public class ConnectionFailureEvictsFromPoolTest extends TestSupport {
private static final Logger LOG = LoggerFactory.getLogger(ConnectionFailureEvictsFromPoolTest.class);
private BrokerService broker;
- private ActiveMQConnectionFactory factory;
- private PooledConnectionFactory pooledFactory;
+ TransportConnector connector;
protected void setUp() throws Exception {
broker = new BrokerService();
broker.setUseJmx(false);
broker.setPersistent(false);
- TransportConnector connector = broker.addConnector("tcp://localhost:0");
+ connector = broker.addConnector("tcp://localhost:0");
broker.start();
- factory = new ActiveMQConnectionFactory("mock:" + connector.getConnectUri() + "?closeAsync=false");
- pooledFactory = new PooledConnectionFactory(factory);
+ }
+
+ public void testEnhancedConnection() throws Exception {
+ XaPooledConnectionFactory pooledFactory =
+ new XaPooledConnectionFactory(new ActiveMQXAConnectionFactory("mock:" + connector.getConnectUri() + "?closeAsync=false"));
+
+ PooledConnection connection = (PooledConnection) pooledFactory.createConnection();
+ EnhancedConnection enhancedConnection = (EnhancedConnection)connection.getConnection();
+ DestinationSource destinationSource = enhancedConnection.getDestinationSource();
+ assertNotNull(destinationSource);
+
+ }
+
+ public void testEvictionXA() throws Exception {
+ XaPooledConnectionFactory pooledFactory =
+ new XaPooledConnectionFactory(new ActiveMQXAConnectionFactory("mock:" + connector.getConnectUri() + "?closeAsync=false"));
+
+ doTestEviction(pooledFactory);
}
public void testEviction() throws Exception {
+ PooledConnectionFactory pooledFactory =
+ new PooledConnectionFactory(new ActiveMQConnectionFactory("mock:" + connector.getConnectUri() + "?closeAsync=false"));
+
+ doTestEviction(pooledFactory);
+ }
+
+ public void doTestEviction(ConnectionFactory pooledFactory) throws Exception {
PooledConnection connection = (PooledConnection) pooledFactory.createConnection();
- ActiveMQConnection amqC = connection.getConnection();
+ ActiveMQConnection amqC = (ActiveMQConnection) connection.getConnection();
final CountDownLatch gotExceptionEvent = new CountDownLatch(1);
amqC.addTransportListener(new TransportListener() {
public void onCommand(Object command) {
@@ -75,12 +103,12 @@ public class ConnectionFailureEvictsFromPoolTest extends TestSupport {
createConnectionFailure(connection);
try {
sendMessage(connection);
- fail("Expected Error");
+ TestCase.fail("Expected Error");
} catch (JMSException e) {
} finally {
connection.close();
}
- assertTrue("exception event propagated ok", gotExceptionEvent.await(5, TimeUnit.SECONDS));
+ TestCase.assertTrue("exception event propagated ok", gotExceptionEvent.await(5, TimeUnit.SECONDS));
// If we get another connection now it should be a new connection that
// works.
LOG.info("expect new connection after failure");
@@ -89,7 +117,7 @@ public class ConnectionFailureEvictsFromPoolTest extends TestSupport {
}
private void createConnectionFailure(Connection connection) throws Exception {
- ActiveMQConnection c = ((PooledConnection)connection).getConnection();
+ ActiveMQConnection c = (ActiveMQConnection) ((PooledConnection)connection).getConnection();
MockTransport t = (MockTransport)c.getTransportChannel().narrow(MockTransport.class);
t.onException(new IOException("forcing exception for " + getName() + " to force pool eviction"));
LOG.info("arranged for failure, chucked exception");
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionFactoryMaximumActiveTest.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionFactoryMaximumActiveTest.java b/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionFactoryMaximumActiveTest.java
deleted file mode 100644
index 8c01c39..0000000
--- a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionFactoryMaximumActiveTest.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-import java.util.concurrent.Callable;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Session;
-
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-
-import org.apache.activemq.ActiveMQConnectionFactory;
-import org.apache.log4j.Logger;
-
-/**
- * Checks the behavior of the PooledConnectionFactory when the maximum amount of sessions is being reached
- * (maximumActive). When using setBlockIfSessionPoolIsFull(true) on the ConnectionFactory, further requests for sessions
- * should block. If it does not block, its a bug.
- *
- * @author: tmielke
- */
-public class PooledConnectionFactoryMaximumActiveTest extends TestCase {
- public final static Logger LOG = Logger.getLogger(PooledConnectionFactoryMaximumActiveTest.class);
- public static Connection conn = null;
- public static int sleepTimeout = 5000;
-
- private static ConcurrentHashMap<Integer, Session> sessions = new ConcurrentHashMap<Integer, Session>();
-
- /**
- * Create the test case
- *
- * @param testName
- * name of the test case
- */
- public PooledConnectionFactoryMaximumActiveTest(String testName) {
- super(testName);
- }
-
- public static void addSession(Session s) {
- sessions.put(s.hashCode(), s);
- }
-
- /**
- * @return the suite of tests being tested
- */
- public static Test suite() {
- return new TestSuite(PooledConnectionFactoryMaximumActiveTest.class);
- }
-
- /**
- * Tests the behavior of the sessionPool of the PooledConnectionFactory when maximum number of sessions are reached.
- * This test uses maximumActive=1. When creating two threads that both try to create a JMS session from the same JMS
- * connection, the thread that is second to call createSession() should block (as only 1 session is allowed) until
- * the session is returned to pool. If it does not block, its a bug.
- *
- */
- public void testApp() throws Exception {
- // Initialize JMS connection
- ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory("vm://broker1?marshal=false&broker.persistent=false");
- PooledConnectionFactory cf = new PooledConnectionFactory(amq);
- cf.setMaxConnections(3);
- cf.setMaximumActiveSessionPerConnection(1);
- cf.setBlockIfSessionPoolIsFull(true);
- conn = cf.createConnection();
-
- // start test runner threads. It is expected that the second thread
- // blocks on the call to createSession()
-
- ExecutorService executor = Executors.newFixedThreadPool(2);
- executor.submit(new TestRunner2());
- // Thread.sleep(100);
- Future<Boolean> result2 = executor.submit(new TestRunner2());
-
- // sleep to allow threads to run
- Thread.sleep(sleepTimeout);
-
- // second task should not have finished, instead wait on getting a
- // JMS Session
- assertEquals(false, result2.isDone());
-
- // Only 1 session should have been created
- assertEquals(1, sessions.size());
-
- // Take all threads down
- executor.shutdownNow();
- }
-}
-
-class TestRunner2 implements Callable<Boolean> {
-
- public final static Logger LOG = Logger.getLogger(TestRunner2.class);
-
- /**
- * @return true if test succeeded, false otherwise
- */
- @Override
- public Boolean call() {
-
- Session one = null;
-
- // wait at most 5 seconds for the call to createSession
- try {
-
- if (PooledConnectionFactoryMaximumActiveTest.conn == null) {
- LOG.error("Connection not yet initialized. Aborting test.");
- return new Boolean(false);
- }
-
- one = PooledConnectionFactoryMaximumActiveTest.conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- LOG.info("Created new Session with id" + one);
- PooledConnectionFactoryMaximumActiveTest.addSession(one);
- Thread.sleep(2 * PooledConnectionFactoryMaximumActiveTest.sleepTimeout);
- } catch (Exception ex) {
- LOG.error(ex.getMessage());
- return new Boolean(false);
-
- } finally {
- if (one != null)
- try {
- one.close();
- } catch (JMSException e) {
- LOG.error(e.getMessage());
- }
- }
-
- // all good, test succeeded
- return new Boolean(true);
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionFactoryTest.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionFactoryTest.java b/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionFactoryTest.java
deleted file mode 100644
index 48e7069..0000000
--- a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionFactoryTest.java
+++ /dev/null
@@ -1,279 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-import java.util.concurrent.Callable;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.Session;
-
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-
-import org.apache.activemq.ActiveMQConnection;
-import org.apache.activemq.ActiveMQConnectionFactory;
-import org.apache.activemq.util.Wait;
-import org.apache.log4j.Logger;
-
-/**
- * Checks the behavior of the PooledConnectionFactory when the maximum amount of
- * sessions is being reached.
- *
- * Older versions simply block in the call to Connection.getSession(), which
- * isn't good. An exception being returned is the better option, so JMS clients
- * don't block. This test succeeds if an exception is returned and fails if the
- * call to getSession() blocks.
- */
-public class PooledConnectionFactoryTest extends TestCase {
-
- public final static Logger LOG = Logger.getLogger(PooledConnectionFactoryTest.class);
-
- /**
- * Create the test case
- *
- * @param testName
- * name of the test case
- */
- public PooledConnectionFactoryTest(String testName) {
- super(testName);
- }
-
- /**
- * @return the suite of tests being tested
- */
- public static Test suite() {
- return new TestSuite(PooledConnectionFactoryTest.class);
- }
-
- public void testClearAllConnections() throws Exception {
-
- ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory("vm://broker1?marshal=false&broker.persistent=false");
- PooledConnectionFactory cf = new PooledConnectionFactory(amq);
- cf.setMaxConnections(3);
-
- PooledConnection conn1 = (PooledConnection) cf.createConnection();
- PooledConnection conn2 = (PooledConnection) cf.createConnection();
- PooledConnection conn3 = (PooledConnection) cf.createConnection();
-
- assertNotSame(conn1.getConnection(), conn2.getConnection());
- assertNotSame(conn1.getConnection(), conn3.getConnection());
- assertNotSame(conn2.getConnection(), conn3.getConnection());
-
- assertEquals(3, cf.getNumConnections());
-
- cf.clear();
-
- assertEquals(0, cf.getNumConnections());
-
- conn1 = (PooledConnection) cf.createConnection();
- conn2 = (PooledConnection) cf.createConnection();
- conn3 = (PooledConnection) cf.createConnection();
-
- assertNotSame(conn1.getConnection(), conn2.getConnection());
- assertNotSame(conn1.getConnection(), conn3.getConnection());
- assertNotSame(conn2.getConnection(), conn3.getConnection());
- }
-
- public void testMaxConnectionsAreCreated() throws Exception {
-
- ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory("vm://broker1?marshal=false&broker.persistent=false");
- PooledConnectionFactory cf = new PooledConnectionFactory(amq);
- cf.setMaxConnections(3);
-
- PooledConnection conn1 = (PooledConnection) cf.createConnection();
- PooledConnection conn2 = (PooledConnection) cf.createConnection();
- PooledConnection conn3 = (PooledConnection) cf.createConnection();
-
- assertNotSame(conn1.getConnection(), conn2.getConnection());
- assertNotSame(conn1.getConnection(), conn3.getConnection());
- assertNotSame(conn2.getConnection(), conn3.getConnection());
-
- assertEquals(3, cf.getNumConnections());
- }
-
- public void testConnectionsAreRotated() throws Exception {
-
- ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory("vm://broker1?marshal=false&broker.persistent=false");
- PooledConnectionFactory cf = new PooledConnectionFactory(amq);
- cf.setMaxConnections(10);
-
- ActiveMQConnection previous = null;
-
- // Front load the pool.
- for (int i = 0; i < 10; ++i) {
- cf.createConnection();
- }
-
- for (int i = 0; i < 100; ++i) {
- ActiveMQConnection current = ((PooledConnection) cf.createConnection()).getConnection();
- assertNotSame(previous, current);
- previous = current;
- }
- }
-
- public void testConnectionsArePooled() throws Exception {
-
- ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory("vm://broker1?marshal=false&broker.persistent=false");
- PooledConnectionFactory cf = new PooledConnectionFactory(amq);
- cf.setMaxConnections(1);
-
- PooledConnection conn1 = (PooledConnection) cf.createConnection();
- PooledConnection conn2 = (PooledConnection) cf.createConnection();
- PooledConnection conn3 = (PooledConnection) cf.createConnection();
-
- assertSame(conn1.getConnection(), conn2.getConnection());
- assertSame(conn1.getConnection(), conn3.getConnection());
- assertSame(conn2.getConnection(), conn3.getConnection());
-
- assertEquals(1, cf.getNumConnections());
- }
-
- public void testConnectionsArePooledAsyncCreate() throws Exception {
-
- final ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory("vm://broker1?marshal=false&broker.persistent=false");
- final PooledConnectionFactory cf = new PooledConnectionFactory(amq);
- cf.setMaxConnections(1);
-
- final ConcurrentLinkedQueue<PooledConnection> connections = new ConcurrentLinkedQueue<PooledConnection>();
-
- final PooledConnection primary = (PooledConnection) cf.createConnection();
- final ExecutorService executor = Executors.newFixedThreadPool(10);
- final int numConnections = 100;
-
- for (int i = 0; i < numConnections; ++i) {
- executor.execute(new Runnable() {
-
- @Override
- public void run() {
- try {
- connections.add((PooledConnection) cf.createConnection());
- } catch (JMSException e) {
- }
- }
- });
- }
-
- assertTrue("", Wait.waitFor(new Wait.Condition() {
- @Override
- public boolean isSatisified() throws Exception {
- return connections.size() == numConnections;
- }
- }));
-
- executor.shutdown();
- assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
-
- for(PooledConnection connection : connections) {
- assertSame(primary.getConnection(), connection.getConnection());
- }
-
- connections.clear();
- }
-
- /**
- * Tests the behavior of the sessionPool of the PooledConnectionFactory when
- * maximum number of sessions are reached.
- */
- public void testApp() throws Exception {
- // using separate thread for testing so that we can interrupt the test
- // if the call to get a new session blocks.
-
- // start test runner thread
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Future<Boolean> result = executor.submit(new TestRunner());
-
- // test should not take > 5secs, so test fails i
- Thread.sleep(5 * 1000);
-
- if (!result.isDone() || !result.get().booleanValue()) {
- PooledConnectionFactoryTest.LOG.error("2nd call to createSession() " +
- "is blocking but should have returned an error instead.");
-
- executor.shutdownNow();
-
- fail("SessionPool inside PooledConnectionFactory is blocking if " +
- "limit is exceeded but should return an exception instead.");
- }
- }
-
- static class TestRunner implements Callable<Boolean> {
-
- public final static Logger LOG = Logger.getLogger(TestRunner.class);
-
- /**
- * @return true if test succeeded, false otherwise
- */
- @Override
- public Boolean call() {
-
- Connection conn = null;
- Session one = null;
-
- // wait at most 5 seconds for the call to createSession
- try {
- ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory("vm://broker1?marshal=false&broker.persistent=false");
- PooledConnectionFactory cf = new PooledConnectionFactory(amq);
- cf.setMaxConnections(3);
- cf.setMaximumActiveSessionPerConnection(1);
- cf.setBlockIfSessionPoolIsFull(false);
-
- conn = cf.createConnection();
- one = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- Session two = null;
- try {
- // this should raise an exception as we called
- // setMaximumActive(1)
- two = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
- two.close();
-
- LOG.error("Expected JMSException wasn't thrown.");
- fail("seconds call to Connection.createSession() was supposed" +
- "to raise an JMSException as internal session pool" +
- "is exhausted. This did not happen and indiates a problem");
- return new Boolean(false);
- } catch (JMSException ex) {
- if (ex.getCause().getClass() == java.util.NoSuchElementException.class) {
- // expected, ignore but log
- LOG.info("Caught expected " + ex);
- } else {
- LOG.error(ex);
- return new Boolean(false);
- }
- } finally {
- if (one != null)
- one.close();
- if (conn != null)
- conn.close();
- }
- } catch (Exception ex) {
- LOG.error(ex.getMessage());
- return new Boolean(false);
- }
-
- // all good, test succeeded
- return new Boolean(true);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionFactoryWithTemporaryDestinationsTest.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionFactoryWithTemporaryDestinationsTest.java b/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionFactoryWithTemporaryDestinationsTest.java
deleted file mode 100644
index ed13e2f..0000000
--- a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionFactoryWithTemporaryDestinationsTest.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-import javax.jms.Queue;
-import javax.jms.Session;
-import javax.jms.Topic;
-import javax.jms.Connection;
-
-import org.apache.activemq.broker.BrokerService;
-import org.apache.activemq.broker.TransportConnector;
-import org.apache.activemq.broker.region.RegionBroker;
-import org.apache.activemq.test.TestSupport;
-import org.apache.activemq.ActiveMQConnectionFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @version $Revision: 1.1 $
- */
-public class PooledConnectionFactoryWithTemporaryDestinationsTest extends TestSupport {
-
- private static final Logger LOG = LoggerFactory.getLogger(PooledConnectionFactoryWithTemporaryDestinationsTest.class);
-
- private BrokerService broker;
- private ActiveMQConnectionFactory factory;
- private PooledConnectionFactory pooledFactory;
-
- protected void setUp() throws Exception {
- broker = new BrokerService();
- broker.setUseJmx(false);
- broker.setPersistent(false);
- TransportConnector connector = broker.addConnector("tcp://localhost:0");
- broker.start();
- factory = new ActiveMQConnectionFactory("mock:" + connector.getConnectUri() + "?closeAsync=false");
- pooledFactory = new PooledConnectionFactory(factory);
- }
-
- protected void tearDown() throws Exception {
- broker.stop();
- }
-
- public void testTemporaryQueueWithMultipleConnectionUsers() throws Exception {
- Connection pooledConnection = null;
- Connection pooledConnection2 = null;
- Session session = null;
- Session session2 = null;
- Queue tempQueue = null;
- Queue normalQueue = null;
-
- pooledConnection = pooledFactory.createConnection();
- session = pooledConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- tempQueue = session.createTemporaryQueue();
- LOG.info("Created queue named: " + tempQueue.getQueueName());
-
- assertEquals(1, countBrokerTemporaryQueues());
-
- pooledConnection2 = pooledFactory.createConnection();
- session2 = pooledConnection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
- normalQueue = session2.createQueue("queue:FOO.TEST");
- LOG.info("Created queue named: " + normalQueue.getQueueName());
-
- // didn't create a temp queue on pooledConnection2 so we should still have a temp queue
- pooledConnection2.close();
- assertEquals(1, countBrokerTemporaryQueues());
-
- // after closing pooledConnection, where we created the temp queue, there should
- // be no temp queues left
- pooledConnection.close();
- assertEquals(0, countBrokerTemporaryQueues());
- }
-
- public void testTemporaryQueueLeakAfterConnectionClose() throws Exception {
- Connection pooledConnection = null;
- Session session = null;
- Queue tempQueue = null;
- for (int i = 0; i < 2; i++) {
- pooledConnection = pooledFactory.createConnection();
- session = pooledConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- tempQueue = session.createTemporaryQueue();
- LOG.info("Created queue named: " + tempQueue.getQueueName());
- pooledConnection.close();
- }
-
- assertEquals(0, countBrokerTemporaryQueues());
- }
-
- public void testTemporaryTopicLeakAfterConnectionClose() throws Exception {
- Connection pooledConnection = null;
- Session session = null;
- Topic tempTopic = null;
- for (int i = 0; i < 2; i++) {
- pooledConnection = pooledFactory.createConnection();
- session = pooledConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- tempTopic = session.createTemporaryTopic();
- LOG.info("Created topic named: " + tempTopic.getTopicName());
- pooledConnection.close();
- }
-
- assertEquals(0, countBrokerTemporaryTopics());
- }
-
- private int countBrokerTemporaryQueues() throws Exception {
- return ((RegionBroker) broker.getRegionBroker()).getTempQueueRegion().getDestinationMap().size();
- }
-
- private int countBrokerTemporaryTopics() throws Exception {
- return ((RegionBroker) broker.getRegionBroker()).getTempTopicRegion().getDestinationMap().size();
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionSessionCleanupTest.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionSessionCleanupTest.java b/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionSessionCleanupTest.java
deleted file mode 100644
index 57219a2..0000000
--- a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionSessionCleanupTest.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.activemq.pool;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.concurrent.TimeUnit;
-
-import javax.jms.Connection;
-import javax.jms.JMSException;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
-
-import org.apache.activemq.ActiveMQConnectionFactory;
-import org.apache.activemq.broker.BrokerService;
-import org.apache.activemq.broker.jmx.QueueViewMBean;
-import org.apache.activemq.command.ActiveMQQueue;
-import org.apache.activemq.util.Wait;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class PooledConnectionSessionCleanupTest {
-
- @SuppressWarnings("unused")
- private static final Logger LOG = LoggerFactory.getLogger(PooledConnectionSessionCleanupTest.class);
-
- protected BrokerService service;
-
- protected ActiveMQConnectionFactory directConnFact;
- protected Connection directConn1;
- protected Connection directConn2;
-
- protected PooledConnectionFactory pooledConnFact;
- protected Connection pooledConn1;
- protected Connection pooledConn2;
-
- private final ActiveMQQueue queue = new ActiveMQQueue("ContendedQueue");
- private final int MESSAGE_COUNT = 50;
-
- /**
- * Prepare to run a test case: create, configure, and start the embedded
- * broker, as well as creating the client connections to the broker.
- */
- @Before
- public void prepTest() throws java.lang.Exception {
- service = new BrokerService();
- service.setBrokerName("PooledConnectionSessionCleanupTestBroker");
- service.setUseJmx(true);
- service.setPersistent(false);
- service.setSchedulerSupport(false);
- service.start();
- service.waitUntilStarted();
-
- // Create the ActiveMQConnectionFactory and the PooledConnectionFactory.
- // Set a long idle timeout on the pooled connections to better show the
- // problem of holding onto created resources on close.
- directConnFact = new ActiveMQConnectionFactory(service.getVmConnectorURI());
- pooledConnFact = new PooledConnectionFactory(directConnFact);
- pooledConnFact.setIdleTimeout((int)TimeUnit.MINUTES.toMillis(60));
- pooledConnFact.setMaxConnections(1);
-
- // Prepare the connections
- directConn1 = directConnFact.createConnection();
- directConn1.start();
- directConn2 = directConnFact.createConnection();
- directConn2.start();
-
- // The pooled Connections should have the same underlying connection
- pooledConn1 = pooledConnFact.createConnection();
- pooledConn1.start();
- pooledConn2 = pooledConnFact.createConnection();
- pooledConn2.start();
- }
-
- @After
- public void cleanupTest() throws java.lang.Exception {
- try {
- if (pooledConn1 != null) {
- pooledConn1.close();
- }
- } catch (JMSException jms_exc) {
- }
- try {
- if (pooledConn2 != null) {
- pooledConn2.close();
- }
- } catch (JMSException jms_exc) {
- }
- try {
- if (directConn1 != null) {
- directConn1.close();
- }
- } catch (JMSException jms_exc) {
- }
- try {
- if (directConn2 != null) {
- directConn2.close();
- }
- } catch (JMSException jms_exc) {
- }
- try {
- if (service != null) {
- service.stop();
- service.waitUntilStopped();
- service = null;
- }
- } catch (JMSException jms_exc) {
- }
- }
-
- private void produceMessages() throws Exception {
-
- Session session = directConn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
- MessageProducer producer = session.createProducer(queue);
- for (int i = 0; i < MESSAGE_COUNT; ++i) {
- producer.send(session.createTextMessage("Test Message: " + i));
- }
- producer.close();
- }
-
- private QueueViewMBean getProxyToQueue(String name) throws MalformedObjectNameException, JMSException {
- ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq"
- + ":destinationType=Queue,destinationName=" + name
- + ",type=Broker,brokerName=" + service.getBrokerName());
- QueueViewMBean proxy = (QueueViewMBean) service.getManagementContext()
- .newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true);
- return proxy;
- }
-
- @Test
- public void testLingeringPooledSessionsHoldingPrefetchedMessages() throws Exception {
-
- produceMessages();
-
- Session pooledSession1 = pooledConn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
- pooledSession1.createConsumer(queue);
-
- final QueueViewMBean view = getProxyToQueue(queue.getPhysicalName());
-
- assertTrue("Should have all sent messages in flight:", Wait.waitFor(new Wait.Condition() {
-
- @Override
- public boolean isSatisified() throws Exception {
- return view.getInFlightCount() == MESSAGE_COUNT;
- }
- }));
-
- // While all the message are in flight we should get anything on this consumer.
- Session session = directConn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
- MessageConsumer consumer = session.createConsumer(queue);
- assertNull(consumer.receive(2000));
-
- pooledConn1.close();
-
- assertTrue("Should have only one consumer now:", Wait.waitFor(new Wait.Condition() {
-
- @Override
- public boolean isSatisified() throws Exception {
- return view.getSubscriptions().length == 1;
- }
- }));
-
- // Now we'd expect that the message stuck in the prefetch of the pooled session's
- // consumer would be rerouted to the non-pooled session's consumer.
- assertNotNull(consumer.receive(10000));
- }
-
- @Test
- public void testNonPooledConnectionCloseNotHoldingPrefetchedMessages() throws Exception {
-
- produceMessages();
-
- Session directSession = directConn2.createSession(false, Session.AUTO_ACKNOWLEDGE);
- directSession.createConsumer(queue);
-
- final QueueViewMBean view = getProxyToQueue(queue.getPhysicalName());
-
- assertTrue("Should have all sent messages in flight:", Wait.waitFor(new Wait.Condition() {
-
- @Override
- public boolean isSatisified() throws Exception {
- return view.getInFlightCount() == MESSAGE_COUNT;
- }
- }));
-
- // While all the message are in flight we should get anything on this consumer.
- Session session = directConn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
- MessageConsumer consumer = session.createConsumer(queue);
- assertNull(consumer.receive(2000));
-
- directConn2.close();
-
- assertTrue("Should have only one consumer now:", Wait.waitFor(new Wait.Condition() {
-
- @Override
- public boolean isSatisified() throws Exception {
- return view.getSubscriptions().length == 1;
- }
- }));
-
- // Now we'd expect that the message stuck in the prefetch of the first session's
- // consumer would be rerouted to the alternate session's consumer.
- assertNotNull(consumer.receive(10000));
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionTempDestCleanupTest.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionTempDestCleanupTest.java b/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionTempDestCleanupTest.java
deleted file mode 100644
index 005cb58..0000000
--- a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionTempDestCleanupTest.java
+++ /dev/null
@@ -1,222 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.activemq.pool;
-
-import static org.junit.Assert.assertTrue;
-
-import javax.jms.Connection;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Session;
-import javax.jms.TemporaryQueue;
-
-import org.apache.activemq.ActiveMQConnectionFactory;
-import org.apache.activemq.broker.BrokerService;
-import org.apache.activemq.broker.region.RegionBroker;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Test of lingering temporary destinations on pooled connections when the
- * underlying connections are reused. Also tests that closing one
- * PooledConnection does not delete the temporary destinations of another
- * PooledConnection that uses the same underlying ConnectionPool.
- *
- * jira: AMQ-3457
- */
-public class PooledConnectionTempDestCleanupTest {
-
- @SuppressWarnings("unused")
- private static final Logger LOG = LoggerFactory.getLogger(PooledConnectionTempDestCleanupTest.class);
-
- protected BrokerService embeddedBroker;
-
- protected ActiveMQConnectionFactory directConnFact;
- protected Connection directConn1;
- protected Connection directConn2;
-
- protected PooledConnectionFactory pooledConnFact;
- protected Connection pooledConn1;
- protected Connection pooledConn2;
-
- protected TemporaryQueue tempDest;
- protected TemporaryQueue otherTempDest;
-
- /**
- * Prepare to run a test case: create, configure, and start the embedded
- * broker, as well as creating the client connections to the broker.
- */
- @Before
- public void prepTest() throws java.lang.Exception {
- embeddedBroker = new BrokerService();
- configureBroker(embeddedBroker);
- embeddedBroker.start();
- embeddedBroker.waitUntilStarted();
-
- // Create the ActiveMQConnectionFactory and the PooledConnectionFactory.
- directConnFact = new ActiveMQConnectionFactory(embeddedBroker.getVmConnectorURI());
- pooledConnFact = new PooledConnectionFactory(directConnFact);
-
- // Prepare the connections
- directConn1 = directConnFact.createConnection();
- directConn1.start();
- directConn2 = directConnFact.createConnection();
- directConn2.start();
-
- pooledConn1 = pooledConnFact.createConnection();
- pooledConn1.start();
- pooledConn2 = pooledConnFact.createConnection();
- pooledConn2.start();
- }
-
- @After
- public void cleanupTest() throws java.lang.Exception {
- try {
- pooledConn1.stop();
- } catch (JMSException jms_exc) {
- }
- try {
- pooledConn2.stop();
- } catch (JMSException jms_exc) {
- }
- try {
- directConn1.stop();
- } catch (JMSException jms_exc) {
- }
- try {
- directConn2.stop();
- } catch (JMSException jms_exc) {
- }
-
- try {
- embeddedBroker.stop();
- } catch (JMSException jms_exc) {
- }
- }
-
- protected void configureBroker(BrokerService broker_svc) throws Exception {
- broker_svc.setBrokerName("testbroker1");
- broker_svc.setUseJmx(false);
- broker_svc.setPersistent(false);
- }
-
- /**
- * Test for lingering temporary destinations after closing a
- * PooledConnection. Here are the steps:
- *
- * 1. create a session on the first pooled connection 2. create a session on
- * the second pooled connection 3. create a temporary destination on the
- * first session 4. confirm the temporary destination exists in the broker
- * 5. close the first connection 6. check that the temporary destination no
- * longer exists in the broker
- */
- @Test
- public void testPooledLingeringTempDests() throws java.lang.Exception {
- Session session1;
- Session session2;
-
- session1 = pooledConn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
- session2 = pooledConn2.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- tempDest = session1.createTemporaryQueue();
-
- assertTrue("TEST METHOD FAILURE - NEW TEMP DESTINATION DOES NOT EXIST", destinationExists(tempDest));
-
- pooledConn1.close();
-
- assertTrue("FAILED: temp dest from closed pooled connection is lingering", !destinationExists(tempDest));
-
- session2.close();
- }
-
- /**
- * Test that closing one PooledConnection does not delete the temporary
- * destinations of another.
- *
- * 1. create a session on the first pooled connection 2. create a session on
- * the second pooled connection 3. create a temporary destination on the
- * first session 4. create a temporary destination on the second session 5.
- * confirm both temporary destinations exist in the broker 6. close the
- * first connection 7. check that the first temporary destination no longer
- * exists in the broker 8. check that the second temporary destination does
- * still exist in the broker
- */
- @Test
- public void testPooledTempDestsCleanupOverzealous() throws java.lang.Exception {
- Session session1;
- Session session2;
-
- session1 = pooledConn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
- session2 = pooledConn2.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- tempDest = session1.createTemporaryQueue();
- otherTempDest = session2.createTemporaryQueue();
-
- assertTrue("TEST METHOD FAILURE - NEW TEMP DESTINATION DOES NOT EXIST", destinationExists(tempDest));
- assertTrue("TEST METHOD FAILURE - NEW TEMP DESTINATION DOES NOT EXIST", destinationExists(otherTempDest));
-
- pooledConn1.close();
-
- // Now confirm the first temporary destination no longer exists and the
- // second does.
- assertTrue("FAILED: temp dest from closed pooled connection is lingering", !destinationExists(tempDest));
- assertTrue("FAILED: second PooledConnectin's temporary destination was incorrectly deleted", destinationExists(otherTempDest));
- }
-
- /**
- * CONTROL CASE
- *
- * Test for lingering temporary destinations after closing a Connection that
- * is NOT pooled. This demonstrates the standard JMS operation and helps to
- * validate the test methodology.
- *
- * 1. create a session on the first direct connection 2. create a session on
- * the second direct connection 3. create a temporary destination on the
- * first session 4. confirm the destination exists in the broker 5. close
- * the first connection 6. check that the destination no longer exists in
- * the broker
- */
- @Test
- public void testDirectLingeringTempDests() throws java.lang.Exception {
- Session session1;
- Session session2;
-
- session1 = directConn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
- session2 = directConn2.createSession(false, Session.AUTO_ACKNOWLEDGE);
-
- tempDest = session1.createTemporaryQueue();
-
- assertTrue("TEST METHOD FAILURE - NEW TEMP DESTINATION DOES NOT EXIST", destinationExists(tempDest));
-
- directConn1.close();
-
- // Now confirm the temporary destination no longer exists.
- assertTrue("CONTROL TEST FAILURE - TEST METHOD IS SUSPECT", (!destinationExists(tempDest)));
-
- session2.close();
- }
-
- private boolean destinationExists(Destination dest) throws Exception {
- RegionBroker rb = (RegionBroker) embeddedBroker.getBroker().getAdaptor(RegionBroker.class);
- return rb.getTopicRegion().getDestinationMap().containsKey(dest) || rb.getQueueRegion().getDestinationMap().containsKey(dest)
- || rb.getTempTopicRegion().getDestinationMap().containsKey(dest) || rb.getTempQueueRegion().getDestinationMap().containsKey(dest);
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionTest.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionTest.java b/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionTest.java
deleted file mode 100644
index e45bdb5..0000000
--- a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledConnectionTest.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-import javax.jms.Connection;
-import javax.jms.ConnectionFactory;
-import javax.jms.IllegalStateException;
-
-import junit.framework.TestCase;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * A couple of tests against the PooledConnection class.
- *
- */
-public class PooledConnectionTest extends TestCase {
-
- private final Logger log = LoggerFactory.getLogger(PooledConnectionTest.class);
-
- @Override
- public void setUp() throws Exception {
- log.debug("setUp() called.");
- }
-
-
- @Override
- public void tearDown() throws Exception {
- log.debug("tearDown() called.");
- }
-
- /**
- * AMQ-3752:
- * Tests how the ActiveMQConnection reacts to repeated calls to
- * setClientID().
- *
- * @throws Exception
- */
- public void testRepeatedSetClientIDCalls() throws Exception {
- log.debug("running testRepeatedSetClientIDCalls()");
-
- // 1st test: call setClientID("newID") twice
- // this should be tolerated and not result in an exception
- //
- ConnectionFactory cf = createPooledConnectionFactory();
- Connection conn = cf.createConnection();
- conn.setClientID("newID");
-
- try {
- conn.setClientID("newID");
- conn.start();
- conn.close();
- cf = null;
- } catch (IllegalStateException ise) {
- log.error("Repeated calls to ActiveMQConnection.setClientID(\"newID\") caused " + ise.getMessage());
- fail("Repeated calls to ActiveMQConnection.setClientID(\"newID\") caused " + ise.getMessage());
- }
-
- // 2nd test: call setClientID() twice with different IDs
- // this should result in an IllegalStateException
- //
- cf = createPooledConnectionFactory();
- conn = cf.createConnection();
- conn.setClientID("newID1");
- try {
- conn.setClientID("newID2");
- fail("calling ActiveMQConnection.setClientID() twice with different clientID must raise an IllegalStateException");
- } catch (IllegalStateException ise) {
- log.debug("Correctly received " + ise);
- } finally {
- conn.close();
- }
-
- // 3rd test: try to call setClientID() after start()
- // should result in an exception
- cf = createPooledConnectionFactory();
- conn = cf.createConnection();
- try {
- conn.start();
- conn.setClientID("newID3");
- fail("Calling setClientID() after start() mut raise a JMSException.");
- } catch (IllegalStateException ise) {
- log.debug("Correctly received " + ise);
- } finally {
- conn.close();
- }
-
- log.debug("Test finished.");
- }
-
- protected ConnectionFactory createPooledConnectionFactory() {
- ConnectionFactory cf = new PooledConnectionFactory("vm://localhost?broker.persistent=false");
- ((PooledConnectionFactory)cf).setMaxConnections(1);
- log.debug("ConnectionFactory initialized.");
- return cf;
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/test/java/org/apache/activemq/pool/PooledSessionExhaustionTest.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledSessionExhaustionTest.java b/activemq-pool/src/test/java/org/apache/activemq/pool/PooledSessionExhaustionTest.java
deleted file mode 100644
index 6954e9e..0000000
--- a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledSessionExhaustionTest.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-import javax.jms.Connection;
-import javax.jms.ConnectionFactory;
-import javax.jms.Destination;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
-import javax.jms.Session;
-import javax.jms.TextMessage;
-
-import junit.framework.TestCase;
-
-import org.apache.activemq.ActiveMQConnectionFactory;
-import org.apache.activemq.broker.BrokerService;
-import org.apache.activemq.broker.TransportConnector;
-import org.apache.log4j.Logger;
-
-public class PooledSessionExhaustionTest extends TestCase {
- private static final String QUEUE = "FOO";
- private static final int NUM_MESSAGES = 700;
-
- private Logger logger = Logger.getLogger(getClass());
-
- private BrokerService broker;
- private ActiveMQConnectionFactory factory;
- private PooledConnectionFactory pooledFactory;
- private String connectionUri;
- private int numReceived = 0;
-
- @Override
- protected void setUp() throws Exception {
- broker = new BrokerService();
- broker.setPersistent(false);
- broker.setUseJmx(false);
- TransportConnector connector = broker.addConnector("tcp://localhost:0");
- broker.start();
- connectionUri = connector.getPublishableConnectString();
- factory = new ActiveMQConnectionFactory(connectionUri);
- pooledFactory = new PooledConnectionFactory(factory);
- pooledFactory.setMaxConnections(1);
- pooledFactory.setBlockIfSessionPoolIsFull(false);
- }
-
- @Override
- protected void tearDown() throws Exception {
- broker.stop();
- broker.waitUntilStopped();
- broker = null;
- }
-
- public void sendMessages(ConnectionFactory connectionFactory) throws Exception {
- for (int i = 0; i < NUM_MESSAGES; i++) {
- Connection connection = connectionFactory.createConnection();
- connection.start();
-
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Destination destination = session.createQueue(QUEUE);
- MessageProducer producer = session.createProducer(destination);
-
- String msgTo = "hello";
- TextMessage message = session.createTextMessage(msgTo);
- producer.send(message);
- connection.close();
- logger.debug("sent " + i + " messages using " + connectionFactory.getClass());
- }
- }
-
- public void testCanExhaustSessions() throws Exception {
- Thread thread = new Thread(new Runnable() {
- public void run() {
- try {
- ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri);
- Connection connection = connectionFactory.createConnection();
- connection.start();
-
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- Destination destination = session.createQueue(QUEUE);
- MessageConsumer consumer = session.createConsumer(destination);
- for (int i = 0; i < NUM_MESSAGES; ++i) {
- Message msg = consumer.receive(5000);
- if (msg == null) {
- return;
- }
- numReceived++;
- if (numReceived % 20 == 0) {
- logger.debug("received " + numReceived + " messages ");
- System.runFinalization();
- }
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- });
- thread.start();
-
- sendMessages(pooledFactory);
- thread.join();
-
- assertEquals(NUM_MESSAGES, numReceived);
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/test/java/org/apache/activemq/pool/PooledSessionTest.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledSessionTest.java b/activemq-pool/src/test/java/org/apache/activemq/pool/PooledSessionTest.java
deleted file mode 100644
index d875f7b..0000000
--- a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledSessionTest.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-import static org.junit.Assert.assertEquals;
-
-import javax.jms.Session;
-
-import org.apache.activemq.ActiveMQConnectionFactory;
-import org.apache.activemq.broker.BrokerService;
-import org.apache.activemq.broker.TransportConnector;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-public class PooledSessionTest {
-
- private BrokerService broker;
- private ActiveMQConnectionFactory factory;
- private PooledConnectionFactory pooledFactory;
- private String connectionUri;
-
- @Before
- public void setUp() throws Exception {
- broker = new BrokerService();
- broker.setPersistent(false);
- broker.setUseJmx(false);
- TransportConnector connector = broker.addConnector("tcp://localhost:0");
- broker.start();
- connectionUri = connector.getPublishableConnectString();
- factory = new ActiveMQConnectionFactory(connectionUri);
- pooledFactory = new PooledConnectionFactory(factory);
- pooledFactory.setMaxConnections(1);
- pooledFactory.setBlockIfSessionPoolIsFull(false);
- }
-
- @After
- public void tearDown() throws Exception {
- broker.stop();
- broker.waitUntilStopped();
- broker = null;
- }
-
- @Test
- public void testPooledSessionStats() throws Exception {
- PooledConnection connection = (PooledConnection) pooledFactory.createConnection();
-
- assertEquals(0, connection.getNumActiveSessions());
- Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- assertEquals(1, connection.getNumActiveSessions());
- session.close();
- assertEquals(0, connection.getNumActiveSessions());
- assertEquals(1, connection.getNumtIdleSessions());
- assertEquals(1, connection.getNumSessions());
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/test/java/org/apache/activemq/pool/PooledTopicPublisherTest.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledTopicPublisherTest.java b/activemq-pool/src/test/java/org/apache/activemq/pool/PooledTopicPublisherTest.java
deleted file mode 100644
index 7df11f9..0000000
--- a/activemq-pool/src/test/java/org/apache/activemq/pool/PooledTopicPublisherTest.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import javax.jms.ExceptionListener;
-import javax.jms.JMSException;
-import javax.jms.Session;
-import javax.jms.TopicConnection;
-import javax.jms.TopicPublisher;
-import javax.jms.TopicSession;
-
-import org.apache.activemq.ActiveMQConnection;
-import org.apache.activemq.ActiveMQConnectionFactory;
-import org.apache.activemq.broker.BrokerService;
-import org.apache.activemq.broker.TransportConnector;
-import org.apache.activemq.command.ActiveMQTopic;
-import org.apache.activemq.test.TestSupport;
-import org.apache.activemq.util.SocketProxy;
-
-/**
- *
- */
-public class PooledTopicPublisherTest extends TestSupport {
-
- private TopicConnection connection;
-
- public void testPooledConnectionFactory() throws Exception {
- ActiveMQTopic topic = new ActiveMQTopic("test");
- PooledConnectionFactory pcf = new PooledConnectionFactory();
- pcf.setConnectionFactory(new ActiveMQConnectionFactory("vm://test"));
-
- connection = (TopicConnection) pcf.createConnection();
- TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- TopicPublisher publisher = session.createPublisher(topic);
- publisher.publish(session.createMessage());
- }
-
-
- public void testSetGetExceptionListener() throws Exception {
- PooledConnectionFactory pcf = new PooledConnectionFactory();
- pcf.setConnectionFactory(new ActiveMQConnectionFactory("vm://test"));
-
- connection = (TopicConnection) pcf.createConnection();
- ExceptionListener listener = new ExceptionListener() {
- public void onException(JMSException exception) {
- }
- };
- connection.setExceptionListener(listener);
- assertEquals(listener, connection.getExceptionListener());
- }
-
- public void testPooledConnectionAfterInactivity() throws Exception {
- BrokerService broker = new BrokerService();
- TransportConnector networkConnector = broker.addConnector("tcp://localhost:0");
- broker.setPersistent(false);
- broker.setUseJmx(false);
- broker.start();
-
- SocketProxy proxy = new SocketProxy(networkConnector.getConnectUri());
-
- PooledConnectionFactory pcf = new PooledConnectionFactory();
- String uri = proxy.getUrl().toString() + "?trace=true&wireFormat.maxInactivityDuration=500&wireFormat.maxInactivityDurationInitalDelay=500";
- pcf.setConnectionFactory(new ActiveMQConnectionFactory(uri));
-
- PooledConnection conn = (PooledConnection) pcf.createConnection();
- ActiveMQConnection amq = conn.getConnection();
- assertNotNull(amq);
- final CountDownLatch gotException = new CountDownLatch(1);
- conn.setExceptionListener(new ExceptionListener() {
- public void onException(JMSException exception) {
- gotException.countDown();
- }});
- conn.setClientID(getName());
-
- // let it hang, simulate a server hang so inactivity timeout kicks in
- proxy.pause();
- //assertTrue("got an exception", gotException.await(5, TimeUnit.SECONDS));
- TimeUnit.SECONDS.sleep(2);
- conn.close();
- }
-
- @Override
- protected void tearDown() throws Exception {
- if (connection != null) {
- connection.close();
- connection = null;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/test/java/org/apache/activemq/pool/XAConnectionPoolTest.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/test/java/org/apache/activemq/pool/XAConnectionPoolTest.java b/activemq-pool/src/test/java/org/apache/activemq/pool/XAConnectionPoolTest.java
index 56c4f60..8223f2d 100644
--- a/activemq-pool/src/test/java/org/apache/activemq/pool/XAConnectionPoolTest.java
+++ b/activemq-pool/src/test/java/org/apache/activemq/pool/XAConnectionPoolTest.java
@@ -18,7 +18,6 @@ package org.apache.activemq.pool;
import java.util.Hashtable;
import java.util.Vector;
-
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
@@ -40,11 +39,11 @@ import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import javax.transaction.xa.XAResource;
-
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQXAConnectionFactory;
import org.apache.activemq.ActiveMQXASession;
import org.apache.activemq.command.ActiveMQTopic;
+import org.apache.activemq.jms.pool.PooledSession;
import org.apache.activemq.test.TestSupport;
public class XAConnectionPoolTest extends TestSupport {
@@ -54,7 +53,7 @@ public class XAConnectionPoolTest extends TestSupport {
final Vector<Synchronization> syncs = new Vector<Synchronization>();
ActiveMQTopic topic = new ActiveMQTopic("test");
XaPooledConnectionFactory pcf = new XaPooledConnectionFactory();
- pcf.setConnectionFactory(new ActiveMQXAConnectionFactory("vm://test?broker.persistent=false"));
+ pcf.setConnectionFactory(new ActiveMQConnectionFactory("vm://test?broker.persistent=false"));
// simple TM that is in a tx and will track syncs
pcf.setTransactionManager(new TransactionManager(){
@@ -135,8 +134,8 @@ public class XAConnectionPoolTest extends TestSupport {
TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
assertTrue(session instanceof PooledSession);
- PooledSession pooledSession = (PooledSession) session;
- assertTrue(pooledSession.getInternalSession() instanceof ActiveMQXASession);
+// PooledSession pooledSession = (PooledSession) session;
+// assertTrue(pooledSession.getInternalSession() instanceof ActiveMQXASession);
TopicPublisher publisher = session.createPublisher(topic);
publisher.publish(session.createMessage());
@@ -155,7 +154,7 @@ public class XAConnectionPoolTest extends TestSupport {
final Vector<Synchronization> syncs = new Vector<Synchronization>();
ActiveMQTopic topic = new ActiveMQTopic("test");
XaPooledConnectionFactory pcf = new XaPooledConnectionFactory();
- pcf.setConnectionFactory(new ActiveMQConnectionFactory("vm://test?broker.persistent=false"));
+ pcf.setConnectionFactory(new ActiveMQXAConnectionFactory("vm://test?broker.persistent=false&jms.xaAckMode=" + Session.CLIENT_ACKNOWLEDGE));
// simple TM that is in a tx and will track syncs
pcf.setTransactionManager(new TransactionManager(){
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/test/java/org/apache/activemq/pool/bugs/AMQ4441Test.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/test/java/org/apache/activemq/pool/bugs/AMQ4441Test.java b/activemq-pool/src/test/java/org/apache/activemq/pool/bugs/AMQ4441Test.java
deleted file mode 100644
index 0775aa6..0000000
--- a/activemq-pool/src/test/java/org/apache/activemq/pool/bugs/AMQ4441Test.java
+++ /dev/null
@@ -1,84 +0,0 @@
-package org.apache.activemq.pool.bugs;
-
-import static org.junit.Assert.fail;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import javax.jms.JMSException;
-
-import org.apache.activemq.broker.BrokerService;
-import org.apache.activemq.pool.PooledConnection;
-import org.apache.activemq.pool.PooledConnectionFactory;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class AMQ4441Test {
-
- private static final Logger LOG = LoggerFactory.getLogger(AMQ4441Test.class);
- private BrokerService broker;
-
- @Before
- public void setUp() throws Exception {
- broker = new BrokerService();
- broker.setDeleteAllMessagesOnStartup(true);
- broker.setPersistent(false);
- broker.setUseJmx(false);
- broker.start();
- broker.waitUntilStarted();
- }
-
- @After
- public void stopBroker() throws Exception {
- broker.stop();
- broker.waitUntilStopped();
- }
-
- @Test(timeout=120000)
- public void demo() throws JMSException, InterruptedException {
- final CountDownLatch latch = new CountDownLatch(1);
- final AtomicBoolean done = new AtomicBoolean(false);
- final PooledConnectionFactory pooled = new PooledConnectionFactory("vm://localhost?create=false");
-
- pooled.setMaxConnections(2);
- pooled.setExpiryTimeout(10L);
- pooled.start();
- Thread[] threads = new Thread[10];
- for (int i = 0; i < threads.length; i++) {
- threads[i] = new Thread(new Runnable() {
- @Override
- public void run() {
- while (!done.get() && latch.getCount() > 0) {
- try {
- final PooledConnection pooledConnection = (PooledConnection) pooled.createConnection();
- if (pooledConnection.getConnection() == null) {
- LOG.info("Found broken connection.");
- latch.countDown();
- }
- pooledConnection.close();
- } catch (JMSException e) {
- LOG.warn("Caught Exception", e);
- }
- }
- }
- });
- }
- for (Thread thread : threads) {
- thread.start();
- }
-
- if (latch.await(1, TimeUnit.MINUTES)) {
- fail("A thread obtained broken connection");
- }
-
- done.set(true);
- for (Thread thread : threads) {
- thread.join();
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/test/resources/activemq-spring-jdbc.xml
----------------------------------------------------------------------
diff --git a/activemq-pool/src/test/resources/activemq-spring-jdbc.xml b/activemq-pool/src/test/resources/activemq-spring-jdbc.xml
deleted file mode 100644
index e406d69..0000000
--- a/activemq-pool/src/test/resources/activemq-spring-jdbc.xml
+++ /dev/null
@@ -1,69 +0,0 @@
-<!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<!-- START SNIPPET: example -->
-<beans
- xmlns="http://www.springframework.org/schema/beans"
- xmlns:amq="http://activemq.apache.org/schema/core"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
- http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd
- http://activemq.apache.org/camel/schema/spring http://activemq.apache.org/camel/schema/spring/camel-spring.xsd">
-
- <broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="target/" useJmx="false" deleteAllMessagesOnStartup="true">
-
- <persistenceAdapter>
- <jdbcPersistenceAdapter dataSource="#derby-ds" dataDirectory="target/"/>
- </persistenceAdapter>
-
- <destinationPolicy>
- <policyMap>
- <policyEntries>
- <policyEntry queue=">" memoryLimit="10240"/>
- <policyEntry topic=">" memoryLimit="10240">
- </policyEntry>
- </policyEntries>
- </policyMap>
- </destinationPolicy>
-
-
- <systemUsage>
- <systemUsage>
- <memoryUsage>
- <memoryUsage limit="102400"/>
- </memoryUsage>
- <storeUsage>
- <storeUsage limit="1 gb" name="foo"/>
- </storeUsage>
- <tempUsage>
- <tempUsage limit="100 mb"/>
- </tempUsage>
- </systemUsage>
- </systemUsage>
-
- <transportConnectors>
- <transportConnector name="openwire" uri="tcp://localhost:61616" discoveryUri="multicast://default"/>
- </transportConnectors>
- </broker>
-
-
- <bean id="derby-ds" class="org.apache.derby.jdbc.EmbeddedDataSource">
- <property name="databaseName" value="derbydb"/>
- <property name="createDatabase" value="create"/>
- </bean>
-
-</beans>
-<!-- END SNIPPET: example -->
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/test/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/activemq-pool/src/test/resources/log4j.properties b/activemq-pool/src/test/resources/log4j.properties
deleted file mode 100755
index b42af1a..0000000
--- a/activemq-pool/src/test/resources/log4j.properties
+++ /dev/null
@@ -1,38 +0,0 @@
-## ---------------------------------------------------------------------------
-## Licensed to the Apache Software Foundation (ASF) under one or more
-## contributor license agreements. See the NOTICE file distributed with
-## this work for additional information regarding copyright ownership.
-## The ASF licenses this file to You under the Apache License, Version 2.0
-## (the "License"); you may not use this file except in compliance with
-## the License. You may obtain a copy of the License at
-##
-## http://www.apache.org/licenses/LICENSE-2.0
-##
-## Unless required by applicable law or agreed to in writing, software
-## distributed under the License is distributed on an "AS IS" BASIS,
-## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-## See the License for the specific language governing permissions and
-## limitations under the License.
-## ---------------------------------------------------------------------------
-
-#
-# The logging properties used during tests..
-#
-log4j.rootLogger=INFO, out, stdout
-
-log4j.logger.org.apache.activemq.spring=WARN
-#log4j.logger.org.apache.activemq.usecases=DEBUG
-#log4j.logger.org.apache.activemq.broker.region=DEBUG
-log4j.logger.org.apache.activemq.pool=DEBUG
-
-# CONSOLE appender not used by default
-log4j.appender.stdout=org.apache.log4j.ConsoleAppender
-log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
-log4j.appender.stdout.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n
-
-# File appender
-log4j.appender.out=org.apache.log4j.FileAppender
-log4j.appender.out.layout=org.apache.log4j.PatternLayout
-log4j.appender.out.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n
-log4j.appender.out.file=target/activemq-test.log
-log4j.appender.out.append=true
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-spring/src/main/java/org/apache/activemq/pool/PooledConnectionFactoryBean.java
----------------------------------------------------------------------
diff --git a/activemq-spring/src/main/java/org/apache/activemq/pool/PooledConnectionFactoryBean.java b/activemq-spring/src/main/java/org/apache/activemq/pool/PooledConnectionFactoryBean.java
index 1524f34..afd380f 100644
--- a/activemq-spring/src/main/java/org/apache/activemq/pool/PooledConnectionFactoryBean.java
+++ b/activemq-spring/src/main/java/org/apache/activemq/pool/PooledConnectionFactoryBean.java
@@ -20,7 +20,7 @@ import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.jms.ConnectionFactory;
import javax.transaction.TransactionManager;
-
+import org.apache.activemq.jms.pool.PooledConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
@@ -38,7 +38,7 @@ import org.springframework.beans.factory.FactoryBean;
* </bean>
* </pre>
*
- * The <code>resourceName</code> property should be used along with the {@link ActiveMQResourceManager} and have
+ * The <code>resourceName</code> property should be used along with the {@link org.apache.activemq.jms.pool.GenericResourceManager} and have
* the same value than its <code>resourceName</code> property. This will make sure the transaction manager
* maps correctly the connection factory to the recovery process.
*
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-spring/src/test/java/org/apache/bugs/AMQ2754Test.java
----------------------------------------------------------------------
diff --git a/activemq-spring/src/test/java/org/apache/bugs/AMQ2754Test.java b/activemq-spring/src/test/java/org/apache/bugs/AMQ2754Test.java
index 22a2ba0..932f7ca 100644
--- a/activemq-spring/src/test/java/org/apache/bugs/AMQ2754Test.java
+++ b/activemq-spring/src/test/java/org/apache/bugs/AMQ2754Test.java
@@ -39,7 +39,6 @@ import org.apache.activemq.store.memory.MemoryPersistenceAdapter;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
-//import org.apache.activemq.pool.PooledConnectionFactory;
public class AMQ2754Test extends TestCase {
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/assembly/pom.xml
----------------------------------------------------------------------
diff --git a/assembly/pom.xml b/assembly/pom.xml
index a11abf1..49f4ab7 100755
--- a/assembly/pom.xml
+++ b/assembly/pom.xml
@@ -152,6 +152,14 @@
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
+ <artifactId>activemq-jms-pool</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>activemq-pool</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
<artifactId>activemq-web</artifactId>
</dependency>
<dependency>
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/assembly/src/main/descriptors/common-bin.xml
----------------------------------------------------------------------
diff --git a/assembly/src/main/descriptors/common-bin.xml b/assembly/src/main/descriptors/common-bin.xml
index 82ded4b..f1978f5 100644
--- a/assembly/src/main/descriptors/common-bin.xml
+++ b/assembly/src/main/descriptors/common-bin.xml
@@ -177,6 +177,7 @@
<include>${pom.groupId}:activemq-jdbc-store</include>
<include>${pom.groupId}:activemq-leveldb-store</include>
<include>${pom.groupId}:activemq-log4j-appender</include>
+ <include>${pom.groupId}:activemq-jms-pool</include>
<include>${pom.groupId}:activemq-pool</include>
<include>${pom.groupId}:activeio-core</include>
<include>commons-beanutils:commons-beanutils</include>
[3/6] https://issues.apache.org/jira/browse/AMQ-4757
activemq-jms-pool a generic jms xa pool derived from activemq-pool which
activemq-pool now extends with amq specifics
Posted by gt...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/PooledConnection.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/PooledConnection.java b/activemq-pool/src/main/java/org/apache/activemq/pool/PooledConnection.java
old mode 100755
new mode 100644
index a03eaf9..16d561e
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/PooledConnection.java
+++ b/activemq-pool/src/main/java/org/apache/activemq/pool/PooledConnection.java
@@ -16,284 +16,19 @@
*/
package org.apache.activemq.pool;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-import javax.jms.Connection;
-import javax.jms.ConnectionConsumer;
-import javax.jms.ConnectionMetaData;
-import javax.jms.Destination;
-import javax.jms.ExceptionListener;
import javax.jms.JMSException;
-import javax.jms.Queue;
-import javax.jms.QueueConnection;
-import javax.jms.QueueSession;
-import javax.jms.ServerSessionPool;
-import javax.jms.Session;
-import javax.jms.TemporaryQueue;
-import javax.jms.TemporaryTopic;
-import javax.jms.Topic;
-import javax.jms.TopicConnection;
-import javax.jms.TopicSession;
-
import org.apache.activemq.ActiveMQConnection;
-import org.apache.activemq.ActiveMQSession;
-import org.apache.activemq.AlreadyClosedException;
import org.apache.activemq.EnhancedConnection;
import org.apache.activemq.advisory.DestinationSource;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Represents a proxy {@link Connection} which is-a {@link TopicConnection} and
- * {@link QueueConnection} which is pooled and on {@link #close()} will return
- * its reference to the ConnectionPool backing it.
- *
- * <b>NOTE</b> this implementation is only intended for use when sending
- * messages. It does not deal with pooling of consumers; for that look at a
- * library like <a href="http://jencks.org/">Jencks</a> such as in <a
- * href="http://jencks.org/Message+Driven+POJOs">this example</a>
- *
- */
-public class PooledConnection implements TopicConnection, QueueConnection, EnhancedConnection, PooledSessionEventListener {
- private static final transient Logger LOG = LoggerFactory.getLogger(PooledConnection.class);
-
- private ConnectionPool pool;
- private volatile boolean stopped;
- private final List<TemporaryQueue> connTempQueues = new CopyOnWriteArrayList<TemporaryQueue>();
- private final List<TemporaryTopic> connTempTopics = new CopyOnWriteArrayList<TemporaryTopic>();
- private final List<PooledSession> loanedSessions = new CopyOnWriteArrayList<PooledSession>();
-
- /**
- * Creates a new PooledConnection instance that uses the given ConnectionPool to create
- * and manage its resources. The ConnectionPool instance can be shared amongst many
- * PooledConnection instances.
- *
- * @param pool
- * The connection and pool manager backing this proxy connection object.
- */
- public PooledConnection(ConnectionPool pool) {
- this.pool = pool;
- }
-
- /**
- * Factory method to create a new instance.
- */
- public PooledConnection newInstance() {
- return new PooledConnection(pool);
- }
-
- @Override
- public void close() throws JMSException {
- this.cleanupConnectionTemporaryDestinations();
- this.cleanupAllLoanedSessions();
- if (this.pool != null) {
- this.pool.decrementReferenceCount();
- this.pool = null;
- }
- }
-
- @Override
- public void start() throws JMSException {
- assertNotClosed();
- pool.start();
- }
-
- @Override
- public void stop() throws JMSException {
- stopped = true;
- }
-
- @Override
- public ConnectionConsumer createConnectionConsumer(Destination destination, String selector, ServerSessionPool serverSessionPool, int maxMessages) throws JMSException {
- return getConnection().createConnectionConsumer(destination, selector, serverSessionPool, maxMessages);
- }
-
- @Override
- public ConnectionConsumer createConnectionConsumer(Topic topic, String s, ServerSessionPool serverSessionPool, int maxMessages) throws JMSException {
- return getConnection().createConnectionConsumer(topic, s, serverSessionPool, maxMessages);
- }
-
- @Override
- public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String selector, String s1, ServerSessionPool serverSessionPool, int i) throws JMSException {
- return getConnection().createDurableConnectionConsumer(topic, selector, s1, serverSessionPool, i);
- }
-
- @Override
- public String getClientID() throws JMSException {
- return getConnection().getClientID();
- }
-
- @Override
- public ExceptionListener getExceptionListener() throws JMSException {
- return getConnection().getExceptionListener();
- }
-
- @Override
- public ConnectionMetaData getMetaData() throws JMSException {
- return getConnection().getMetaData();
- }
-
- @Override
- public void setExceptionListener(ExceptionListener exceptionListener) throws JMSException {
- getConnection().setExceptionListener(exceptionListener);
- }
-
- @Override
- public void setClientID(String clientID) throws JMSException {
- // ignore repeated calls to setClientID() with the same client id
- // this could happen when a JMS component such as Spring that uses a
- // PooledConnectionFactory shuts down and reinitializes.
- if (this.getConnection().getClientID() == null || !this.getClientID().equals(clientID)) {
- getConnection().setClientID(clientID);
- }
- }
+import org.apache.activemq.jms.pool.ConnectionPool;
- @Override
- public ConnectionConsumer createConnectionConsumer(Queue queue, String selector, ServerSessionPool serverSessionPool, int maxMessages) throws JMSException {
- return getConnection().createConnectionConsumer(queue, selector, serverSessionPool, maxMessages);
- }
-
- // Session factory methods
- // -------------------------------------------------------------------------
- @Override
- public QueueSession createQueueSession(boolean transacted, int ackMode) throws JMSException {
- return (QueueSession) createSession(transacted, ackMode);
- }
-
- @Override
- public TopicSession createTopicSession(boolean transacted, int ackMode) throws JMSException {
- return (TopicSession) createSession(transacted, ackMode);
+public class PooledConnection extends org.apache.activemq.jms.pool.PooledConnection implements EnhancedConnection {
+ public PooledConnection(ConnectionPool connection) {
+ super(connection);
}
@Override
- public Session createSession(boolean transacted, int ackMode) throws JMSException {
- PooledSession result;
- result = (PooledSession) pool.createSession(transacted, ackMode);
-
- // Store the session so we can close the sessions that this PooledConnection
- // created in order to ensure that consumers etc are closed per the JMS contract.
- loanedSessions.add(result);
-
- // Add a event listener to the session that notifies us when the session
- // creates / destroys temporary destinations and closes etc.
- result.addSessionEventListener(this);
- return result;
- }
-
- // EnhancedCollection API
- // -------------------------------------------------------------------------
-
- @Override
public DestinationSource getDestinationSource() throws JMSException {
- return getConnection().getDestinationSource();
- }
-
- // Implementation methods
- // -------------------------------------------------------------------------
-
- @Override
- public void onTemporaryQueueCreate(TemporaryQueue tempQueue) {
- connTempQueues.add(tempQueue);
- }
-
- @Override
- public void onTemporaryTopicCreate(TemporaryTopic tempTopic) {
- connTempTopics.add(tempTopic);
- }
-
- @Override
- public void onSessionClosed(PooledSession session) {
- if (session != null) {
- this.loanedSessions.remove(session);
- }
- }
-
- public ActiveMQConnection getConnection() throws JMSException {
- assertNotClosed();
- return pool.getConnection();
- }
-
- protected void assertNotClosed() throws AlreadyClosedException {
- if (stopped || pool == null) {
- throw new AlreadyClosedException();
- }
- }
-
- protected ActiveMQSession createSession(SessionKey key) throws JMSException {
- return (ActiveMQSession) getConnection().createSession(key.isTransacted(), key.getAckMode());
- }
-
- @Override
- public String toString() {
- return "PooledConnection { " + pool + " }";
- }
-
- /**
- * Remove all of the temporary destinations created for this connection.
- * This is important since the underlying connection may be reused over a
- * long period of time, accumulating all of the temporary destinations from
- * each use. However, from the perspective of the lifecycle from the
- * client's view, close() closes the connection and, therefore, deletes all
- * of the temporary destinations created.
- */
- protected void cleanupConnectionTemporaryDestinations() {
-
- for (TemporaryQueue tempQueue : connTempQueues) {
- try {
- tempQueue.delete();
- } catch (JMSException ex) {
- LOG.info("failed to delete Temporary Queue \"" + tempQueue.toString() + "\" on closing pooled connection: " + ex.getMessage());
- }
- }
- connTempQueues.clear();
-
- for (TemporaryTopic tempTopic : connTempTopics) {
- try {
- tempTopic.delete();
- } catch (JMSException ex) {
- LOG.info("failed to delete Temporary Topic \"" + tempTopic.toString() + "\" on closing pooled connection: " + ex.getMessage());
- }
- }
- connTempTopics.clear();
- }
-
- /**
- * The PooledSession tracks all Sessions that it created and now we close them. Closing the
- * PooledSession will return the internal Session to the Pool of Session after cleaning up
- * all the resources that the Session had allocated for this PooledConnection.
- */
- protected void cleanupAllLoanedSessions() {
-
- for (PooledSession session : loanedSessions) {
- try {
- session.close();
- } catch (JMSException ex) {
- LOG.info("failed to close laoned Session \"" + session + "\" on closing pooled connection: " + ex.getMessage());
- }
- }
- loanedSessions.clear();
- }
-
- /**
- * @return the total number of Pooled session including idle sessions that are not
- * currently loaned out to any client.
- */
- public int getNumSessions() {
- return this.pool.getNumSessions();
- }
-
- /**
- * @return the number of Sessions that are currently checked out of this Connection's session pool.
- */
- public int getNumActiveSessions() {
- return this.pool.getNumActiveSessions();
- }
-
- /**
- * @return the number of Sessions that are idle in this Connection's sessions pool.
- */
- public int getNumtIdleSessions() {
- return this.pool.getNumIdleSessions();
+ return ((ActiveMQConnection)getConnection()).getDestinationSource();
}
}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/PooledConnectionFactory.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/PooledConnectionFactory.java b/activemq-pool/src/main/java/org/apache/activemq/pool/PooledConnectionFactory.java
index 3e34517..62b97f9 100644
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/PooledConnectionFactory.java
+++ b/activemq-pool/src/main/java/org/apache/activemq/pool/PooledConnectionFactory.java
@@ -16,486 +16,126 @@
*/
package org.apache.activemq.pool;
+import java.io.IOException;
+import java.util.HashMap;
import java.util.Properties;
-import java.util.concurrent.atomic.AtomicBoolean;
-
import javax.jms.Connection;
-import javax.jms.ConnectionFactory;
-import javax.jms.JMSException;
-
+import javax.naming.NamingException;
+import javax.naming.Reference;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.Service;
-import org.apache.activemq.jndi.JNDIBaseStorable;
-import org.apache.activemq.util.JMSExceptionSupport;
-import org.apache.commons.pool.KeyedObjectPool;
-import org.apache.commons.pool.KeyedPoolableObjectFactory;
-import org.apache.commons.pool.impl.GenericKeyedObjectPool;
+import org.apache.activemq.jms.pool.ConnectionPool;
+import org.apache.activemq.jndi.JNDIReferenceFactory;
+import org.apache.activemq.jndi.JNDIStorableInterface;
+import org.apache.activemq.transport.TransportListener;
+import org.apache.activemq.util.IntrospectionSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * A JMS provider which pools Connection, Session and MessageProducer instances
- * so it can be used with tools like <a href="http://camel.apache.org/activemq.html">Camel</a> and Spring's
- * <a href="http://activemq.apache.org/spring-support.html">JmsTemplate and MessagListenerContainer</a>.
- * Connections, sessions and producers are returned to a pool after use so that they can be reused later
- * without having to undergo the cost of creating them again.
- *
- * b>NOTE:</b> while this implementation does allow the creation of a collection of active consumers,
- * it does not 'pool' consumers. Pooling makes sense for connections, sessions and producers, which
- * are expensive to create and can remain idle a minimal cost. Consumers, on the other hand, are usually
- * just created at startup and left active, handling incoming messages as they come. When a consumer is
- * complete, it is best to close it rather than return it to a pool for later reuse: this is because,
- * even if a consumer is idle, ActiveMQ will keep delivering messages to the consumer's prefetch buffer,
- * where they'll get held until the consumer is active again.
- *
- * If you are creating a collection of consumers (for example, for multi-threaded message consumption), you
- * might want to consider using a lower prefetch value for each consumer (e.g. 10 or 20), to ensure that
- * all messages don't end up going to just one of the consumers. See this FAQ entry for more detail:
- * http://activemq.apache.org/i-do-not-receive-messages-in-my-second-consumer.html
- *
- * Optionally, one may configure the pool to examine and possibly evict objects as they sit idle in the
- * pool. This is performed by an "idle object eviction" thread, which runs asynchronously. Caution should
- * be used when configuring this optional feature. Eviction runs contend with client threads for access
- * to objects in the pool, so if they run too frequently performance issues may result. The idle object
- * eviction thread may be configured using the {@link setTimeBetweenExpirationCheckMillis} method. By
- * default the value is -1 which means no eviction thread will be run. Set to a non-negative value to
- * configure the idle eviction thread to run.
+ * Add Service and Referenceable and TransportListener to @link{org.apache.activemq.jms.pool.PooledConnectionFactory}
*
* @org.apache.xbean.XBean element="pooledConnectionFactory"
*/
-public class PooledConnectionFactory extends JNDIBaseStorable implements ConnectionFactory, Service {
- private static final transient Logger LOG = LoggerFactory.getLogger(PooledConnectionFactory.class);
-
- private final AtomicBoolean stopped = new AtomicBoolean(false);
- private final GenericKeyedObjectPool<ConnectionKey, ConnectionPool> connectionsPool;
-
- private ConnectionFactory connectionFactory;
+public class PooledConnectionFactory extends org.apache.activemq.jms.pool.PooledConnectionFactory implements JNDIStorableInterface, Service {
+ public static final String POOL_PROPS_PREFIX = "pool";
- private int maximumActiveSessionPerConnection = 500;
- private int idleTimeout = 30 * 1000;
- private boolean blockIfSessionPoolIsFull = true;
- private long expiryTimeout = 0l;
- private boolean createConnectionOnStartup = true;
+ private static final transient Logger LOG = LoggerFactory.getLogger(org.apache.activemq.jms.pool.PooledConnectionFactory.class);
- /**
- * Creates new PooledConnectionFactory with a default ActiveMQConnectionFactory instance.
- * <p/>
- * The URI used to connect to ActiveMQ comes from the default value of ActiveMQConnectionFactory.
- */
public PooledConnectionFactory() {
- this(new ActiveMQConnectionFactory());
+ super();
}
- /**
- * Creates a new PooledConnectionFactory that will use the given broker URI to connect to
- * ActiveMQ.
- *
- * @param brokerURL
- * The URI to use to configure the internal ActiveMQConnectionFactory.
- */
- public PooledConnectionFactory(String brokerURL) {
- this(new ActiveMQConnectionFactory(brokerURL));
+ public PooledConnectionFactory(ActiveMQConnectionFactory activeMQConnectionFactory) {
+ setConnectionFactory(activeMQConnectionFactory);
}
- /**
- * Creates a new PooledConnectionFactory that will use the given ActiveMQConnectionFactory to
- * create new ActiveMQConnection instances that will be pooled.
- *
- * @param connectionFactory
- * The ActiveMQConnectionFactory to create new Connections for this pool.
- */
- public PooledConnectionFactory(ActiveMQConnectionFactory connectionFactory) {
- this.connectionFactory = connectionFactory;
-
- this.connectionsPool = new GenericKeyedObjectPool<ConnectionKey, ConnectionPool>(
- new KeyedPoolableObjectFactory<ConnectionKey, ConnectionPool>() {
-
- @Override
- public void activateObject(ConnectionKey key, ConnectionPool connection) throws Exception {
- }
-
- @Override
- public void destroyObject(ConnectionKey key, ConnectionPool connection) throws Exception {
- try {
- if (LOG.isTraceEnabled()) {
- LOG.trace("Destroying connection: {}", connection);
- }
- connection.close();
- } catch (Exception e) {
- LOG.warn("Close connection failed for connection: " + connection + ". This exception will be ignored.",e);
- }
- }
-
- @Override
- public ConnectionPool makeObject(ConnectionKey key) throws Exception {
- ActiveMQConnection delegate = createConnection(key);
-
- ConnectionPool connection = createConnectionPool(delegate);
- connection.setIdleTimeout(getIdleTimeout());
- connection.setExpiryTimeout(getExpiryTimeout());
- connection.setMaximumActiveSessionPerConnection(getMaximumActiveSessionPerConnection());
- connection.setBlockIfSessionPoolIsFull(isBlockIfSessionPoolIsFull());
-
- if (LOG.isTraceEnabled()) {
- LOG.trace("Created new connection: {}", connection);
- }
-
- return connection;
- }
-
- @Override
- public void passivateObject(ConnectionKey key, ConnectionPool connection) throws Exception {
- }
-
- @Override
- public boolean validateObject(ConnectionKey key, ConnectionPool connection) {
- if (connection != null && connection.expiredCheck()) {
- if (LOG.isTraceEnabled()) {
- LOG.trace("Connection has expired: {} and will be destroyed", connection);
- }
-
- return false;
- }
-
- return true;
- }
- });
-
- // Set max idle (not max active) since our connections always idle in the pool.
- this.connectionsPool.setMaxIdle(1);
-
- // We always want our validate method to control when idle objects are evicted.
- this.connectionsPool.setTestOnBorrow(true);
- this.connectionsPool.setTestWhileIdle(true);
+ public PooledConnectionFactory(String brokerURL) {
+ setConnectionFactory(new ActiveMQConnectionFactory(brokerURL));
}
- /**
- * @return the currently configured ConnectionFactory used to create the pooled Connections.
- */
- public ConnectionFactory getConnectionFactory() {
- return connectionFactory;
+ protected void buildFromProperties(Properties props) {
+ ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();
+ activeMQConnectionFactory.buildFromProperties(props);
+ setConnectionFactory(activeMQConnectionFactory);
+ IntrospectionSupport.setProperties(this, new HashMap(props), POOL_PROPS_PREFIX);
}
- /**
- * Sets the ConnectionFactory used to create new pooled Connections.
- * <p/>
- * Updates to this value do not affect Connections that were previously created and placed
- * into the pool. In order to allocate new Connections based off this new ConnectionFactory
- * it is first necessary to {@link clear} the pooled Connections.
- *
- * @param connectionFactory
- * The factory to use to create pooled Connections.
- */
- public void setConnectionFactory(ConnectionFactory connectionFactory) {
- this.connectionFactory = connectionFactory;
+ protected void populateProperties(Properties props) {
+ ((ActiveMQConnectionFactory)getConnectionFactory()).populateProperties(props);
+ IntrospectionSupport.getProperties(this, props, POOL_PROPS_PREFIX);
}
@Override
- public Connection createConnection() throws JMSException {
- return createConnection(null, null);
+ public void setProperties(Properties properties) {
+ buildFromProperties(properties);
}
@Override
- public synchronized Connection createConnection(String userName, String password) throws JMSException {
- if (stopped.get()) {
- LOG.debug("PooledConnectionFactory is stopped, skip create new connection.");
- return null;
- }
-
- ConnectionPool connection = null;
- ConnectionKey key = new ConnectionKey(userName, password);
-
- // This will either return an existing non-expired ConnectionPool or it
- // will create a new one to meet the demand.
- if (connectionsPool.getNumIdle(key) < getMaxConnections()) {
- try {
- // we want borrowObject to return the one we added.
- connectionsPool.setLifo(true);
- connectionsPool.addObject(key);
- } catch (Exception e) {
- throw JMSExceptionSupport.create("Error while attempting to add new Connection to the pool", e);
- }
- } else {
- // now we want the oldest one in the pool.
- connectionsPool.setLifo(false);
- }
-
- try {
-
- // We can race against other threads returning the connection when there is an
- // expiration or idle timeout. We keep pulling out ConnectionPool instances until
- // we win and get a non-closed instance and then increment the reference count
- // under lock to prevent another thread from triggering an expiration check and
- // pulling the rug out from under us.
- while (connection == null) {
- connection = connectionsPool.borrowObject(key);
- synchronized (connection) {
- if (connection.getConnection() != null) {
- connection.incrementReferenceCount();
- break;
- }
-
- // Return the bad one to the pool and let if get destroyed as normal.
- connectionsPool.returnObject(key, connection);
- connection = null;
- }
- }
- } catch (Exception e) {
- throw JMSExceptionSupport.create("Error while attempting to retrieve a connection from the pool", e);
- }
-
- try {
- connectionsPool.returnObject(key, connection);
- } catch (Exception e) {
- throw JMSExceptionSupport.create("Error when returning connection to the pool", e);
- }
-
- return new PooledConnection(connection);
+ public Properties getProperties() {
+ Properties properties = new Properties();
+ populateProperties(properties);
+ return properties;
}
- protected ActiveMQConnection createConnection(ConnectionKey key) throws JMSException {
- if (key.getUserName() == null && key.getPassword() == null) {
- return (ActiveMQConnection)connectionFactory.createConnection();
- } else {
- return (ActiveMQConnection)connectionFactory.createConnection(key.getUserName(), key.getPassword());
- }
- }
@Override
- public void start() {
- LOG.debug("Staring the PooledConnectionFactory: create on start = {}", isCreateConnectionOnStartup());
- stopped.set(false);
- if (isCreateConnectionOnStartup()) {
- try {
- // warm the pool by creating a connection during startup
- createConnection();
- } catch (JMSException e) {
- LOG.warn("Create pooled connection during start failed. This exception will be ignored.", e);
- }
- }
+ public Reference getReference() throws NamingException {
+ return JNDIReferenceFactory.createReference(this.getClass().getName(), this);
}
@Override
- public void stop() {
- LOG.debug("Stopping the PooledConnectionFactory, number of connections in cache: {}",
- connectionsPool.getNumActive());
-
- if (stopped.compareAndSet(false, true)) {
- try {
- connectionsPool.close();
- } catch (Exception e) {
- }
- }
- }
-
- /**
- * Clears all connections from the pool. Each connection that is currently in the pool is
- * closed and removed from the pool. A new connection will be created on the next call to
- * {@link createConnection}. Care should be taken when using this method as Connections that
- * are in use be client's will be closed.
- */
- public void clear() {
-
- if (stopped.get()) {
- return;
- }
-
- this.connectionsPool.clear();
- }
-
- /**
- * Returns the currently configured maximum number of sessions a pooled Connection will
- * create before it either blocks or throws an exception when a new session is requested,
- * depending on configuration.
- *
- * @return the number of session instances that can be taken from a pooled connection.
- */
- public int getMaximumActiveSessionPerConnection() {
- return maximumActiveSessionPerConnection;
- }
-
- /**
- * Sets the maximum number of active sessions per connection
- *
- * @param maximumActiveSessionPerConnection
- * The maximum number of active session per connection in the pool.
- */
- public void setMaximumActiveSessionPerConnection(int maximumActiveSessionPerConnection) {
- this.maximumActiveSessionPerConnection = maximumActiveSessionPerConnection;
- }
-
- /**
- * Controls the behavior of the internal session pool. By default the call to
- * Connection.getSession() will block if the session pool is full. If the
- * argument false is given, it will change the default behavior and instead the
- * call to getSession() will throw a JMSException.
- *
- * The size of the session pool is controlled by the @see #maximumActive
- * property.
- *
- * @param block - if true, the call to getSession() blocks if the pool is full
- * until a session object is available. defaults to true.
- */
- public void setBlockIfSessionPoolIsFull(boolean block) {
- this.blockIfSessionPoolIsFull = block;
- }
-
- /**
- * Returns whether a pooled Connection will enter a blocked state or will throw an Exception
- * once the maximum number of sessions has been borrowed from the the Session Pool.
- *
- * @return true if the pooled Connection createSession method will block when the limit is hit.
- * @see setBlockIfSessionPoolIsFull
- */
- public boolean isBlockIfSessionPoolIsFull() {
- return this.blockIfSessionPoolIsFull;
- }
-
- /**
- * Returns the maximum number to pooled Connections that this factory will allow before it
- * begins to return connections from the pool on calls to ({@link createConnection}.
- *
- * @return the maxConnections that will be created for this pool.
- */
- public int getMaxConnections() {
- return connectionsPool.getMaxIdle();
- }
-
- /**
- * Sets the maximum number of pooled Connections (defaults to one). Each call to
- * {@link createConnection} will result in a new Connection being create up to the max
- * connections value.
- *
- * @param maxConnections the maxConnections to set
- */
- public void setMaxConnections(int maxConnections) {
- this.connectionsPool.setMaxIdle(maxConnections);
- }
-
- /**
- * Gets the Idle timeout value applied to new Connection's that are created by this pool.
- * <p/>
- * The idle timeout is used determine if a Connection instance has sat to long in the pool unused
- * and if so is closed and removed from the pool. The default value is 30 seconds.
- *
- * @return idle timeout value (milliseconds)
- */
- public int getIdleTimeout() {
- return idleTimeout;
- }
-
- /**
- * Sets the idle timeout value for Connection's that are created by this pool in Milliseconds,
- * defaults to 30 seconds.
- * <p/>
- * For a Connection that is in the pool but has no current users the idle timeout determines how
- * long the Connection can live before it is eligible for removal from the pool. Normally the
- * connections are tested when an attempt to check one out occurs so a Connection instance can sit
- * in the pool much longer than its idle timeout if connections are used infrequently.
- *
- * @param idleTimeout
- * The maximum time a pooled Connection can sit unused before it is eligible for removal.
- */
- public void setIdleTimeout(int idleTimeout) {
- this.idleTimeout = idleTimeout;
- }
-
- /**
- * allow connections to expire, irrespective of load or idle time. This is useful with failover
- * to force a reconnect from the pool, to reestablish load balancing or use of the master post recovery
- *
- * @param expiryTimeout non zero in milliseconds
- */
- public void setExpiryTimeout(long expiryTimeout) {
- this.expiryTimeout = expiryTimeout;
- }
-
- /**
- * @return the configured expiration timeout for connections in the pool.
- */
- public long getExpiryTimeout() {
- return expiryTimeout;
+ protected Connection newPooledConnection(ConnectionPool connection) {
+ return new PooledConnection(connection);
}
- /**
- * @return true if a Connection is created immediately on a call to {@link start}.
- */
- public boolean isCreateConnectionOnStartup() {
- return createConnectionOnStartup;
- }
+ @Override
+ protected org.apache.activemq.jms.pool.ConnectionPool createConnectionPool(Connection connection) {
+ return new ConnectionPool(connection) {
+
+ @Override
+ protected Connection wrap(final Connection connection) {
+ // Add a transport Listener so that we can notice if this connection
+ // should be expired due to a connection failure.
+ ((ActiveMQConnection)connection).addTransportListener(new TransportListener() {
+ @Override
+ public void onCommand(Object command) {
+ }
- /**
- * Whether to create a connection on starting this {@link PooledConnectionFactory}.
- * <p/>
- * This can be used to warm-up the pool on startup. Notice that any kind of exception
- * happens during startup is logged at WARN level and ignored.
- *
- * @param createConnectionOnStartup <tt>true</tt> to create a connection on startup
- */
- public void setCreateConnectionOnStartup(boolean createConnectionOnStartup) {
- this.createConnectionOnStartup = createConnectionOnStartup;
- }
+ @Override
+ public void onException(IOException error) {
+ synchronized (this) {
+ setHasExpired(true);
+ LOG.info("Expiring connection {} on IOException: {}" , connection, error);
+ LOG.debug("Expiring connection on IOException", error);
+ }
+ }
- /**
- * Gets the Pool of ConnectionPool instances which are keyed by different ConnectionKeys.
- *
- * @return this factories pool of ConnectionPool instances.
- */
- KeyedObjectPool<ConnectionKey, ConnectionPool> getConnectionsPool() {
- return this.connectionsPool;
- }
+ @Override
+ public void transportInterupted() {
+ }
- /**
- * Sets the number of milliseconds to sleep between runs of the idle Connection eviction thread.
- * When non-positive, no idle object eviction thread will be run, and Connections will only be
- * checked on borrow to determine if they have sat idle for too long or have failed for some
- * other reason.
- * <p/>
- * By default this value is set to -1 and no expiration thread ever runs.
- *
- * @param timeBetweenExpirationCheckMillis
- * The time to wait between runs of the idle Connection eviction thread.
- */
- public void setTimeBetweenExpirationCheckMillis(long timeBetweenExpirationCheckMillis) {
- this.connectionsPool.setTimeBetweenEvictionRunsMillis(timeBetweenExpirationCheckMillis);
- }
+ @Override
+ public void transportResumed() {
+ }
+ });
- /**
- * @return the number of milliseconds to sleep between runs of the idle connection eviction thread.
- */
- public long getTimeBetweenExpirationCheckMillis() {
- return this.connectionsPool.getTimeBetweenEvictionRunsMillis();
- }
+ // make sure that we set the hasFailed flag, in case the transport already failed
+ // prior to the addition of our new TransportListener
+ setHasExpired(((ActiveMQConnection)connection).isTransportFailed());
- /**
- * @return the number of Connections currently in the Pool
- */
- public int getNumConnections() {
- return this.connectionsPool.getNumIdle();
- }
-
- /**
- * Delegate that creates each instance of an ConnectionPool object. Subclasses can override
- * this method to customize the type of connection pool returned.
- *
- * @param connection
- *
- * @return instance of a new ConnectionPool.
- */
- protected ConnectionPool createConnectionPool(ActiveMQConnection connection) {
- return new ConnectionPool(connection);
- }
+ // may want to return an amq EnhancedConnection
+ return connection;
+ }
- @Override
- protected void buildFromProperties(Properties props) {
- ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory();
- activeMQConnectionFactory.buildFromProperties(props);
- connectionFactory = activeMQConnectionFactory;
+ @Override
+ protected void unWrap(Connection connection) {
+ if (connection != null) {
+ ((ActiveMQConnection)connection).cleanUpTempDestinations();
+ }
+ }
+ };
}
- @Override
- protected void populateProperties(Properties props) {
- ((ActiveMQConnectionFactory)connectionFactory).populateProperties(props);
- }
}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/PooledMessageConsumer.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/PooledMessageConsumer.java b/activemq-pool/src/main/java/org/apache/activemq/pool/PooledMessageConsumer.java
deleted file mode 100644
index 4de3416..0000000
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/PooledMessageConsumer.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-
-/**
- * A {@link MessageConsumer} which was created by {@link PooledSession}.
- */
-public class PooledMessageConsumer implements MessageConsumer {
-
- private final PooledSession session;
- private final MessageConsumer delegate;
-
- /**
- * Wraps the message consumer.
- *
- * @param session the pooled session
- * @param delegate the created consumer to wrap
- */
- public PooledMessageConsumer(PooledSession session, MessageConsumer delegate) {
- this.session = session;
- this.delegate = delegate;
- }
-
- @Override
- public void close() throws JMSException {
- // ensure session removes consumer as its closed now
- session.onConsumerClose(delegate);
- delegate.close();
- }
-
- @Override
- public MessageListener getMessageListener() throws JMSException {
- return delegate.getMessageListener();
- }
-
- @Override
- public String getMessageSelector() throws JMSException {
- return delegate.getMessageSelector();
- }
-
- @Override
- public Message receive() throws JMSException {
- return delegate.receive();
- }
-
- @Override
- public Message receive(long timeout) throws JMSException {
- return delegate.receive(timeout);
- }
-
- @Override
- public Message receiveNoWait() throws JMSException {
- return delegate.receiveNoWait();
- }
-
- @Override
- public void setMessageListener(MessageListener listener) throws JMSException {
- delegate.setMessageListener(listener);
- }
-
- @Override
- public String toString() {
- return "PooledMessageConsumer { " + delegate + " }";
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/PooledProducer.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/PooledProducer.java b/activemq-pool/src/main/java/org/apache/activemq/pool/PooledProducer.java
deleted file mode 100644
index 71014b4..0000000
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/PooledProducer.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageProducer;
-
-import org.apache.activemq.ActiveMQMessageProducer;
-
-/**
- * A pooled {@link MessageProducer}
- */
-public class PooledProducer implements MessageProducer {
-
- private final ActiveMQMessageProducer messageProducer;
- private final Destination destination;
-
- private int deliveryMode;
- private boolean disableMessageID;
- private boolean disableMessageTimestamp;
- private int priority;
- private long timeToLive;
-
- public PooledProducer(ActiveMQMessageProducer messageProducer, Destination destination) throws JMSException {
- this.messageProducer = messageProducer;
- this.destination = destination;
-
- this.deliveryMode = messageProducer.getDeliveryMode();
- this.disableMessageID = messageProducer.getDisableMessageID();
- this.disableMessageTimestamp = messageProducer.getDisableMessageTimestamp();
- this.priority = messageProducer.getPriority();
- this.timeToLive = messageProducer.getTimeToLive();
- }
-
- @Override
- public void close() throws JMSException {
- }
-
- @Override
- public void send(Destination destination, Message message) throws JMSException {
- send(destination, message, getDeliveryMode(), getPriority(), getTimeToLive());
- }
-
- @Override
- public void send(Message message) throws JMSException {
- send(destination, message, getDeliveryMode(), getPriority(), getTimeToLive());
- }
-
- @Override
- public void send(Message message, int deliveryMode, int priority, long timeToLive) throws JMSException {
- send(destination, message, deliveryMode, priority, timeToLive);
- }
-
- @Override
- public void send(Destination destination, Message message, int deliveryMode, int priority, long timeToLive) throws JMSException {
- if (destination == null) {
- destination = this.destination;
- }
- ActiveMQMessageProducer messageProducer = getMessageProducer();
-
- // just in case let only one thread send at once
- synchronized (messageProducer) {
- messageProducer.send(destination, message, deliveryMode, priority, timeToLive);
- }
- }
-
- @Override
- public Destination getDestination() {
- return destination;
- }
-
- @Override
- public int getDeliveryMode() {
- return deliveryMode;
- }
-
- @Override
- public void setDeliveryMode(int deliveryMode) {
- this.deliveryMode = deliveryMode;
- }
-
- @Override
- public boolean getDisableMessageID() {
- return disableMessageID;
- }
-
- @Override
- public void setDisableMessageID(boolean disableMessageID) {
- this.disableMessageID = disableMessageID;
- }
-
- @Override
- public boolean getDisableMessageTimestamp() {
- return disableMessageTimestamp;
- }
-
- @Override
- public void setDisableMessageTimestamp(boolean disableMessageTimestamp) {
- this.disableMessageTimestamp = disableMessageTimestamp;
- }
-
- @Override
- public int getPriority() {
- return priority;
- }
-
- @Override
- public void setPriority(int priority) {
- this.priority = priority;
- }
-
- @Override
- public long getTimeToLive() {
- return timeToLive;
- }
-
- @Override
- public void setTimeToLive(long timeToLive) {
- this.timeToLive = timeToLive;
- }
-
- // Implementation methods
- // -------------------------------------------------------------------------
- protected ActiveMQMessageProducer getMessageProducer() {
- return messageProducer;
- }
-
- @Override
- public String toString() {
- return "PooledProducer { " + messageProducer + " }";
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/PooledQueueSender.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/PooledQueueSender.java b/activemq-pool/src/main/java/org/apache/activemq/pool/PooledQueueSender.java
deleted file mode 100644
index 6624a3a..0000000
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/PooledQueueSender.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.Queue;
-import javax.jms.QueueSender;
-
-import org.apache.activemq.ActiveMQQueueSender;
-
-/**
- * {@link QueueSender} instance that is created and managed by the PooledConnection.
- */
-public class PooledQueueSender extends PooledProducer implements QueueSender {
-
- public PooledQueueSender(ActiveMQQueueSender messageProducer, Destination destination) throws JMSException {
- super(messageProducer, destination);
- }
-
- @Override
- public void send(Queue queue, Message message, int i, int i1, long l) throws JMSException {
- getQueueSender().send(queue, message, i, i1, l);
- }
-
- @Override
- public void send(Queue queue, Message message) throws JMSException {
- getQueueSender().send(queue, message);
- }
-
- @Override
- public Queue getQueue() throws JMSException {
- return (Queue) getDestination();
- }
-
- protected ActiveMQQueueSender getQueueSender() {
- return (ActiveMQQueueSender) getMessageProducer();
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/PooledSession.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/PooledSession.java b/activemq-pool/src/main/java/org/apache/activemq/pool/PooledSession.java
deleted file mode 100644
index 6e206f6..0000000
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/PooledSession.java
+++ /dev/null
@@ -1,449 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-import java.io.Serializable;
-import java.util.Iterator;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-import javax.jms.BytesMessage;
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.MapMessage;
-import javax.jms.Message;
-import javax.jms.MessageConsumer;
-import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
-import javax.jms.ObjectMessage;
-import javax.jms.Queue;
-import javax.jms.QueueBrowser;
-import javax.jms.QueueReceiver;
-import javax.jms.QueueSender;
-import javax.jms.QueueSession;
-import javax.jms.Session;
-import javax.jms.StreamMessage;
-import javax.jms.TemporaryQueue;
-import javax.jms.TemporaryTopic;
-import javax.jms.TextMessage;
-import javax.jms.Topic;
-import javax.jms.TopicPublisher;
-import javax.jms.TopicSession;
-import javax.jms.TopicSubscriber;
-import javax.jms.XASession;
-import javax.transaction.xa.XAResource;
-
-import org.apache.activemq.ActiveMQMessageProducer;
-import org.apache.activemq.ActiveMQQueueSender;
-import org.apache.activemq.ActiveMQSession;
-import org.apache.activemq.ActiveMQTopicPublisher;
-import org.apache.activemq.AlreadyClosedException;
-import org.apache.activemq.util.JMSExceptionSupport;
-import org.apache.commons.pool.KeyedObjectPool;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class PooledSession implements Session, TopicSession, QueueSession, XASession {
- private static final transient Logger LOG = LoggerFactory.getLogger(PooledSession.class);
-
- private final SessionKey key;
- private final KeyedObjectPool<SessionKey, PooledSession> sessionPool;
- private final CopyOnWriteArrayList<MessageConsumer> consumers = new CopyOnWriteArrayList<MessageConsumer>();
- private final CopyOnWriteArrayList<QueueBrowser> browsers = new CopyOnWriteArrayList<QueueBrowser>();
- private final CopyOnWriteArrayList<PooledSessionEventListener> sessionEventListeners =
- new CopyOnWriteArrayList<PooledSessionEventListener>();
-
- private ActiveMQSession session;
- private ActiveMQMessageProducer messageProducer;
- private ActiveMQQueueSender queueSender;
- private ActiveMQTopicPublisher topicPublisher;
- private boolean transactional = true;
- private boolean ignoreClose;
- private boolean isXa;
-
- public PooledSession(SessionKey key, ActiveMQSession session, KeyedObjectPool<SessionKey, PooledSession> sessionPool) {
- this.key = key;
- this.session = session;
- this.sessionPool = sessionPool;
- this.transactional = session.isTransacted();
- }
-
- public void addSessionEventListener(PooledSessionEventListener listener) {
- // only add if really needed
- if (!sessionEventListeners.contains(listener)) {
- this.sessionEventListeners.add(listener);
- }
- }
-
- protected boolean isIgnoreClose() {
- return ignoreClose;
- }
-
- protected void setIgnoreClose(boolean ignoreClose) {
- this.ignoreClose = ignoreClose;
- }
-
- @Override
- public void close() throws JMSException {
- if (!ignoreClose) {
- boolean invalidate = false;
- try {
- // lets reset the session
- getInternalSession().setMessageListener(null);
-
- // Close any consumers and browsers that may have been created.
- for (Iterator<MessageConsumer> iter = consumers.iterator(); iter.hasNext();) {
- MessageConsumer consumer = iter.next();
- consumer.close();
- }
-
- for (Iterator<QueueBrowser> iter = browsers.iterator(); iter.hasNext();) {
- QueueBrowser browser = iter.next();
- browser.close();
- }
-
- if (transactional && !isXa) {
- try {
- getInternalSession().rollback();
- } catch (JMSException e) {
- invalidate = true;
- LOG.warn("Caught exception trying rollback() when putting session back into the pool, will invalidate. " + e, e);
- }
- }
- } catch (JMSException ex) {
- invalidate = true;
- LOG.warn("Caught exception trying close() when putting session back into the pool, will invalidate. " + ex, ex);
- } finally {
- consumers.clear();
- browsers.clear();
- for (PooledSessionEventListener listener : this.sessionEventListeners) {
- listener.onSessionClosed(this);
- }
- sessionEventListeners.clear();
- }
-
- if (invalidate) {
- // lets close the session and not put the session back into the pool
- // instead invalidate it so the pool can create a new one on demand.
- if (session != null) {
- try {
- session.close();
- } catch (JMSException e1) {
- LOG.trace("Ignoring exception on close as discarding session: " + e1, e1);
- }
- session = null;
- }
- try {
- sessionPool.invalidateObject(key, this);
- } catch (Exception e) {
- LOG.trace("Ignoring exception on invalidateObject as discarding session: " + e, e);
- }
- } else {
- try {
- sessionPool.returnObject(key, this);
- } catch (Exception e) {
- throw JMSExceptionSupport.create(e);
- }
- }
- }
- }
-
- @Override
- public void commit() throws JMSException {
- getInternalSession().commit();
- }
-
- @Override
- public BytesMessage createBytesMessage() throws JMSException {
- return getInternalSession().createBytesMessage();
- }
-
- @Override
- public MapMessage createMapMessage() throws JMSException {
- return getInternalSession().createMapMessage();
- }
-
- @Override
- public Message createMessage() throws JMSException {
- return getInternalSession().createMessage();
- }
-
- @Override
- public ObjectMessage createObjectMessage() throws JMSException {
- return getInternalSession().createObjectMessage();
- }
-
- @Override
- public ObjectMessage createObjectMessage(Serializable serializable) throws JMSException {
- return getInternalSession().createObjectMessage(serializable);
- }
-
- @Override
- public Queue createQueue(String s) throws JMSException {
- return getInternalSession().createQueue(s);
- }
-
- @Override
- public StreamMessage createStreamMessage() throws JMSException {
- return getInternalSession().createStreamMessage();
- }
-
- @Override
- public TemporaryQueue createTemporaryQueue() throws JMSException {
- TemporaryQueue result;
-
- result = getInternalSession().createTemporaryQueue();
-
- // Notify all of the listeners of the created temporary Queue.
- for (PooledSessionEventListener listener : this.sessionEventListeners) {
- listener.onTemporaryQueueCreate(result);
- }
-
- return result;
- }
-
- @Override
- public TemporaryTopic createTemporaryTopic() throws JMSException {
- TemporaryTopic result;
-
- result = getInternalSession().createTemporaryTopic();
-
- // Notify all of the listeners of the created temporary Topic.
- for (PooledSessionEventListener listener : this.sessionEventListeners) {
- listener.onTemporaryTopicCreate(result);
- }
-
- return result;
- }
-
- @Override
- public void unsubscribe(String s) throws JMSException {
- getInternalSession().unsubscribe(s);
- }
-
- @Override
- public TextMessage createTextMessage() throws JMSException {
- return getInternalSession().createTextMessage();
- }
-
- @Override
- public TextMessage createTextMessage(String s) throws JMSException {
- return getInternalSession().createTextMessage(s);
- }
-
- @Override
- public Topic createTopic(String s) throws JMSException {
- return getInternalSession().createTopic(s);
- }
-
- @Override
- public int getAcknowledgeMode() throws JMSException {
- return getInternalSession().getAcknowledgeMode();
- }
-
- @Override
- public boolean getTransacted() throws JMSException {
- return getInternalSession().getTransacted();
- }
-
- @Override
- public void recover() throws JMSException {
- getInternalSession().recover();
- }
-
- @Override
- public void rollback() throws JMSException {
- getInternalSession().rollback();
- }
-
- @Override
- public XAResource getXAResource() {
- if (session == null) {
- throw new IllegalStateException("Session is closed");
- }
- return session.getTransactionContext();
- }
-
- @Override
- public Session getSession() {
- return this;
- }
-
- @Override
- public void run() {
- if (session != null) {
- session.run();
- }
- }
-
- // Consumer related methods
- // -------------------------------------------------------------------------
- @Override
- public QueueBrowser createBrowser(Queue queue) throws JMSException {
- return addQueueBrowser(getInternalSession().createBrowser(queue));
- }
-
- @Override
- public QueueBrowser createBrowser(Queue queue, String selector) throws JMSException {
- return addQueueBrowser(getInternalSession().createBrowser(queue, selector));
- }
-
- @Override
- public MessageConsumer createConsumer(Destination destination) throws JMSException {
- return addConsumer(getInternalSession().createConsumer(destination));
- }
-
- @Override
- public MessageConsumer createConsumer(Destination destination, String selector) throws JMSException {
- return addConsumer(getInternalSession().createConsumer(destination, selector));
- }
-
- @Override
- public MessageConsumer createConsumer(Destination destination, String selector, boolean noLocal) throws JMSException {
- return addConsumer(getInternalSession().createConsumer(destination, selector, noLocal));
- }
-
- @Override
- public TopicSubscriber createDurableSubscriber(Topic topic, String selector) throws JMSException {
- return addTopicSubscriber(getInternalSession().createDurableSubscriber(topic, selector));
- }
-
- @Override
- public TopicSubscriber createDurableSubscriber(Topic topic, String name, String selector, boolean noLocal) throws JMSException {
- return addTopicSubscriber(getInternalSession().createDurableSubscriber(topic, name, selector, noLocal));
- }
-
- @Override
- public MessageListener getMessageListener() throws JMSException {
- return getInternalSession().getMessageListener();
- }
-
- @Override
- public void setMessageListener(MessageListener messageListener) throws JMSException {
- getInternalSession().setMessageListener(messageListener);
- }
-
- @Override
- public TopicSubscriber createSubscriber(Topic topic) throws JMSException {
- return addTopicSubscriber(getInternalSession().createSubscriber(topic));
- }
-
- @Override
- public TopicSubscriber createSubscriber(Topic topic, String selector, boolean local) throws JMSException {
- return addTopicSubscriber(getInternalSession().createSubscriber(topic, selector, local));
- }
-
- @Override
- public QueueReceiver createReceiver(Queue queue) throws JMSException {
- return addQueueReceiver(getInternalSession().createReceiver(queue));
- }
-
- @Override
- public QueueReceiver createReceiver(Queue queue, String selector) throws JMSException {
- return addQueueReceiver(getInternalSession().createReceiver(queue, selector));
- }
-
- // Producer related methods
- // -------------------------------------------------------------------------
- @Override
- public MessageProducer createProducer(Destination destination) throws JMSException {
- return new PooledProducer(getMessageProducer(), destination);
- }
-
- @Override
- public QueueSender createSender(Queue queue) throws JMSException {
- return new PooledQueueSender(getQueueSender(), queue);
- }
-
- @Override
- public TopicPublisher createPublisher(Topic topic) throws JMSException {
- return new PooledTopicPublisher(getTopicPublisher(), topic);
- }
-
- /**
- * Callback invoked when the consumer is closed.
- * <p/>
- * This is used to keep track of an explicit closed consumer created by this
- * session, by which we know do not need to keep track of the consumer, as
- * its already closed.
- *
- * @param consumer
- * the consumer which is being closed
- */
- protected void onConsumerClose(MessageConsumer consumer) {
- consumers.remove(consumer);
- }
-
- public ActiveMQSession getInternalSession() throws AlreadyClosedException {
- if (session == null) {
- throw new AlreadyClosedException("The session has already been closed");
- }
- return session;
- }
-
- public ActiveMQMessageProducer getMessageProducer() throws JMSException {
- if (messageProducer == null) {
- messageProducer = (ActiveMQMessageProducer) getInternalSession().createProducer(null);
- }
- return messageProducer;
- }
-
- public ActiveMQQueueSender getQueueSender() throws JMSException {
- if (queueSender == null) {
- queueSender = (ActiveMQQueueSender) getInternalSession().createSender(null);
- }
- return queueSender;
- }
-
- public ActiveMQTopicPublisher getTopicPublisher() throws JMSException {
- if (topicPublisher == null) {
- topicPublisher = (ActiveMQTopicPublisher) getInternalSession().createPublisher(null);
- }
- return topicPublisher;
- }
-
- private QueueBrowser addQueueBrowser(QueueBrowser browser) {
- browsers.add(browser);
- return browser;
- }
-
- private MessageConsumer addConsumer(MessageConsumer consumer) {
- consumers.add(consumer);
- // must wrap in PooledMessageConsumer to ensure the onConsumerClose method is
- // invoked when the returned consumer is closed, to avoid memory leak in this
- // session class in case many consumers is created
- return new PooledMessageConsumer(this, consumer);
- }
-
- private TopicSubscriber addTopicSubscriber(TopicSubscriber subscriber) {
- consumers.add(subscriber);
- return subscriber;
- }
-
- private QueueReceiver addQueueReceiver(QueueReceiver receiver) {
- consumers.add(receiver);
- return receiver;
- }
-
- public void setIsXa(boolean isXa) {
- this.isXa = isXa;
- }
-
- @Override
- public String toString() {
- return "PooledSession { " + session + " }";
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/PooledSessionEventListener.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/PooledSessionEventListener.java b/activemq-pool/src/main/java/org/apache/activemq/pool/PooledSessionEventListener.java
deleted file mode 100644
index 5081605..0000000
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/PooledSessionEventListener.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.activemq.pool;
-
-import javax.jms.TemporaryQueue;
-import javax.jms.TemporaryTopic;
-
-interface PooledSessionEventListener {
-
- /**
- * Called on successful creation of a new TemporaryQueue.
- *
- * @param tempQueue
- * The TemporaryQueue just created.
- */
- void onTemporaryQueueCreate(TemporaryQueue tempQueue);
-
- /**
- * Called on successful creation of a new TemporaryTopic.
- *
- * @param tempTopic
- * The TemporaryTopic just created.
- */
- void onTemporaryTopicCreate(TemporaryTopic tempTopic);
-
- /**
- * Called when the PooledSession is closed.
- *
- * @param session
- * The PooledSession that has been closed.
- */
- void onSessionClosed(PooledSession session);
-
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/PooledTopicPublisher.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/PooledTopicPublisher.java b/activemq-pool/src/main/java/org/apache/activemq/pool/PooledTopicPublisher.java
deleted file mode 100644
index 7b2af14..0000000
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/PooledTopicPublisher.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-import javax.jms.Destination;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.Topic;
-import javax.jms.TopicPublisher;
-
-import org.apache.activemq.ActiveMQTopicPublisher;
-
-/**
- * A {@link TopicPublisher} instance that is created and managed by a PooledConnection.
- */
-public class PooledTopicPublisher extends PooledProducer implements TopicPublisher {
-
- public PooledTopicPublisher(ActiveMQTopicPublisher messageProducer, Destination destination) throws JMSException {
- super(messageProducer, destination);
- }
-
- @Override
- public Topic getTopic() throws JMSException {
- return (Topic) getDestination();
- }
-
- @Override
- public void publish(Message message) throws JMSException {
- getTopicPublisher().publish((Topic) getDestination(), message);
- }
-
- @Override
- public void publish(Message message, int i, int i1, long l) throws JMSException {
- getTopicPublisher().publish((Topic) getDestination(), message, i, i1, l);
- }
-
- @Override
- public void publish(Topic topic, Message message) throws JMSException {
- getTopicPublisher().publish(topic, message);
- }
-
- @Override
- public void publish(Topic topic, Message message, int i, int i1, long l) throws JMSException {
- getTopicPublisher().publish(topic, message, i, i1, l);
- }
-
- protected ActiveMQTopicPublisher getTopicPublisher() {
- return (ActiveMQTopicPublisher) getMessageProducer();
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/SessionKey.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/SessionKey.java b/activemq-pool/src/main/java/org/apache/activemq/pool/SessionKey.java
deleted file mode 100644
index 1e2cffd..0000000
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/SessionKey.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-/**
- * A cache key for the session details used to locate PooledSession intances.
- */
-public class SessionKey {
-
- private final boolean transacted;
- private final int ackMode;
-
- private int hash;
-
- public SessionKey(boolean transacted, int ackMode) {
- this.transacted = transacted;
- this.ackMode = ackMode;
- hash = ackMode;
- if (transacted) {
- hash = 31 * hash + 1;
- }
- }
-
- public int hashCode() {
- return hash;
- }
-
- public boolean equals(Object that) {
- if (this == that) {
- return true;
- }
- if (that instanceof SessionKey) {
- return equals((SessionKey) that);
- }
- return false;
- }
-
- public boolean equals(SessionKey that) {
- return this.transacted == that.transacted && this.ackMode == that.ackMode;
- }
-
- public boolean isTransacted() {
- return transacted;
- }
-
- public int getAckMode() {
- return ackMode;
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/XaConnectionPool.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/XaConnectionPool.java b/activemq-pool/src/main/java/org/apache/activemq/pool/XaConnectionPool.java
deleted file mode 100644
index e0699fe..0000000
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/XaConnectionPool.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-import javax.jms.JMSException;
-import javax.jms.Session;
-import javax.transaction.RollbackException;
-import javax.transaction.Status;
-import javax.transaction.SystemException;
-import javax.transaction.TransactionManager;
-import javax.transaction.xa.XAResource;
-
-import org.apache.activemq.ActiveMQConnection;
-
-/**
- * An XA-aware connection pool. When a session is created and an xa transaction is active,
- * the session will automatically be enlisted in the current transaction.
- *
- * @author gnodet
- */
-public class XaConnectionPool extends ConnectionPool {
-
- private final TransactionManager transactionManager;
-
- public XaConnectionPool(ActiveMQConnection connection, TransactionManager transactionManager) {
- super(connection);
- this.transactionManager = transactionManager;
- }
-
- @Override
- public Session createSession(boolean transacted, int ackMode) throws JMSException {
- try {
- boolean isXa = (transactionManager != null && transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION);
- if (isXa) {
- // if the xa tx aborts inflight we don't want to auto create a local transaction or auto ack
- transacted = false;
- ackMode = Session.CLIENT_ACKNOWLEDGE;
- } else if (transactionManager != null) {
- // cmt or transactionManager managed
- transacted = false;
- if (ackMode == Session.SESSION_TRANSACTED) {
- ackMode = Session.AUTO_ACKNOWLEDGE;
- }
- }
- PooledSession session = (PooledSession) super.createSession(transacted, ackMode);
- if (isXa) {
- session.setIgnoreClose(true);
- session.setIsXa(true);
- transactionManager.getTransaction().registerSynchronization(new Synchronization(session));
- incrementReferenceCount();
- transactionManager.getTransaction().enlistResource(createXaResource(session));
- } else {
- session.setIgnoreClose(false);
- }
- return session;
- } catch (RollbackException e) {
- final JMSException jmsException = new JMSException("Rollback Exception");
- jmsException.initCause(e);
- throw jmsException;
- } catch (SystemException e) {
- final JMSException jmsException = new JMSException("System Exception");
- jmsException.initCause(e);
- throw jmsException;
- }
- }
-
- protected XAResource createXaResource(PooledSession session) throws JMSException {
- return session.getXAResource();
- }
-
- protected class Synchronization implements javax.transaction.Synchronization {
- private final PooledSession session;
-
- private Synchronization(PooledSession session) {
- this.session = session;
- }
-
- @Override
- public void beforeCompletion() {
- }
-
- @Override
- public void afterCompletion(int status) {
- try {
- // This will return session to the pool.
- session.setIgnoreClose(false);
- session.close();
- session.setIgnoreClose(true);
- session.setIsXa(false);
- decrementReferenceCount();
- } catch (JMSException e) {
- throw new RuntimeException(e);
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/XaPooledConnectionFactory.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/XaPooledConnectionFactory.java b/activemq-pool/src/main/java/org/apache/activemq/pool/XaPooledConnectionFactory.java
index c469d92..09a1c0a 100644
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/XaPooledConnectionFactory.java
+++ b/activemq-pool/src/main/java/org/apache/activemq/pool/XaPooledConnectionFactory.java
@@ -16,167 +16,143 @@
*/
package org.apache.activemq.pool;
-import java.io.Serializable;
-import java.util.Hashtable;
+import java.io.IOException;
+import java.util.HashMap;
import java.util.Properties;
+import javax.jms.Connection;
import javax.jms.JMSException;
-import javax.jms.QueueConnection;
-import javax.jms.QueueConnectionFactory;
-import javax.jms.TopicConnection;
-import javax.jms.TopicConnectionFactory;
-import javax.naming.Binding;
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.Name;
-import javax.naming.NamingEnumeration;
-import javax.naming.spi.ObjectFactory;
-import javax.transaction.TransactionManager;
-
+import javax.jms.Session;
+import javax.jms.XAConnection;
+import javax.jms.XASession;
+import javax.naming.NamingException;
+import javax.naming.Reference;
+import javax.transaction.xa.XAResource;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
+import org.apache.activemq.ActiveMQSession;
+import org.apache.activemq.ActiveMQXAConnectionFactory;
+import org.apache.activemq.Service;
+import org.apache.activemq.jms.pool.PooledSession;
+import org.apache.activemq.jms.pool.SessionKey;
+import org.apache.activemq.jms.pool.XaConnectionPool;
+import org.apache.activemq.jndi.JNDIReferenceFactory;
+import org.apache.activemq.jndi.JNDIStorableInterface;
+import org.apache.activemq.transport.TransportListener;
import org.apache.activemq.util.IntrospectionSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * A pooled connection factory that automatically enlists
- * sessions in the current active XA transaction if any.
- */
-public class XaPooledConnectionFactory extends PooledConnectionFactory implements ObjectFactory,
- Serializable, QueueConnectionFactory, TopicConnectionFactory {
-
- private static final transient Logger LOG = LoggerFactory.getLogger(XaPooledConnectionFactory.class);
- private TransactionManager transactionManager;
- private boolean tmFromJndi = false;
- private String tmJndiName = "java:/TransactionManager";
- private String brokerUrl = null;
+ * Add Service and Referenceable and TransportListener to @link{org.apache.activemq.jms.pool.XaPooledConnectionFactory}
+ *
+ * @org.apache.xbean.XBean element=xaPooledConnectionFactory"
+ */
+public class XaPooledConnectionFactory extends org.apache.activemq.jms.pool.XaPooledConnectionFactory implements JNDIStorableInterface, Service {
+ public static final String POOL_PROPS_PREFIX = "pool";
+ private static final transient Logger LOG = LoggerFactory.getLogger(org.apache.activemq.jms.pool.XaPooledConnectionFactory.class);
public XaPooledConnectionFactory() {
super();
}
- public XaPooledConnectionFactory(ActiveMQConnectionFactory connectionFactory) {
- super(connectionFactory);
- }
-
- public XaPooledConnectionFactory(String brokerURL) {
- super(brokerURL);
- }
-
- public TransactionManager getTransactionManager() {
- if (transactionManager == null && tmFromJndi) {
- try {
- transactionManager = (TransactionManager) new InitialContext().lookup(getTmJndiName());
- } catch (Throwable ignored) {
- if (LOG.isTraceEnabled()) {
- LOG.trace("exception on tmFromJndi: " + getTmJndiName(), ignored);
- }
- }
- }
- return transactionManager;
- }
-
- public void setTransactionManager(TransactionManager transactionManager) {
- this.transactionManager = transactionManager;
+ public XaPooledConnectionFactory(ActiveMQXAConnectionFactory connectionFactory) {
+ setConnectionFactory(connectionFactory);
}
@Override
- protected ConnectionPool createConnectionPool(ActiveMQConnection connection) {
- return new XaConnectionPool(connection, getTransactionManager());
- }
-
- @Override
- public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
- setTmFromJndi(true);
- configFromJndiConf(obj);
- if (environment != null) {
- IntrospectionSupport.setProperties(this, environment);
- }
- return this;
- }
-
- private void configFromJndiConf(Object rootContextName) {
- if (rootContextName instanceof String) {
- String name = (String) rootContextName;
- name = name.substring(0, name.lastIndexOf('/')) + "/conf" + name.substring(name.lastIndexOf('/'));
- try {
- InitialContext ctx = new InitialContext();
- NamingEnumeration bindings = ctx.listBindings(name);
-
- while (bindings.hasMore()) {
- Binding bd = (Binding)bindings.next();
- IntrospectionSupport.setProperty(this, bd.getName(), bd.getObject());
+ protected org.apache.activemq.jms.pool.ConnectionPool createConnectionPool(Connection connection) {
+ return new XaConnectionPool(connection, getTransactionManager()) {
+
+ @Override
+ protected Session makeSession(SessionKey key) throws JMSException {
+ if (connection instanceof XAConnection) {
+ return ((XAConnection)connection).createXASession();
+ } else {
+ return connection.createSession(key.isTransacted(), key.getAckMode());
}
+ }
- } catch (Exception ignored) {
- if (LOG.isTraceEnabled()) {
- LOG.trace("exception on config from jndi: " + name, ignored);
+ @Override
+ protected XAResource createXaResource(PooledSession session) throws JMSException {
+ if (session.getInternalSession() instanceof XASession) {
+ return ((XASession)session.getInternalSession()).getXAResource();
+ } else {
+ return ((ActiveMQSession)session.getInternalSession()).getTransactionContext();
}
}
- }
- }
- public void setBrokerUrl(String url) {
- if (brokerUrl == null || !brokerUrl.equals(url)) {
- brokerUrl = url;
- setConnectionFactory(new ActiveMQConnectionFactory(brokerUrl));
- }
- }
- public String getTmJndiName() {
- return tmJndiName;
- }
-
- public void setTmJndiName(String tmJndiName) {
- this.tmJndiName = tmJndiName;
- }
-
- public boolean isTmFromJndi() {
- return tmFromJndi;
- }
-
- /**
- * Allow transaction manager resolution from JNDI (ee deployment)
- * @param tmFromJndi
- */
- public void setTmFromJndi(boolean tmFromJndi) {
- this.tmFromJndi = tmFromJndi;
- }
+ @Override
+ protected Connection wrap(final Connection connection) {
+ // Add a transport Listener so that we can notice if this connection
+ // should be expired due to a connection failure.
+ ((ActiveMQConnection)connection).addTransportListener(new TransportListener() {
+ @Override
+ public void onCommand(Object command) {
+ }
+
+ @Override
+ public void onException(IOException error) {
+ synchronized (this) {
+ setHasExpired(true);
+ LOG.info("Expiring connection " + connection + " on IOException: " + error);
+ LOG.debug("Expiring connection on IOException", error);
+ }
+ }
+
+ @Override
+ public void transportInterupted() {
+ }
+
+ @Override
+ public void transportResumed() {
+ }
+ });
+
+ // make sure that we set the hasFailed flag, in case the transport already failed
+ // prior to the addition of our new TransportListener
+ setHasExpired(((ActiveMQConnection) connection).isTransportFailed());
+
+ // may want to return an amq EnhancedConnection
+ return connection;
+ }
- @Override
- public QueueConnection createQueueConnection() throws JMSException {
- return (QueueConnection) createConnection();
+ @Override
+ protected void unWrap(Connection connection) {
+ if (connection != null) {
+ ((ActiveMQConnection)connection).cleanUpTempDestinations();
+ }
+ }
+ };
}
- @Override
- public QueueConnection createQueueConnection(String userName, String password) throws JMSException {
- return (QueueConnection) createConnection(userName, password);
+ protected void buildFromProperties(Properties props) {
+ ActiveMQConnectionFactory activeMQConnectionFactory = props.containsKey("xaAckMode") ?
+ new ActiveMQXAConnectionFactory() : new ActiveMQConnectionFactory();
+ activeMQConnectionFactory.buildFromProperties(props);
+ setConnectionFactory(activeMQConnectionFactory);
+ IntrospectionSupport.setProperties(this, new HashMap(props), POOL_PROPS_PREFIX);
}
- @Override
- public TopicConnection createTopicConnection() throws JMSException {
- return (TopicConnection) createConnection();
+ protected void populateProperties(Properties props) {
+ ((ActiveMQConnectionFactory)getConnectionFactory()).populateProperties(props);
+ IntrospectionSupport.getProperties(this, props, POOL_PROPS_PREFIX);
}
@Override
- public TopicConnection createTopicConnection(String userName, String password) throws JMSException {
- return (TopicConnection) createConnection(userName, password);
+ public void setProperties(Properties properties) {
+ buildFromProperties(properties);
}
@Override
- protected void buildFromProperties(Properties props) {
- super.buildFromProperties(props);
- for (String v : new String[]{"tmFromJndi", "tmJndiName"}) {
- if (props.containsKey(v)) {
- IntrospectionSupport.setProperty(this, v, props.getProperty(v));
- }
- }
+ public Properties getProperties() {
+ Properties properties = new Properties();
+ populateProperties(properties);
+ return properties;
}
@Override
- protected void populateProperties(Properties props) {
- super.populateProperties(props);
- props.setProperty("tmFromJndi", String.valueOf(isTmFromJndi()));
- props.setProperty("tmJndiName", tmJndiName);
+ public Reference getReference() throws NamingException {
+ return JNDIReferenceFactory.createReference(this.getClass().getName(), this);
}
}
[4/6] https://issues.apache.org/jira/browse/AMQ-4757
activemq-jms-pool a generic jms xa pool derived from activemq-pool which
activemq-pool now extends with amq specifics
Posted by gt...@apache.org.
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionTempDestCleanupTest.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionTempDestCleanupTest.java b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionTempDestCleanupTest.java
new file mode 100644
index 0000000..8afdf90
--- /dev/null
+++ b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionTempDestCleanupTest.java
@@ -0,0 +1,223 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.activemq.jms.pool;
+
+import static org.junit.Assert.assertTrue;
+
+import javax.jms.Connection;
+import javax.jms.Destination;
+import javax.jms.JMSException;
+import javax.jms.Session;
+import javax.jms.TemporaryQueue;
+
+import org.apache.activemq.ActiveMQConnectionFactory;
+import org.apache.activemq.broker.BrokerService;
+import org.apache.activemq.broker.region.RegionBroker;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Test of lingering temporary destinations on pooled connections when the
+ * underlying connections are reused. Also tests that closing one
+ * PooledConnection does not delete the temporary destinations of another
+ * PooledConnection that uses the same underlying ConnectionPool.
+ *
+ * jira: AMQ-3457
+ */
+public class PooledConnectionTempDestCleanupTest {
+
+ @SuppressWarnings("unused")
+ private static final Logger LOG = LoggerFactory.getLogger(PooledConnectionTempDestCleanupTest.class);
+
+ protected BrokerService embeddedBroker;
+
+ protected ActiveMQConnectionFactory directConnFact;
+ protected Connection directConn1;
+ protected Connection directConn2;
+
+ protected PooledConnectionFactory pooledConnFact;
+ protected Connection pooledConn1;
+ protected Connection pooledConn2;
+
+ protected TemporaryQueue tempDest;
+ protected TemporaryQueue otherTempDest;
+
+ /**
+ * Prepare to run a test case: create, configure, and start the embedded
+ * broker, as well as creating the client connections to the broker.
+ */
+ @Before
+ public void prepTest() throws java.lang.Exception {
+ embeddedBroker = new BrokerService();
+ configureBroker(embeddedBroker);
+ embeddedBroker.start();
+ embeddedBroker.waitUntilStarted();
+
+ // Create the ActiveMQConnectionFactory and the PooledConnectionFactory.
+ directConnFact = new ActiveMQConnectionFactory(embeddedBroker.getVmConnectorURI());
+ pooledConnFact = new PooledConnectionFactory();
+ pooledConnFact.setConnectionFactory(directConnFact);
+
+ // Prepare the connections
+ directConn1 = directConnFact.createConnection();
+ directConn1.start();
+ directConn2 = directConnFact.createConnection();
+ directConn2.start();
+
+ pooledConn1 = pooledConnFact.createConnection();
+ pooledConn1.start();
+ pooledConn2 = pooledConnFact.createConnection();
+ pooledConn2.start();
+ }
+
+ @After
+ public void cleanupTest() throws java.lang.Exception {
+ try {
+ pooledConn1.stop();
+ } catch (JMSException jms_exc) {
+ }
+ try {
+ pooledConn2.stop();
+ } catch (JMSException jms_exc) {
+ }
+ try {
+ directConn1.stop();
+ } catch (JMSException jms_exc) {
+ }
+ try {
+ directConn2.stop();
+ } catch (JMSException jms_exc) {
+ }
+
+ try {
+ embeddedBroker.stop();
+ } catch (JMSException jms_exc) {
+ }
+ }
+
+ protected void configureBroker(BrokerService broker_svc) throws Exception {
+ broker_svc.setBrokerName("testbroker1");
+ broker_svc.setUseJmx(false);
+ broker_svc.setPersistent(false);
+ }
+
+ /**
+ * Test for lingering temporary destinations after closing a
+ * PooledConnection. Here are the steps:
+ *
+ * 1. create a session on the first pooled connection 2. create a session on
+ * the second pooled connection 3. create a temporary destination on the
+ * first session 4. confirm the temporary destination exists in the broker
+ * 5. close the first connection 6. check that the temporary destination no
+ * longer exists in the broker
+ */
+ @Test
+ public void testPooledLingeringTempDests() throws java.lang.Exception {
+ Session session1;
+ Session session2;
+
+ session1 = pooledConn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ session2 = pooledConn2.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+ tempDest = session1.createTemporaryQueue();
+
+ assertTrue("TEST METHOD FAILURE - NEW TEMP DESTINATION DOES NOT EXIST", destinationExists(tempDest));
+
+ pooledConn1.close();
+
+ assertTrue("FAILED: temp dest from closed pooled connection is lingering", !destinationExists(tempDest));
+
+ session2.close();
+ }
+
+ /**
+ * Test that closing one PooledConnection does not delete the temporary
+ * destinations of another.
+ *
+ * 1. create a session on the first pooled connection 2. create a session on
+ * the second pooled connection 3. create a temporary destination on the
+ * first session 4. create a temporary destination on the second session 5.
+ * confirm both temporary destinations exist in the broker 6. close the
+ * first connection 7. check that the first temporary destination no longer
+ * exists in the broker 8. check that the second temporary destination does
+ * still exist in the broker
+ */
+ @Test
+ public void testPooledTempDestsCleanupOverzealous() throws java.lang.Exception {
+ Session session1;
+ Session session2;
+
+ session1 = pooledConn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ session2 = pooledConn2.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+ tempDest = session1.createTemporaryQueue();
+ otherTempDest = session2.createTemporaryQueue();
+
+ assertTrue("TEST METHOD FAILURE - NEW TEMP DESTINATION DOES NOT EXIST", destinationExists(tempDest));
+ assertTrue("TEST METHOD FAILURE - NEW TEMP DESTINATION DOES NOT EXIST", destinationExists(otherTempDest));
+
+ pooledConn1.close();
+
+ // Now confirm the first temporary destination no longer exists and the
+ // second does.
+ assertTrue("FAILED: temp dest from closed pooled connection is lingering", !destinationExists(tempDest));
+ assertTrue("FAILED: second PooledConnectin's temporary destination was incorrectly deleted", destinationExists(otherTempDest));
+ }
+
+ /**
+ * CONTROL CASE
+ *
+ * Test for lingering temporary destinations after closing a Connection that
+ * is NOT pooled. This demonstrates the standard JMS operation and helps to
+ * validate the test methodology.
+ *
+ * 1. create a session on the first direct connection 2. create a session on
+ * the second direct connection 3. create a temporary destination on the
+ * first session 4. confirm the destination exists in the broker 5. close
+ * the first connection 6. check that the destination no longer exists in
+ * the broker
+ */
+ @Test
+ public void testDirectLingeringTempDests() throws java.lang.Exception {
+ Session session1;
+ Session session2;
+
+ session1 = directConn1.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ session2 = directConn2.createSession(false, Session.AUTO_ACKNOWLEDGE);
+
+ tempDest = session1.createTemporaryQueue();
+
+ assertTrue("TEST METHOD FAILURE - NEW TEMP DESTINATION DOES NOT EXIST", destinationExists(tempDest));
+
+ directConn1.close();
+
+ // Now confirm the temporary destination no longer exists.
+ assertTrue("CONTROL TEST FAILURE - TEST METHOD IS SUSPECT", (!destinationExists(tempDest)));
+
+ session2.close();
+ }
+
+ private boolean destinationExists(Destination dest) throws Exception {
+ RegionBroker rb = (RegionBroker) embeddedBroker.getBroker().getAdaptor(RegionBroker.class);
+ return rb.getTopicRegion().getDestinationMap().containsKey(dest) || rb.getQueueRegion().getDestinationMap().containsKey(dest)
+ || rb.getTempTopicRegion().getDestinationMap().containsKey(dest) || rb.getTempQueueRegion().getDestinationMap().containsKey(dest);
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionTest.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionTest.java b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionTest.java
new file mode 100644
index 0000000..3198f1a
--- /dev/null
+++ b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledConnectionTest.java
@@ -0,0 +1,114 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.IllegalStateException;
+
+import junit.framework.TestCase;
+
+import org.apache.activemq.ActiveMQConnectionFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A couple of tests against the PooledConnection class.
+ *
+ */
+public class PooledConnectionTest extends TestCase {
+
+ private final Logger log = LoggerFactory.getLogger(PooledConnectionTest.class);
+
+ @Override
+ public void setUp() throws Exception {
+ log.debug("setUp() called.");
+ }
+
+
+ @Override
+ public void tearDown() throws Exception {
+ log.debug("tearDown() called.");
+ }
+
+ /**
+ * AMQ-3752:
+ * Tests how the ActiveMQConnection reacts to repeated calls to
+ * setClientID().
+ *
+ * @throws Exception
+ */
+ public void testRepeatedSetClientIDCalls() throws Exception {
+ log.debug("running testRepeatedSetClientIDCalls()");
+
+ // 1st test: call setClientID("newID") twice
+ // this should be tolerated and not result in an exception
+ //
+ ConnectionFactory cf = createPooledConnectionFactory();
+ Connection conn = cf.createConnection();
+ conn.setClientID("newID");
+
+ try {
+ conn.setClientID("newID");
+ conn.start();
+ conn.close();
+ cf = null;
+ } catch (IllegalStateException ise) {
+ log.error("Repeated calls to ActiveMQConnection.setClientID(\"newID\") caused " + ise.getMessage());
+ fail("Repeated calls to ActiveMQConnection.setClientID(\"newID\") caused " + ise.getMessage());
+ }
+
+ // 2nd test: call setClientID() twice with different IDs
+ // this should result in an IllegalStateException
+ //
+ cf = createPooledConnectionFactory();
+ conn = cf.createConnection();
+ conn.setClientID("newID1");
+ try {
+ conn.setClientID("newID2");
+ fail("calling ActiveMQConnection.setClientID() twice with different clientID must raise an IllegalStateException");
+ } catch (IllegalStateException ise) {
+ log.debug("Correctly received " + ise);
+ } finally {
+ conn.close();
+ }
+
+ // 3rd test: try to call setClientID() after start()
+ // should result in an exception
+ cf = createPooledConnectionFactory();
+ conn = cf.createConnection();
+ try {
+ conn.start();
+ conn.setClientID("newID3");
+ fail("Calling setClientID() after start() mut raise a JMSException.");
+ } catch (IllegalStateException ise) {
+ log.debug("Correctly received " + ise);
+ } finally {
+ conn.close();
+ }
+
+ log.debug("Test finished.");
+ }
+
+ protected ConnectionFactory createPooledConnectionFactory() {
+ PooledConnectionFactory cf = new PooledConnectionFactory();
+ cf.setConnectionFactory(new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false"));
+ cf.setMaxConnections(1);
+ log.debug("ConnectionFactory initialized.");
+ return cf;
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledSessionExhaustionTest.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledSessionExhaustionTest.java b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledSessionExhaustionTest.java
new file mode 100644
index 0000000..7ad15ca
--- /dev/null
+++ b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledSessionExhaustionTest.java
@@ -0,0 +1,120 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.Destination;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+
+import junit.framework.TestCase;
+
+import org.apache.activemq.ActiveMQConnectionFactory;
+import org.apache.activemq.broker.BrokerService;
+import org.apache.activemq.broker.TransportConnector;
+import org.apache.log4j.Logger;
+
+public class PooledSessionExhaustionTest extends TestCase {
+ private static final String QUEUE = "FOO";
+ private static final int NUM_MESSAGES = 700;
+
+ private Logger logger = Logger.getLogger(getClass());
+
+ private BrokerService broker;
+ private ActiveMQConnectionFactory factory;
+ private PooledConnectionFactory pooledFactory;
+ private String connectionUri;
+ private int numReceived = 0;
+
+ @Override
+ protected void setUp() throws Exception {
+ broker = new BrokerService();
+ broker.setPersistent(false);
+ broker.setUseJmx(false);
+ TransportConnector connector = broker.addConnector("tcp://localhost:0");
+ broker.start();
+ connectionUri = connector.getPublishableConnectString();
+ factory = new ActiveMQConnectionFactory(connectionUri);
+ pooledFactory = new PooledConnectionFactory();
+ pooledFactory.setConnectionFactory(factory);
+ pooledFactory.setMaxConnections(1);
+ pooledFactory.setBlockIfSessionPoolIsFull(false);
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ broker.stop();
+ broker.waitUntilStopped();
+ broker = null;
+ }
+
+ public void sendMessages(ConnectionFactory connectionFactory) throws Exception {
+ for (int i = 0; i < NUM_MESSAGES; i++) {
+ Connection connection = connectionFactory.createConnection();
+ connection.start();
+
+ Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ Destination destination = session.createQueue(QUEUE);
+ MessageProducer producer = session.createProducer(destination);
+
+ String msgTo = "hello";
+ TextMessage message = session.createTextMessage(msgTo);
+ producer.send(message);
+ connection.close();
+ logger.debug("sent " + i + " messages using " + connectionFactory.getClass());
+ }
+ }
+
+ public void testCanExhaustSessions() throws Exception {
+ Thread thread = new Thread(new Runnable() {
+ public void run() {
+ try {
+ ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUri);
+ Connection connection = connectionFactory.createConnection();
+ connection.start();
+
+ Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ Destination destination = session.createQueue(QUEUE);
+ MessageConsumer consumer = session.createConsumer(destination);
+ for (int i = 0; i < NUM_MESSAGES; ++i) {
+ Message msg = consumer.receive(5000);
+ if (msg == null) {
+ return;
+ }
+ numReceived++;
+ if (numReceived % 20 == 0) {
+ logger.debug("received " + numReceived + " messages ");
+ System.runFinalization();
+ }
+ }
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+ });
+ thread.start();
+
+ sendMessages(pooledFactory);
+ thread.join();
+
+ assertEquals(NUM_MESSAGES, numReceived);
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledSessionTest.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledSessionTest.java b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledSessionTest.java
new file mode 100644
index 0000000..a60d053
--- /dev/null
+++ b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledSessionTest.java
@@ -0,0 +1,71 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import static org.junit.Assert.assertEquals;
+
+import javax.jms.Session;
+
+import org.apache.activemq.ActiveMQConnectionFactory;
+import org.apache.activemq.broker.BrokerService;
+import org.apache.activemq.broker.TransportConnector;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+public class PooledSessionTest {
+
+ private BrokerService broker;
+ private ActiveMQConnectionFactory factory;
+ private PooledConnectionFactory pooledFactory;
+ private String connectionUri;
+
+ @Before
+ public void setUp() throws Exception {
+ broker = new BrokerService();
+ broker.setPersistent(false);
+ broker.setUseJmx(false);
+ TransportConnector connector = broker.addConnector("tcp://localhost:0");
+ broker.start();
+ connectionUri = connector.getPublishableConnectString();
+ factory = new ActiveMQConnectionFactory(connectionUri);
+ pooledFactory = new PooledConnectionFactory();
+ pooledFactory.setConnectionFactory(factory);
+ pooledFactory.setMaxConnections(1);
+ pooledFactory.setBlockIfSessionPoolIsFull(false);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ broker.stop();
+ broker.waitUntilStopped();
+ broker = null;
+ }
+
+ @Test
+ public void testPooledSessionStats() throws Exception {
+ PooledConnection connection = (PooledConnection) pooledFactory.createConnection();
+
+ assertEquals(0, connection.getNumActiveSessions());
+ Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+ assertEquals(1, connection.getNumActiveSessions());
+ session.close();
+ assertEquals(0, connection.getNumActiveSessions());
+ assertEquals(1, connection.getNumtIdleSessions());
+ assertEquals(1, connection.getNumSessions());
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledTopicPublisherTest.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledTopicPublisherTest.java b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledTopicPublisherTest.java
new file mode 100644
index 0000000..1d1760d
--- /dev/null
+++ b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/PooledTopicPublisherTest.java
@@ -0,0 +1,106 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import javax.jms.Connection;
+import javax.jms.ExceptionListener;
+import javax.jms.JMSException;
+import javax.jms.Session;
+import javax.jms.TopicConnection;
+import javax.jms.TopicPublisher;
+import javax.jms.TopicSession;
+
+import org.apache.activemq.ActiveMQConnectionFactory;
+import org.apache.activemq.broker.BrokerService;
+import org.apache.activemq.broker.TransportConnector;
+import org.apache.activemq.command.ActiveMQTopic;
+import org.apache.activemq.test.TestSupport;
+import org.apache.activemq.util.SocketProxy;
+
+/**
+ *
+ */
+public class PooledTopicPublisherTest extends TestSupport {
+
+ private TopicConnection connection;
+
+ public void testPooledConnectionFactory() throws Exception {
+ ActiveMQTopic topic = new ActiveMQTopic("test");
+ PooledConnectionFactory pcf = new PooledConnectionFactory();
+ pcf.setConnectionFactory(new ActiveMQConnectionFactory("vm://test"));
+
+ connection = (TopicConnection) pcf.createConnection();
+ TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
+ TopicPublisher publisher = session.createPublisher(topic);
+ publisher.publish(session.createMessage());
+ }
+
+
+ public void testSetGetExceptionListener() throws Exception {
+ PooledConnectionFactory pcf = new PooledConnectionFactory();
+ pcf.setConnectionFactory(new ActiveMQConnectionFactory("vm://test"));
+
+ connection = (TopicConnection) pcf.createConnection();
+ ExceptionListener listener = new ExceptionListener() {
+ public void onException(JMSException exception) {
+ }
+ };
+ connection.setExceptionListener(listener);
+ assertEquals(listener, connection.getExceptionListener());
+ }
+
+ public void testPooledConnectionAfterInactivity() throws Exception {
+ BrokerService broker = new BrokerService();
+ TransportConnector networkConnector = broker.addConnector("tcp://localhost:0");
+ broker.setPersistent(false);
+ broker.setUseJmx(false);
+ broker.start();
+
+ SocketProxy proxy = new SocketProxy(networkConnector.getConnectUri());
+
+ PooledConnectionFactory pcf = new PooledConnectionFactory();
+ String uri = proxy.getUrl().toString() + "?trace=true&wireFormat.maxInactivityDuration=500&wireFormat.maxInactivityDurationInitalDelay=500";
+ pcf.setConnectionFactory(new ActiveMQConnectionFactory(uri));
+
+ PooledConnection conn = (PooledConnection) pcf.createConnection();
+ Connection amq = conn.getConnection();
+ assertNotNull(amq);
+ final CountDownLatch gotException = new CountDownLatch(1);
+ conn.setExceptionListener(new ExceptionListener() {
+ public void onException(JMSException exception) {
+ gotException.countDown();
+ }});
+ conn.setClientID(getName());
+
+ // let it hang, simulate a server hang so inactivity timeout kicks in
+ proxy.pause();
+ //assertTrue("got an exception", gotException.await(5, TimeUnit.SECONDS));
+ TimeUnit.SECONDS.sleep(2);
+ conn.close();
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ if (connection != null) {
+ connection.close();
+ connection = null;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/XAConnectionPoolTest.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/XAConnectionPoolTest.java b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/XAConnectionPoolTest.java
new file mode 100644
index 0000000..daf3af5
--- /dev/null
+++ b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/XAConnectionPoolTest.java
@@ -0,0 +1,348 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.activemq.jms.pool;
+
+import java.util.Hashtable;
+import java.util.Vector;
+
+import javax.jms.QueueConnection;
+import javax.jms.QueueConnectionFactory;
+import javax.jms.QueueSender;
+import javax.jms.QueueSession;
+import javax.jms.Session;
+import javax.jms.TopicConnection;
+import javax.jms.TopicConnectionFactory;
+import javax.jms.TopicPublisher;
+import javax.jms.TopicSession;
+import javax.naming.spi.ObjectFactory;
+import javax.transaction.HeuristicMixedException;
+import javax.transaction.HeuristicRollbackException;
+import javax.transaction.InvalidTransactionException;
+import javax.transaction.NotSupportedException;
+import javax.transaction.RollbackException;
+import javax.transaction.Status;
+import javax.transaction.Synchronization;
+import javax.transaction.SystemException;
+import javax.transaction.Transaction;
+import javax.transaction.TransactionManager;
+import javax.transaction.xa.XAResource;
+
+import org.apache.activemq.ActiveMQXAConnectionFactory;
+import org.apache.activemq.ActiveMQXASession;
+import org.apache.activemq.command.ActiveMQTopic;
+import org.apache.activemq.test.TestSupport;
+
+public class XAConnectionPoolTest extends TestSupport {
+
+ // https://issues.apache.org/jira/browse/AMQ-3251
+ public void testAfterCompletionCanClose() throws Exception {
+ final Vector<Synchronization> syncs = new Vector<Synchronization>();
+ ActiveMQTopic topic = new ActiveMQTopic("test");
+ XaPooledConnectionFactory pcf = new XaPooledConnectionFactory();
+ pcf.setConnectionFactory(new ActiveMQXAConnectionFactory("vm://test?broker.persistent=false"));
+
+ // simple TM that is in a tx and will track syncs
+ pcf.setTransactionManager(new TransactionManager(){
+ @Override
+ public void begin() throws NotSupportedException, SystemException {
+ }
+
+ @Override
+ public void commit() throws HeuristicMixedException, HeuristicRollbackException, IllegalStateException, RollbackException, SecurityException, SystemException {
+ }
+
+ @Override
+ public int getStatus() throws SystemException {
+ return Status.STATUS_ACTIVE;
+ }
+
+ @Override
+ public Transaction getTransaction() throws SystemException {
+ return new Transaction() {
+ @Override
+ public void commit() throws HeuristicMixedException, HeuristicRollbackException, RollbackException, SecurityException, SystemException {
+ }
+
+ @Override
+ public boolean delistResource(XAResource xaRes, int flag) throws IllegalStateException, SystemException {
+ return false;
+ }
+
+ @Override
+ public boolean enlistResource(XAResource xaRes) throws IllegalStateException, RollbackException, SystemException {
+ return false;
+ }
+
+ @Override
+ public int getStatus() throws SystemException {
+ return 0;
+ }
+
+ @Override
+ public void registerSynchronization(Synchronization synch) throws IllegalStateException, RollbackException, SystemException {
+ syncs.add(synch);
+ }
+
+ @Override
+ public void rollback() throws IllegalStateException, SystemException {
+ }
+
+ @Override
+ public void setRollbackOnly() throws IllegalStateException, SystemException {
+ }
+ };
+
+ }
+
+ @Override
+ public void resume(Transaction tobj) throws IllegalStateException, InvalidTransactionException, SystemException {
+ }
+
+ @Override
+ public void rollback() throws IllegalStateException, SecurityException, SystemException {
+ }
+
+ @Override
+ public void setRollbackOnly() throws IllegalStateException, SystemException {
+ }
+
+ @Override
+ public void setTransactionTimeout(int seconds) throws SystemException {
+ }
+
+ @Override
+ public Transaction suspend() throws SystemException {
+ return null;
+ }
+ });
+
+ TopicConnection connection = (TopicConnection) pcf.createConnection();
+ TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
+
+ assertTrue(session instanceof PooledSession);
+ PooledSession pooledSession = (PooledSession) session;
+ assertTrue(pooledSession.getInternalSession() instanceof ActiveMQXASession);
+
+ TopicPublisher publisher = session.createPublisher(topic);
+ publisher.publish(session.createMessage());
+
+ // simulate a commit
+ for (Synchronization sync : syncs) {
+ sync.beforeCompletion();
+ }
+ for (Synchronization sync : syncs) {
+ sync.afterCompletion(1);
+ }
+ connection.close();
+ }
+
+ public void testAckModeOfPoolNonXAWithTM() throws Exception {
+ final Vector<Synchronization> syncs = new Vector<Synchronization>();
+ ActiveMQTopic topic = new ActiveMQTopic("test");
+ XaPooledConnectionFactory pcf = new XaPooledConnectionFactory();
+ pcf.setConnectionFactory(new ActiveMQXAConnectionFactory("vm://test?broker.persistent=false&jms.xaAckMode=" + Session.CLIENT_ACKNOWLEDGE));
+
+ // simple TM that is in a tx and will track syncs
+ pcf.setTransactionManager(new TransactionManager(){
+ @Override
+ public void begin() throws NotSupportedException, SystemException {
+ }
+
+ @Override
+ public void commit() throws HeuristicMixedException, HeuristicRollbackException, IllegalStateException, RollbackException, SecurityException, SystemException {
+ }
+
+ @Override
+ public int getStatus() throws SystemException {
+ return Status.STATUS_ACTIVE;
+ }
+
+ @Override
+ public Transaction getTransaction() throws SystemException {
+ return new Transaction() {
+ @Override
+ public void commit() throws HeuristicMixedException, HeuristicRollbackException, RollbackException, SecurityException, SystemException {
+ }
+
+ @Override
+ public boolean delistResource(XAResource xaRes, int flag) throws IllegalStateException, SystemException {
+ return false;
+ }
+
+ @Override
+ public boolean enlistResource(XAResource xaRes) throws IllegalStateException, RollbackException, SystemException {
+ return false;
+ }
+
+ @Override
+ public int getStatus() throws SystemException {
+ return 0;
+ }
+
+ @Override
+ public void registerSynchronization(Synchronization synch) throws IllegalStateException, RollbackException, SystemException {
+ syncs.add(synch);
+ }
+
+ @Override
+ public void rollback() throws IllegalStateException, SystemException {
+ }
+
+ @Override
+ public void setRollbackOnly() throws IllegalStateException, SystemException {
+ }
+ };
+
+ }
+
+ @Override
+ public void resume(Transaction tobj) throws IllegalStateException, InvalidTransactionException, SystemException {
+ }
+
+ @Override
+ public void rollback() throws IllegalStateException, SecurityException, SystemException {
+ }
+
+ @Override
+ public void setRollbackOnly() throws IllegalStateException, SystemException {
+ }
+
+ @Override
+ public void setTransactionTimeout(int seconds) throws SystemException {
+ }
+
+ @Override
+ public Transaction suspend() throws SystemException {
+ return null;
+ }
+ });
+
+ TopicConnection connection = (TopicConnection) pcf.createConnection();
+ TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
+
+ assertEquals("client ack is enforce", Session.CLIENT_ACKNOWLEDGE, session.getAcknowledgeMode());
+ TopicPublisher publisher = session.createPublisher(topic);
+ publisher.publish(session.createMessage());
+
+ // simulate a commit
+ for (Synchronization sync : syncs) {
+ sync.beforeCompletion();
+ }
+ for (Synchronization sync : syncs) {
+ sync.afterCompletion(1);
+ }
+ connection.close();
+ }
+
+ public void testInstanceOf() throws Exception {
+ XaPooledConnectionFactory pcf = new XaPooledConnectionFactory();
+ assertTrue(pcf instanceof QueueConnectionFactory);
+ assertTrue(pcf instanceof TopicConnectionFactory);
+ }
+
+ public void testBindable() throws Exception {
+ XaPooledConnectionFactory pcf = new XaPooledConnectionFactory();
+ assertTrue(pcf instanceof ObjectFactory);
+ assertTrue(((ObjectFactory)pcf).getObjectInstance(null, null, null, null) instanceof XaPooledConnectionFactory);
+ assertTrue(pcf.isTmFromJndi());
+ }
+
+ public void testBindableEnvOverrides() throws Exception {
+ XaPooledConnectionFactory pcf = new XaPooledConnectionFactory();
+ assertTrue(pcf instanceof ObjectFactory);
+ Hashtable<String, String> environment = new Hashtable<String, String>();
+ environment.put("tmFromJndi", String.valueOf(Boolean.FALSE));
+ assertTrue(((ObjectFactory) pcf).getObjectInstance(null, null, null, environment) instanceof XaPooledConnectionFactory);
+ assertFalse(pcf.isTmFromJndi());
+ }
+
+ public void testSenderAndPublisherDest() throws Exception {
+ XaPooledConnectionFactory pcf = new XaPooledConnectionFactory();
+ pcf.setConnectionFactory(new ActiveMQXAConnectionFactory("vm://test?broker.persistent=false"));
+
+ QueueConnection connection = pcf.createQueueConnection();
+ QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
+ QueueSender sender = session.createSender(session.createQueue("AA"));
+ assertNotNull(sender.getQueue().getQueueName());
+
+ connection.close();
+
+ TopicConnection topicConnection = pcf.createTopicConnection();
+ TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
+ TopicPublisher topicPublisher = topicSession.createPublisher(topicSession.createTopic("AA"));
+ assertNotNull(topicPublisher.getTopic().getTopicName());
+
+ topicConnection.close();
+ }
+
+ public void testSessionArgsIgnoredWithTm() throws Exception {
+ XaPooledConnectionFactory pcf = new XaPooledConnectionFactory();
+ pcf.setConnectionFactory(new ActiveMQXAConnectionFactory("vm://test?broker.persistent=false"));
+ // simple TM that with no tx
+ pcf.setTransactionManager(new TransactionManager() {
+ @Override
+ public void begin() throws NotSupportedException, SystemException {
+ throw new SystemException("NoTx");
+ }
+
+ @Override
+ public void commit() throws HeuristicMixedException, HeuristicRollbackException, IllegalStateException, RollbackException, SecurityException, SystemException {
+ throw new IllegalStateException("NoTx");
+ }
+
+ @Override
+ public int getStatus() throws SystemException {
+ return Status.STATUS_NO_TRANSACTION;
+ }
+
+ @Override
+ public Transaction getTransaction() throws SystemException {
+ throw new SystemException("NoTx");
+ }
+
+ @Override
+ public void resume(Transaction tobj) throws IllegalStateException, InvalidTransactionException, SystemException {
+ throw new IllegalStateException("NoTx");
+ }
+
+ @Override
+ public void rollback() throws IllegalStateException, SecurityException, SystemException {
+ throw new IllegalStateException("NoTx");
+ }
+
+ @Override
+ public void setRollbackOnly() throws IllegalStateException, SystemException {
+ throw new IllegalStateException("NoTx");
+ }
+
+ @Override
+ public void setTransactionTimeout(int seconds) throws SystemException {
+ }
+
+ @Override
+ public Transaction suspend() throws SystemException {
+ throw new SystemException("NoTx");
+ }
+ });
+
+ QueueConnection connection = pcf.createQueueConnection();
+ // like ee tck
+ assertNotNull("can create session(false, 0)", connection.createQueueSession(false, 0));
+
+ connection.close();
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/bugs/AMQ4441Test.java
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/bugs/AMQ4441Test.java b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/bugs/AMQ4441Test.java
new file mode 100644
index 0000000..4adc224
--- /dev/null
+++ b/activemq-jms-pool/src/test/java/org/apache/activemq/jms/pool/bugs/AMQ4441Test.java
@@ -0,0 +1,86 @@
+package org.apache.activemq.jms.pool.bugs;
+
+import static org.junit.Assert.fail;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import javax.jms.JMSException;
+
+import org.apache.activemq.ActiveMQConnectionFactory;
+import org.apache.activemq.broker.BrokerService;
+import org.apache.activemq.jms.pool.PooledConnection;
+import org.apache.activemq.jms.pool.PooledConnectionFactory;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class AMQ4441Test {
+
+ private static final Logger LOG = LoggerFactory.getLogger(AMQ4441Test.class);
+ private BrokerService broker;
+
+ @Before
+ public void setUp() throws Exception {
+ broker = new BrokerService();
+ broker.setDeleteAllMessagesOnStartup(true);
+ broker.setPersistent(false);
+ broker.setUseJmx(false);
+ broker.start();
+ broker.waitUntilStarted();
+ }
+
+ @After
+ public void stopBroker() throws Exception {
+ broker.stop();
+ broker.waitUntilStopped();
+ }
+
+ @Test(timeout=120000)
+ public void demo() throws JMSException, InterruptedException {
+ final CountDownLatch latch = new CountDownLatch(1);
+ final AtomicBoolean done = new AtomicBoolean(false);
+ final PooledConnectionFactory pooled = new PooledConnectionFactory();
+ pooled.setConnectionFactory(new ActiveMQConnectionFactory("vm://localhost?create=false"));
+
+ pooled.setMaxConnections(2);
+ pooled.setExpiryTimeout(10L);
+ //pooled.start();
+ Thread[] threads = new Thread[10];
+ for (int i = 0; i < threads.length; i++) {
+ threads[i] = new Thread(new Runnable() {
+ @Override
+ public void run() {
+ while (!done.get() && latch.getCount() > 0) {
+ try {
+ final PooledConnection pooledConnection = (PooledConnection) pooled.createConnection();
+ if (pooledConnection.getConnection() == null) {
+ LOG.info("Found broken connection.");
+ latch.countDown();
+ }
+ pooledConnection.close();
+ } catch (JMSException e) {
+ LOG.warn("Caught Exception", e);
+ }
+ }
+ }
+ });
+ }
+ for (Thread thread : threads) {
+ thread.start();
+ }
+
+ if (latch.await(1, TimeUnit.MINUTES)) {
+ fail("A thread obtained broken connection");
+ }
+
+ done.set(true);
+ for (Thread thread : threads) {
+ thread.join();
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/test/resources/activemq-spring-jdbc.xml
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/test/resources/activemq-spring-jdbc.xml b/activemq-jms-pool/src/test/resources/activemq-spring-jdbc.xml
new file mode 100644
index 0000000..e406d69
--- /dev/null
+++ b/activemq-jms-pool/src/test/resources/activemq-spring-jdbc.xml
@@ -0,0 +1,69 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<!-- START SNIPPET: example -->
+<beans
+ xmlns="http://www.springframework.org/schema/beans"
+ xmlns:amq="http://activemq.apache.org/schema/core"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
+ http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd
+ http://activemq.apache.org/camel/schema/spring http://activemq.apache.org/camel/schema/spring/camel-spring.xsd">
+
+ <broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="target/" useJmx="false" deleteAllMessagesOnStartup="true">
+
+ <persistenceAdapter>
+ <jdbcPersistenceAdapter dataSource="#derby-ds" dataDirectory="target/"/>
+ </persistenceAdapter>
+
+ <destinationPolicy>
+ <policyMap>
+ <policyEntries>
+ <policyEntry queue=">" memoryLimit="10240"/>
+ <policyEntry topic=">" memoryLimit="10240">
+ </policyEntry>
+ </policyEntries>
+ </policyMap>
+ </destinationPolicy>
+
+
+ <systemUsage>
+ <systemUsage>
+ <memoryUsage>
+ <memoryUsage limit="102400"/>
+ </memoryUsage>
+ <storeUsage>
+ <storeUsage limit="1 gb" name="foo"/>
+ </storeUsage>
+ <tempUsage>
+ <tempUsage limit="100 mb"/>
+ </tempUsage>
+ </systemUsage>
+ </systemUsage>
+
+ <transportConnectors>
+ <transportConnector name="openwire" uri="tcp://localhost:61616" discoveryUri="multicast://default"/>
+ </transportConnectors>
+ </broker>
+
+
+ <bean id="derby-ds" class="org.apache.derby.jdbc.EmbeddedDataSource">
+ <property name="databaseName" value="derbydb"/>
+ <property name="createDatabase" value="create"/>
+ </bean>
+
+</beans>
+<!-- END SNIPPET: example -->
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-jms-pool/src/test/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/activemq-jms-pool/src/test/resources/log4j.properties b/activemq-jms-pool/src/test/resources/log4j.properties
new file mode 100755
index 0000000..b42af1a
--- /dev/null
+++ b/activemq-jms-pool/src/test/resources/log4j.properties
@@ -0,0 +1,38 @@
+## ---------------------------------------------------------------------------
+## Licensed to the Apache Software Foundation (ASF) under one or more
+## contributor license agreements. See the NOTICE file distributed with
+## this work for additional information regarding copyright ownership.
+## The ASF licenses this file to You under the Apache License, Version 2.0
+## (the "License"); you may not use this file except in compliance with
+## the License. You may obtain a copy of the License at
+##
+## http://www.apache.org/licenses/LICENSE-2.0
+##
+## Unless required by applicable law or agreed to in writing, software
+## distributed under the License is distributed on an "AS IS" BASIS,
+## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+## See the License for the specific language governing permissions and
+## limitations under the License.
+## ---------------------------------------------------------------------------
+
+#
+# The logging properties used during tests..
+#
+log4j.rootLogger=INFO, out, stdout
+
+log4j.logger.org.apache.activemq.spring=WARN
+#log4j.logger.org.apache.activemq.usecases=DEBUG
+#log4j.logger.org.apache.activemq.broker.region=DEBUG
+log4j.logger.org.apache.activemq.pool=DEBUG
+
+# CONSOLE appender not used by default
+log4j.appender.stdout=org.apache.log4j.ConsoleAppender
+log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
+log4j.appender.stdout.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n
+
+# File appender
+log4j.appender.out=org.apache.log4j.FileAppender
+log4j.appender.out.layout=org.apache.log4j.PatternLayout
+log4j.appender.out.layout.ConversionPattern=%d [%-15.15t] %-5p %-30.30c{1} - %m%n
+log4j.appender.out.file=target/activemq-test.log
+log4j.appender.out.append=true
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-karaf/src/main/resources/org/apache/activemq/karaf/commands/spring.xml
----------------------------------------------------------------------
diff --git a/activemq-karaf/src/main/resources/org/apache/activemq/karaf/commands/spring.xml b/activemq-karaf/src/main/resources/org/apache/activemq/karaf/commands/spring.xml
index 7289240..3b65ce8 100644
--- a/activemq-karaf/src/main/resources/org/apache/activemq/karaf/commands/spring.xml
+++ b/activemq-karaf/src/main/resources/org/apache/activemq/karaf/commands/spring.xml
@@ -121,7 +121,7 @@
<property name="connectionFactory" ref="activemqConnectionFactory" />
</bean>
- <bean id="resourceManager" class="org.apache.activemq.pool.ActiveMQResourceManager" init-method="recoverResource">
+ <bean id="resourceManager" class="org.apache.activemq.jms.pool.GenericResourceManager" init-method="recoverResource">
<property name="transactionManager" ref="transactionManager" />
<property name="connectionFactory" ref="activemqConnectionFactory" />
<property name="resourceName" value="activemq.${name}" />
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/pom.xml
----------------------------------------------------------------------
diff --git a/activemq-pool/pom.xml b/activemq-pool/pom.xml
index 3b9e6fc..f72204a 100755
--- a/activemq-pool/pom.xml
+++ b/activemq-pool/pom.xml
@@ -32,6 +32,7 @@
<properties>
<activemq.osgi.import.pkg>
javax.transaction*;resolution:=optional,
+ org.apache.activemq.jms.pool*;resolution:=optional,
org.apache.activemq.ra*;resolution:=optional,
org.apache.geronimo.transaction.manager*;resolution:=optional,
*
@@ -52,12 +53,11 @@
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
- <artifactId>activemq-client</artifactId>
+ <artifactId>activemq-jms-pool</artifactId>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
- <artifactId>activemq-ra</artifactId>
- <optional>true</optional>
+ <artifactId>activemq-client</artifactId>
</dependency>
<dependency>
<groupId>org.apache.geronimo.components</groupId>
@@ -80,6 +80,11 @@
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>activemq-broker</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>activemq-broker</artifactId>
<type>test-jar</type>
<scope>test</scope>
</dependency>
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/ActiveMQResourceManager.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/ActiveMQResourceManager.java b/activemq-pool/src/main/java/org/apache/activemq/pool/ActiveMQResourceManager.java
index 49e535b..e303c4b 100644
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/ActiveMQResourceManager.java
+++ b/activemq-pool/src/main/java/org/apache/activemq/pool/ActiveMQResourceManager.java
@@ -16,169 +16,10 @@
*/
package org.apache.activemq.pool;
-import java.io.IOException;
-
-import javax.jms.ConnectionFactory;
-import javax.jms.Session;
-import javax.jms.JMSException;
-import javax.transaction.SystemException;
-import javax.transaction.TransactionManager;
-
-import javax.transaction.xa.XAResource;
-import org.apache.geronimo.transaction.manager.NamedXAResourceFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.apache.activemq.ActiveMQConnectionFactory;
-import org.apache.activemq.ActiveMQConnection;
-import org.apache.activemq.ActiveMQSession;
-import org.apache.activemq.util.IOExceptionSupport;
-import org.apache.geronimo.transaction.manager.RecoverableTransactionManager;
-import org.apache.geronimo.transaction.manager.NamedXAResource;
-import org.apache.geronimo.transaction.manager.WrapperNamedXAResource;
-
+import org.apache.activemq.jms.pool.GenericResourceManager;
/**
- * This class allows wiring the ActiveMQ broker and the Geronimo transaction manager
- * in a way that will allow the transaction manager to correctly recover XA transactions.
- *
- * For example, it can be used the following way:
- * <pre>
- * <bean id="activemqConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
- * <property name="brokerURL" value="tcp://localhost:61616" />
- * </bean>
- *
- * <bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactoryFactoryBean">
- * <property name="maxConnections" value="8" />
- * <property name="transactionManager" ref="transactionManager" />
- * <property name="connectionFactory" ref="activemqConnectionFactory" />
- * <property name="resourceName" value="activemq.broker" />
- * </bean>
- *
- * <bean id="resourceManager" class="org.apache.activemq.pool.ActiveMQResourceManager" init-method="recoverResource">
- * <property name="transactionManager" ref="transactionManager" />
- * <property name="connectionFactory" ref="activemqConnectionFactory" />
- * <property name="resourceName" value="activemq.broker" />
- * </bean>
- * </pre>
+ * @Deprecated use {@link org.apache.activemq.jms.pool.GenericResourceManager}
*/
-public class ActiveMQResourceManager {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(ActiveMQResourceManager.class);
-
- private String resourceName;
-
- private TransactionManager transactionManager;
-
- private ConnectionFactory connectionFactory;
-
- public void recoverResource() {
- try {
- if (!Recovery.recover(this)) {
- LOGGER.info("Resource manager is unrecoverable");
- }
- } catch (NoClassDefFoundError e) {
- LOGGER.info("Resource manager is unrecoverable due to missing classes: " + e);
- } catch (Throwable e) {
- LOGGER.warn("Error while recovering resource manager", e);
- }
- }
-
- public String getResourceName() {
- return resourceName;
- }
-
- public void setResourceName(String resourceName) {
- this.resourceName = resourceName;
- }
-
- public TransactionManager getTransactionManager() {
- return transactionManager;
- }
-
- public void setTransactionManager(TransactionManager transactionManager) {
- this.transactionManager = transactionManager;
- }
-
- public ConnectionFactory getConnectionFactory() {
- return connectionFactory;
- }
-
- public void setConnectionFactory(ConnectionFactory connectionFactory) {
- this.connectionFactory = connectionFactory;
- }
-
- /**
- * This class will ensure the broker is properly recovered when wired with
- * the Geronimo transaction manager.
- */
- public static class Recovery {
-
- public static boolean isRecoverable(ActiveMQResourceManager rm) {
- return rm.getConnectionFactory() instanceof ActiveMQConnectionFactory &&
- rm.getTransactionManager() instanceof RecoverableTransactionManager &&
- rm.getResourceName() != null && !"".equals(rm.getResourceName());
- }
-
- public static boolean recover(final ActiveMQResourceManager rm) throws IOException {
- if (isRecoverable(rm)) {
- try {
- final ActiveMQConnectionFactory connFactory = (ActiveMQConnectionFactory) rm.getConnectionFactory();
- ActiveMQConnection activeConn = (ActiveMQConnection)connFactory.createConnection();
- final ActiveMQSession session = (ActiveMQSession)activeConn.createSession(true, Session.SESSION_TRANSACTED);
- NamedXAResource namedXaResource = new WrapperNamedXAResource(session.getTransactionContext(), rm.getResourceName());
-
- RecoverableTransactionManager rtxManager = (RecoverableTransactionManager) rm.getTransactionManager();
- rtxManager.registerNamedXAResourceFactory(new NamedXAResourceFactory() {
-
- @Override
- public String getName() {
- return rm.getResourceName();
- }
-
- @Override
- public NamedXAResource getNamedXAResource() throws SystemException {
- try {
- final ActiveMQConnection activeConn = (ActiveMQConnection)connFactory.createConnection();
- final ActiveMQSession session = (ActiveMQSession)activeConn.createSession(true, Session.SESSION_TRANSACTED);
- activeConn.start();
- LOGGER.debug("new namedXAResource's connection: " + activeConn);
-
- return new ConnectionAndWrapperNamedXAResource(session.getTransactionContext(), getName(), activeConn);
- } catch (Exception e) {
- SystemException se = new SystemException("Failed to create ConnectionAndWrapperNamedXAResource, " + e.getLocalizedMessage());
- se.initCause(e);
- LOGGER.error(se.getLocalizedMessage(), se);
- throw se;
- }
- }
-
- @Override
- public void returnNamedXAResource(NamedXAResource namedXaResource) {
- if (namedXaResource instanceof ConnectionAndWrapperNamedXAResource) {
- try {
- LOGGER.debug("closing returned namedXAResource's connection: " + ((ConnectionAndWrapperNamedXAResource)namedXaResource).connection);
- ((ConnectionAndWrapperNamedXAResource)namedXaResource).connection.close();
- } catch (Exception ignored) {
- LOGGER.debug("failed to close returned namedXAResource: " + namedXaResource, ignored);
- }
- }
- }
- });
- return true;
- } catch (JMSException e) {
- throw IOExceptionSupport.create(e);
- }
- } else {
- return false;
- }
- }
- }
-
- public static class ConnectionAndWrapperNamedXAResource extends WrapperNamedXAResource {
- final ActiveMQConnection connection;
- public ConnectionAndWrapperNamedXAResource(XAResource xaResource, String name, ActiveMQConnection connection) {
- super(xaResource, name);
- this.connection = connection;
- }
- }
+public class ActiveMQResourceManager extends GenericResourceManager {
}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/AmqJNDIPooledConnectionFactory.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/AmqJNDIPooledConnectionFactory.java b/activemq-pool/src/main/java/org/apache/activemq/pool/AmqJNDIPooledConnectionFactory.java
deleted file mode 100644
index 57d4c5d..0000000
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/AmqJNDIPooledConnectionFactory.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-import java.util.Properties;
-
-import javax.naming.NamingException;
-import javax.naming.Reference;
-
-import org.apache.activemq.ActiveMQConnectionFactory;
-import org.apache.activemq.jndi.JNDIReferenceFactory;
-import org.apache.activemq.jndi.JNDIStorableInterface;
-
-/**
-* AmqJNDIPooledConnectionFactory.java
-* Created by linus on 2008-03-07.
-*/
-public class AmqJNDIPooledConnectionFactory extends PooledConnectionFactory
- implements JNDIStorableInterface {
- private Properties properties;
-
- public AmqJNDIPooledConnectionFactory() {
- super();
- }
-
- public AmqJNDIPooledConnectionFactory(String brokerURL) {
- super(brokerURL);
- }
-
- public AmqJNDIPooledConnectionFactory(ActiveMQConnectionFactory connectionFactory) {
- super(connectionFactory);
- }
-
- /**
- * set the properties for this instance as retrieved from JNDI
- *
- * @param props
- */
- public synchronized void setProperties(Properties props) {
- this.properties = props;
- buildFromProperties(props);
- }
-
- /**
- * Get the properties from this instance for storing in JNDI
- *
- * @return the properties
- */
- public synchronized Properties getProperties() {
- if (this.properties == null) {
- this.properties = new Properties();
- }
- populateProperties(this.properties);
- return this.properties;
- }
-
- /**
- * Retrive a Reference for this instance to store in JNDI
- *
- * @return the built Reference
- * @throws NamingException
- * if error on building Reference
- */
- public Reference getReference() throws NamingException {
- return JNDIReferenceFactory.createReference(this.getClass().getName(),
- this);
- }
-
- public void buildFromProperties(Properties properties) {
- if (properties == null) {
- properties = new Properties();
- }
- ((ActiveMQConnectionFactory) getConnectionFactory())
- .buildFromProperties(properties);
- String temp = properties.getProperty("maximumActive");
- if (temp != null && temp.length() > 0) {
- setMaximumActiveSessionPerConnection(Integer.parseInt(temp));
- }
- temp = properties.getProperty("maximumActiveSessionPerConnection");
- if (temp != null && temp.length() > 0) {
- setMaximumActiveSessionPerConnection(Integer.parseInt(temp));
- }
- temp = properties.getProperty("maxConnections");
- if (temp != null && temp.length() > 0) {
- setMaxConnections(Integer.parseInt(temp));
- }
- }
-
- public void populateProperties(Properties props) {
- ((ActiveMQConnectionFactory) getConnectionFactory())
- .populateProperties(props);
- props.setProperty("maximumActive", Integer
- .toString(getMaximumActiveSessionPerConnection()));
- props.setProperty("maximumActiveSessionPerConnection", Integer
- .toString(getMaximumActiveSessionPerConnection()));
- props.setProperty("maxConnections", Integer
- .toString(getMaxConnections()));
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/ConnectionKey.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/ConnectionKey.java b/activemq-pool/src/main/java/org/apache/activemq/pool/ConnectionKey.java
deleted file mode 100644
index de99c2c..0000000
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/ConnectionKey.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-/**
- * A cache key for the connection details
- */
-public class ConnectionKey {
-
- private final String userName;
- private final String password;
- private int hash;
-
- public ConnectionKey(String userName, String password) {
- this.password = password;
- this.userName = userName;
- hash = 31;
- if (userName != null) {
- hash += userName.hashCode();
- }
- hash *= 31;
- if (password != null) {
- hash += password.hashCode();
- }
- }
-
- @Override
- public int hashCode() {
- return hash;
- }
-
- @Override
- public boolean equals(Object that) {
- if (this == that) {
- return true;
- }
- if (that instanceof ConnectionKey) {
- return equals((ConnectionKey) that);
- }
- return false;
- }
-
- public boolean equals(ConnectionKey that) {
- return isEqual(this.userName, that.userName) && isEqual(this.password, that.password);
- }
-
- public String getPassword() {
- return password;
- }
-
- public String getUserName() {
- return userName;
- }
-
- public static boolean isEqual(Object o1, Object o2) {
- if (o1 == o2) {
- return true;
- }
- return o1 != null && o2 != null && o1.equals(o2);
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/ConnectionPool.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/ConnectionPool.java b/activemq-pool/src/main/java/org/apache/activemq/pool/ConnectionPool.java
deleted file mode 100644
index fc83acb..0000000
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/ConnectionPool.java
+++ /dev/null
@@ -1,314 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.activemq.pool;
-
-import java.io.IOException;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import javax.jms.JMSException;
-import javax.jms.Session;
-
-import org.apache.activemq.ActiveMQConnection;
-import org.apache.activemq.ActiveMQSession;
-import org.apache.activemq.transport.TransportListener;
-import org.apache.activemq.util.JMSExceptionSupport;
-import org.apache.commons.pool.KeyedPoolableObjectFactory;
-import org.apache.commons.pool.impl.GenericKeyedObjectPool;
-import org.apache.commons.pool.impl.GenericObjectPool;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Holds a real JMS connection along with the session pools associated with it.
- * <p/>
- * Instances of this class are shared amongst one or more PooledConnection object and must
- * track the session objects that are loaned out for cleanup on close as well as ensuring
- * that the temporary destinations of the managed Connection are purged when all references
- * to this ConnectionPool are released.
- */
-public class ConnectionPool {
-
- private static final transient Logger LOG = LoggerFactory.getLogger(ConnectionPool.class);
-
- private ActiveMQConnection connection;
- private int referenceCount;
- private long lastUsed = System.currentTimeMillis();
- private final long firstUsed = lastUsed;
- private boolean hasFailed;
- private boolean hasExpired;
- private int idleTimeout = 30 * 1000;
- private long expiryTimeout = 0l;
-
- private final AtomicBoolean started = new AtomicBoolean(false);
- private final GenericKeyedObjectPool<SessionKey, PooledSession> sessionPool;
- private final List<PooledSession> loanedSessions = new CopyOnWriteArrayList<PooledSession>();
-
- public ConnectionPool(ActiveMQConnection connection) {
-
- this.connection = connection;
-
- // Add a transport Listener so that we can notice if this connection
- // should be expired due to a connection failure.
- connection.addTransportListener(new TransportListener() {
- @Override
- public void onCommand(Object command) {
- }
-
- @Override
- public void onException(IOException error) {
- synchronized (ConnectionPool.this) {
- hasFailed = true;
- }
- }
-
- @Override
- public void transportInterupted() {
- }
-
- @Override
- public void transportResumed() {
- }
- });
-
- // make sure that we set the hasFailed flag, in case the transport already failed
- // prior to the addition of our new TransportListener
- if(connection.isTransportFailed()) {
- hasFailed = true;
- }
-
- // Create our internal Pool of session instances.
- this.sessionPool = new GenericKeyedObjectPool<SessionKey, PooledSession>(
- new KeyedPoolableObjectFactory<SessionKey, PooledSession>() {
-
- @Override
- public void activateObject(SessionKey key, PooledSession session) throws Exception {
- ConnectionPool.this.loanedSessions.add(session);
- }
-
- @Override
- public void destroyObject(SessionKey key, PooledSession session) throws Exception {
- ConnectionPool.this.loanedSessions.remove(session);
- session.getInternalSession().close();
- }
-
- @Override
- public PooledSession makeObject(SessionKey key) throws Exception {
- ActiveMQSession session = (ActiveMQSession)
- ConnectionPool.this.connection.createSession(key.isTransacted(), key.getAckMode());
- return new PooledSession(key, session, sessionPool);
- }
-
- @Override
- public void passivateObject(SessionKey key, PooledSession session) throws Exception {
- ConnectionPool.this.loanedSessions.remove(session);
- }
-
- @Override
- public boolean validateObject(SessionKey key, PooledSession session) {
- return true;
- }
- }
- );
- }
-
- public void start() throws JMSException {
- if (started.compareAndSet(false, true)) {
- try {
- connection.start();
- } catch (JMSException e) {
- started.set(false);
- throw(e);
- }
- }
- }
-
- public synchronized ActiveMQConnection getConnection() {
- return connection;
- }
-
- public Session createSession(boolean transacted, int ackMode) throws JMSException {
- SessionKey key = new SessionKey(transacted, ackMode);
- PooledSession session;
- try {
- session = sessionPool.borrowObject(key);
- } catch (Exception e) {
- throw JMSExceptionSupport.create(e);
- }
- return session;
- }
-
- public synchronized void close() {
- if (connection != null) {
- try {
- sessionPool.close();
- } catch (Exception e) {
- } finally {
- try {
- connection.close();
- } catch (Exception e) {
- } finally {
- connection = null;
- }
- }
- }
- }
-
- public synchronized void incrementReferenceCount() {
- referenceCount++;
- lastUsed = System.currentTimeMillis();
- }
-
- public synchronized void decrementReferenceCount() {
- referenceCount--;
- lastUsed = System.currentTimeMillis();
- if (referenceCount == 0) {
- // Loaned sessions are those that are active in the sessionPool and
- // have not been closed by the client before closing the connection.
- // These need to be closed so that all session's reflect the fact
- // that the parent Connection is closed.
- for (PooledSession session : this.loanedSessions) {
- try {
- session.close();
- } catch (Exception e) {
- }
- }
- this.loanedSessions.clear();
-
- // We only clean up temporary destinations when all users of this
- // connection have called close.
- if (getConnection() != null) {
- getConnection().cleanUpTempDestinations();
- }
-
- expiredCheck();
- }
- }
-
- /**
- * Determines if this Connection has expired.
- * <p/>
- * A ConnectionPool is considered expired when all references to it are released AND either
- * the configured idleTimeout has elapsed OR the configured expiryTimeout has elapsed.
- * Once a ConnectionPool is determined to have expired its underlying Connection is closed.
- *
- * @return true if this connection has expired.
- */
- public synchronized boolean expiredCheck() {
-
- boolean expired = false;
-
- if (connection == null) {
- return true;
- }
-
- if (hasExpired || hasFailed) {
- if (referenceCount == 0) {
- close();
- expired = true;
- }
- }
-
- if (expiryTimeout > 0 && System.currentTimeMillis() > firstUsed + expiryTimeout) {
- hasExpired = true;
- if (referenceCount == 0) {
- close();
- expired = true;
- }
- }
-
- // Only set hasExpired here is no references, as a Connection with references is by
- // definition not idle at this time.
- if (referenceCount == 0 && idleTimeout > 0 && System.currentTimeMillis() > lastUsed + idleTimeout) {
- hasExpired = true;
- close();
- expired = true;
- }
-
- return expired;
- }
-
- public int getIdleTimeout() {
- return idleTimeout;
- }
-
- public void setIdleTimeout(int idleTimeout) {
- this.idleTimeout = idleTimeout;
- }
-
- public void setExpiryTimeout(long expiryTimeout) {
- this.expiryTimeout = expiryTimeout;
- }
-
- public long getExpiryTimeout() {
- return expiryTimeout;
- }
-
- public int getMaximumActiveSessionPerConnection() {
- return this.sessionPool.getMaxActive();
- }
-
- public void setMaximumActiveSessionPerConnection(int maximumActiveSessionPerConnection) {
- this.sessionPool.setMaxActive(maximumActiveSessionPerConnection);
- }
-
- /**
- * @return the total number of Pooled session including idle sessions that are not
- * currently loaned out to any client.
- */
- public int getNumSessions() {
- return this.sessionPool.getNumIdle() + this.sessionPool.getNumActive();
- }
-
- /**
- * @return the total number of Sessions that are in the Session pool but not loaned out.
- */
- public int getNumIdleSessions() {
- return this.sessionPool.getNumIdle();
- }
-
- /**
- * @return the total number of Session's that have been loaned to PooledConnection instances.
- */
- public int getNumActiveSessions() {
- return this.sessionPool.getNumActive();
- }
-
- /**
- * Configure whether the createSession method should block when there are no more idle sessions and the
- * pool already contains the maximum number of active sessions. If false the create method will fail
- * and throw an exception.
- *
- * @param block
- * Indicates whether blocking should be used to wait for more space to create a session.
- */
- public void setBlockIfSessionPoolIsFull(boolean block) {
- this.sessionPool.setWhenExhaustedAction(
- (block ? GenericObjectPool.WHEN_EXHAUSTED_BLOCK : GenericObjectPool.WHEN_EXHAUSTED_FAIL));
- }
-
- public boolean isBlockIfSessionPoolIsFull() {
- return this.sessionPool.getWhenExhaustedAction() == GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
- }
-
- @Override
- public String toString() {
- return "ConnectionPool[" + connection + "]";
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/JcaConnectionPool.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/JcaConnectionPool.java b/activemq-pool/src/main/java/org/apache/activemq/pool/JcaConnectionPool.java
deleted file mode 100644
index fa5369a..0000000
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/JcaConnectionPool.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright 2006 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.activemq.pool;
-
-import javax.jms.JMSException;
-import javax.transaction.TransactionManager;
-import javax.transaction.xa.XAResource;
-
-import org.apache.activemq.ActiveMQConnection;
-import org.apache.activemq.ra.LocalAndXATransaction;
-import org.apache.geronimo.transaction.manager.WrapperNamedXAResource;
-
-public class JcaConnectionPool extends XaConnectionPool {
-
- private final String name;
-
- public JcaConnectionPool(ActiveMQConnection connection, TransactionManager transactionManager, String name) {
- super(connection, transactionManager);
- this.name = name;
- }
-
- @Override
- protected XAResource createXaResource(PooledSession session) throws JMSException {
- XAResource xares = new LocalAndXATransaction(session.getInternalSession().getTransactionContext());
- if (name != null) {
- xares = new WrapperNamedXAResource(xares, name);
- }
- return xares;
- }
-}
http://git-wip-us.apache.org/repos/asf/activemq/blob/b66559ee/activemq-pool/src/main/java/org/apache/activemq/pool/JcaPooledConnectionFactory.java
----------------------------------------------------------------------
diff --git a/activemq-pool/src/main/java/org/apache/activemq/pool/JcaPooledConnectionFactory.java b/activemq-pool/src/main/java/org/apache/activemq/pool/JcaPooledConnectionFactory.java
index 1923545..55c2482 100644
--- a/activemq-pool/src/main/java/org/apache/activemq/pool/JcaPooledConnectionFactory.java
+++ b/activemq-pool/src/main/java/org/apache/activemq/pool/JcaPooledConnectionFactory.java
@@ -15,28 +15,20 @@
*/
package org.apache.activemq.pool;
+import java.io.IOException;
+import javax.jms.Connection;
import org.apache.activemq.ActiveMQConnection;
-import org.apache.activemq.ActiveMQConnectionFactory;
+import org.apache.activemq.jms.pool.ConnectionPool;
+import org.apache.activemq.jms.pool.JcaConnectionPool;
+import org.apache.activemq.transport.TransportListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-/**
- *
- */
public class JcaPooledConnectionFactory extends XaPooledConnectionFactory {
+ private static final transient Logger LOG = LoggerFactory.getLogger(JcaPooledConnectionFactory.class);
private String name;
- public JcaPooledConnectionFactory() {
- super();
- }
-
- public JcaPooledConnectionFactory(ActiveMQConnectionFactory connectionFactory) {
- super(connectionFactory);
- }
-
- public JcaPooledConnectionFactory(String brokerURL) {
- super(brokerURL);
- }
-
public String getName() {
return name;
}
@@ -45,7 +37,50 @@ public class JcaPooledConnectionFactory extends XaPooledConnectionFactory {
this.name = name;
}
- protected ConnectionPool createConnectionPool(ActiveMQConnection connection) {
- return new JcaConnectionPool(connection, getTransactionManager(), getName());
+ protected ConnectionPool createConnectionPool(Connection connection) {
+ return new JcaConnectionPool(connection, getTransactionManager(), getName()) {
+
+ @Override
+ protected Connection wrap(final Connection connection) {
+ // Add a transport Listener so that we can notice if this connection
+ // should be expired due to a connection failure.
+ ((ActiveMQConnection)connection).addTransportListener(new TransportListener() {
+ @Override
+ public void onCommand(Object command) {
+ }
+
+ @Override
+ public void onException(IOException error) {
+ synchronized (this) {
+ setHasExpired(true);
+ LOG.info("Expiring connection " + connection + " on IOException: " + error);
+ LOG.debug("Expiring connection on IOException", error);
+ }
+ }
+
+ @Override
+ public void transportInterupted() {
+ }
+
+ @Override
+ public void transportResumed() {
+ }
+ });
+
+ // make sure that we set the hasFailed flag, in case the transport already failed
+ // prior to the addition of our new TransportListener
+ setHasExpired(((ActiveMQConnection) connection).isTransportFailed());
+
+ // may want to return an amq EnhancedConnection
+ return connection;
+ }
+
+ @Override
+ protected void unWrap(Connection connection) {
+ if (connection != null) {
+ ((ActiveMQConnection)connection).cleanUpTempDestinations();
+ }
+ }
+ };
}
}