You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commons-dev@ws.apache.org by as...@apache.org on 2008/11/15 17:11:12 UTC
svn commit: r717873 [3/4] - in
/webservices/commons/trunk/scratch/asankha/transport/modules:
base/src/main/java/org/apache/axis2/transport/base/ jms/
jms/src/main/java/org/apache/axis2/transport/jms/ tests/
tests/src/test/java/org/apache/axis2/transpor...
Modified: webservices/commons/trunk/scratch/asankha/transport/modules/jms/src/main/java/org/apache/axis2/transport/jms/JMSUtils.java
URL: http://svn.apache.org/viewvc/webservices/commons/trunk/scratch/asankha/transport/modules/jms/src/main/java/org/apache/axis2/transport/jms/JMSUtils.java?rev=717873&r1=717872&r2=717873&view=diff
==============================================================================
--- webservices/commons/trunk/scratch/asankha/transport/modules/jms/src/main/java/org/apache/axis2/transport/jms/JMSUtils.java (original)
+++ webservices/commons/trunk/scratch/asankha/transport/modules/jms/src/main/java/org/apache/axis2/transport/jms/JMSUtils.java Sat Nov 15 08:11:11 2008
@@ -25,13 +25,14 @@
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.Parameter;
-import org.apache.axis2.description.ParameterIncludeImpl;
import org.apache.axis2.format.TextMessageBuilder;
import org.apache.axis2.format.TextMessageBuilderAdapter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.axis2.transport.TransportUtils;
import org.apache.axis2.transport.base.BaseUtils;
+import org.apache.axis2.transport.base.BaseConstants;
+import org.apache.axis2.transport.base.threads.WorkerPool;
import javax.jms.*;
import javax.jms.Queue;
@@ -55,58 +56,6 @@
private static final Object[] NOPARMS = new Object[] {};
/**
- * Create a JMS Queue using the given connection with the JNDI destination name, and return the
- * JMS Destination name of the created queue
- *
- * @param con the JMS Connection to be used
- * @param destinationJNDIName the JNDI name of the Queue to be created
- * @return the JMS Destination name of the created Queue
- * @throws JMSException on error
- */
- public static String createJMSQueue(Connection con, String destinationJNDIName)
- throws JMSException {
-
- try {
- QueueSession session
- = ((QueueConnection) con).createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
- Queue queue = session.createQueue(destinationJNDIName);
- log.info("JMS Queue with JNDI name : " + destinationJNDIName + " created");
- return queue.getQueueName();
-
- } finally {
- try {
- con.close();
- } catch (JMSException ignore) {}
- }
- }
-
- /**
- * Create a JMS Topic using the given connection with the JNDI destination name, and return the
- * JMS Destination name of the created queue
- *
- * @param con the JMS Connection to be used
- * @param destinationJNDIName the JNDI name of the Topic to be created
- * @return the JMS Destination name of the created Topic
- * @throws JMSException on error
- */
- public static String createJMSTopic(Connection con, String destinationJNDIName)
- throws JMSException {
-
- try {
- TopicSession session
- = ((TopicConnection) con).createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
- Topic topic = session.createTopic(destinationJNDIName);
- log.info("JMS Topic with JNDI name : " + destinationJNDIName + " created");
- return topic.getTopicName();
-
- } finally {
- try {
- con.close();
- } catch (JMSException ignore) {}
- }
- }
-
- /**
* Should this service be enabled over the JMS transport?
*
* @param service the Axis service
@@ -131,26 +80,40 @@
* Get the EPR for the given JMS connection factory and destination
* the form of the URL is
* jms:/<destination>?[<key>=<value>&]*
+ * Credentials Context.SECURITY_PRINCIPAL and Context.SECURITY_CREDENTIALS are filtered
*
- * @param cf the Axis2 JMS connection factory
- * @param destination the JNDI name of the destination
+ * @param cf the Axis2 JMS connection factory
+ * @param destinationType the type of destination
+ * @param endpoint JMSEndpoint
* @return the EPR as a String
*/
- // TODO: duplicate code (see JMSConnectionFactory#getEPRForDestination)
- static String getEPR(JMSConnectionFactory cf, JMSEndpoint endpoint) {
+ static String getEPR(JMSConnectionFactory cf, int destinationType, JMSEndpoint endpoint) {
StringBuffer sb = new StringBuffer();
- sb.append(JMSConstants.JMS_PREFIX).append(endpoint.getJndiDestinationName());
- sb.append("?").append(JMSConstants.DEST_PARAM_TYPE);
- sb.append("=").append(endpoint.getDestinationType());
- for (Map.Entry<String,String> entry : cf.getJndiProperties().entrySet()) {
- sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
- }
- String contentTypeProperty = endpoint.getContentTypeRuleSet().getDefaultContentTypeProperty();
- if (contentTypeProperty != null) {
- sb.append("&");
- sb.append(JMSConstants.CONTENT_TYPE_PROPERTY_PARAM);
- sb.append("=");
- sb.append(contentTypeProperty);
+
+ sb.append(
+ JMSConstants.JMS_PREFIX).append(endpoint.getJndiDestinationName());
+ sb.append("?").
+ append(JMSConstants.PARAM_DEST_TYPE).append("=").append(
+ destinationType == JMSConstants.TOPIC ?
+ JMSConstants.DESTINATION_TYPE_TOPIC : JMSConstants.DESTINATION_TYPE_QUEUE);
+
+ if (endpoint.getContentTypeRuleSet() != null) {
+ String contentTypeProperty =
+ endpoint.getContentTypeRuleSet().getDefaultContentTypeProperty();
+ if (contentTypeProperty != null) {
+ sb.append("&");
+ sb.append(JMSConstants.CONTENT_TYPE_PROPERTY_PARAM);
+ sb.append("=");
+ sb.append(contentTypeProperty);
+ }
+ }
+
+ for (Map.Entry<String,String> entry : cf.getParameters().entrySet()) {
+ if (!Context.SECURITY_PRINCIPAL.equalsIgnoreCase(entry.getKey()) &&
+ !Context.SECURITY_CREDENTIALS.equalsIgnoreCase(entry.getKey())) {
+ sb.append("&").append(
+ entry.getKey()).append("=").append(entry.getValue());
+ }
}
return sb.toString();
}
@@ -188,59 +151,16 @@
}
/**
- * Set JNDI properties and any other connection factory parameters to the connection factory
- * passed in, looking at the parameter in axis2.xml
- * @param param the axis parameter that holds the connection factory settings
- * @param jmsConFactory the JMS connection factory to which the parameters should be applied
+ * Set the SOAPEnvelope to the Axis2 MessageContext, from the JMS Message passed in
+ * @param message the JMS message read
+ * @param msgContext the Axis2 MessageContext to be populated
+ * @param contentType content type for the message
+ * @throws AxisFault
+ * @throws JMSException
*/
- public static void setConnectionFactoryParameters(
- Parameter param, JMSConnectionFactory jmsConFactory) {
-
- ParameterIncludeImpl pi = new ParameterIncludeImpl();
- try {
- pi.deserializeParameters((OMElement) param.getValue());
- } catch (AxisFault axisFault) {
- log.error("Error reading parameters for JMS connection factory" +
- jmsConFactory.getName(), axisFault);
- }
-
- for (Object o : pi.getParameters()) {
-
- Parameter p = (Parameter) o;
-
- if (JMSConstants.CONFAC_TYPE.equals(p.getName())) {
- String connectionFactoryType = (String) p.getValue();
- jmsConFactory.setConnectionFactoryType(connectionFactoryType);
-
- } else if (JMSConstants.RECONNECT_TIMEOUT.equals(p.getName())) {
- String strTimeout = (String) p.getValue();
- int reconnectTimeoutSeconds = Integer.parseInt(strTimeout);
- long reconnectTimeoutMillis = reconnectTimeoutSeconds * 1000;
- jmsConFactory.setReconnectTimeout(reconnectTimeoutMillis);
-
- } else if (Context.INITIAL_CONTEXT_FACTORY.equals(p.getName())) {
- jmsConFactory.addJNDIContextProperty(
- Context.INITIAL_CONTEXT_FACTORY, (String) p.getValue());
- } else if (Context.PROVIDER_URL.equals(p.getName())) {
- jmsConFactory.addJNDIContextProperty(
- Context.PROVIDER_URL, (String) p.getValue());
- } else if (Context.SECURITY_PRINCIPAL.equals(p.getName())) {
- jmsConFactory.addJNDIContextProperty(
- Context.SECURITY_PRINCIPAL, (String) p.getValue());
- } else if (Context.SECURITY_CREDENTIALS.equals(p.getName())) {
- jmsConFactory.addJNDIContextProperty(
- Context.SECURITY_CREDENTIALS, (String) p.getValue());
- } else if (JMSConstants.CONFAC_JNDI_NAME_PARAM.equals(p.getName())) {
- jmsConFactory.setConnFactoryJNDIName((String) p.getValue());
- jmsConFactory.addJNDIContextProperty(
- JMSConstants.CONFAC_JNDI_NAME_PARAM, (String) p.getValue());
- } else {
- jmsConFactory.addJNDIContextProperty( p.getName(), (String) p.getValue());
- }
- }
- }
+ public static void setSOAPEnvelope(Message message, MessageContext msgContext, String contentType)
+ throws AxisFault, JMSException {
- public static void setSOAPEnvelope(Message message, MessageContext msgContext, String contentType) throws AxisFault, JMSException {
if (message instanceof BytesMessage) {
if (contentType == null) {
log.debug("No content type specified; assuming application/octet-stream.");
@@ -268,6 +188,7 @@
return; // Make compiler happy
}
msgContext.setEnvelope(envelope);
+
} else if (message instanceof TextMessage) {
String type;
if (contentType == null) {
@@ -288,6 +209,7 @@
}
builder = new SOAPBuilder();
}
+
TextMessageBuilder textMessageBuilder;
if (builder instanceof TextMessageBuilder) {
textMessageBuilder = (TextMessageBuilder)builder;
@@ -312,6 +234,7 @@
*/
public static Destination setReplyDestination(Destination replyDestination, Session session,
Message message) {
+
if (replyDestination == null) {
try {
// create temporary queue to receive the reply
@@ -340,116 +263,6 @@
}
/**
- * When trying to send a message to a destination, if it does not exist, try to create it
- *
- * @param destination the JMS destination to send messages
- * @param destinationType type of the destination (can be a queue or a topic)
- * @param targetAddress the target JMS EPR to find the Destination to be created if required
- * @param session the JMS session to use
- * @return the JMS Destination where messages could be posted
- * @throws AxisFault if the target Destination does not exist and cannot be created
- */
- public static Destination createDestinationIfRequired(Destination destination,
- String destinationType, String targetAddress, Session session) throws AxisFault {
-
- if (destination == null) {
- if (targetAddress != null) {
- String name = JMSUtils.getDestination(targetAddress);
- if (log.isDebugEnabled()) {
- log.debug("Creating JMS Destination : " + name);
- }
-
- try {
- destination = createDestination(session, name, destinationType);
- } catch (JMSException e) {
- handleException("Error creating destination Queue : " + name, e);
- }
- } else {
- handleException("Cannot send reply to null JMS Destination");
- }
- }
- return destination;
- }
-
- /**
- * If reply destination does not exist, try to create it
- *
- * @param destination the destination queue or topic
- * @param replyDestinationName name of the reply destination queue or topic
- * @param destinationType type of the destination (can be queue or topic)
- * @param targetAddress target address of the queue or topic
- * @param session JMS session with the message to be sent
- * @return destination created if the destination is null or the destination otherwise
- * @throws org.apache.axis2.AxisFault in case of an error in creating the destination
- */
- public static Destination createReplyDestinationIfRequired(Destination destination,
- String replyDestinationName, String destinationType, String targetAddress, Session session)
- throws AxisFault {
-
- if (destination == null) {
- if (targetAddress != null) {
- if (log.isDebugEnabled()) {
- log.debug("Creating JMS Reply Destination : " + replyDestinationName);
- }
-
- try {
- destination = createDestination(session, replyDestinationName, destinationType);
- } catch (JMSException e) {
- handleException("Error creating reply destination : "
- + replyDestinationName, e);
- }
- } else {
- handleException("Cannot send reply to null reply JMS Destination");
- }
- }
- return destination;
- }
-
- /**
- * Send the given message to the Destination using the given session
- *
- * @param session the session to use to send
- * @param destination the Destination
- * @param destinationType type of the destination (can be a queue or a topic)
- * @param message the JMS Message
- * @throws AxisFault on error
- */
- public static void sendMessageToJMSDestination(Session session,
- Destination destination, String destinationType, Message message) throws AxisFault {
-
- MessageProducer producer = null;
- try {
- if (log.isDebugEnabled()) {
- log.debug("Sending message to destination : " + destination);
- }
-
- if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(destinationType)) {
- producer = ((TopicSession) session).createPublisher((Topic) destination);
- ((TopicPublisher) producer).publish(message);
- } else {
- producer = ((QueueSession) session).createSender((Queue) destination);
- producer.send(message);
- }
-
- if (log.isDebugEnabled()) {
- log.debug("Sent message to destination : " + destination +
- "\nMessage ID : " + message.getJMSMessageID() +
- "\nCorrelation ID : " + message.getJMSCorrelationID() +
- "\nReplyTo ID : " + message.getJMSReplyTo());
- }
-
- } catch (JMSException e) {
- handleException("Error creating a producer or sending to : " + destination, e);
- } finally {
- if (producer != null) {
- try {
- producer.close();
- } catch (JMSException ignore) {}
- }
- }
- }
-
- /**
* Set transport headers from the axis message context, into the JMS message
*
* @param msgContext the axis message context
@@ -485,19 +298,21 @@
} else {
log.warn("Invalid delivery mode ignored : " + o);
}
+
} else if (JMSConstants.JMS_EXPIRATION.equals(name)) {
message.setJMSExpiration(
- Long.parseLong((String) headerMap.get(JMSConstants.JMS_EXPIRATION)));
+ Long.parseLong((String) headerMap.get(JMSConstants.JMS_EXPIRATION)));
} else if (JMSConstants.JMS_MESSAGE_ID.equals(name)) {
message.setJMSMessageID((String) headerMap.get(JMSConstants.JMS_MESSAGE_ID));
} else if (JMSConstants.JMS_PRIORITY.equals(name)) {
message.setJMSPriority(
- Integer.parseInt((String) headerMap.get(JMSConstants.JMS_PRIORITY)));
+ Integer.parseInt((String) headerMap.get(JMSConstants.JMS_PRIORITY)));
} else if (JMSConstants.JMS_TIMESTAMP.equals(name)) {
message.setJMSTimestamp(
- Long.parseLong((String) headerMap.get(JMSConstants.JMS_TIMESTAMP)));
+ Long.parseLong((String) headerMap.get(JMSConstants.JMS_TIMESTAMP)));
} else if (JMSConstants.JMS_MESSAGE_TYPE.equals(name)) {
message.setJMSType((String) headerMap.get(JMSConstants.JMS_MESSAGE_TYPE));
+
} else {
Object value = headerMap.get(name);
if (value instanceof String) {
@@ -644,80 +459,14 @@
}
- // ----------- JMS 1.0.2b compatibility methods -------------
- public static Connection createConnection(ConnectionFactory conFactory, String user,
- String pass, String destinationType) throws JMSException {
-
- if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(destinationType) ) {
- if (user != null && pass != null) {
- return ((QueueConnectionFactory) conFactory).createQueueConnection(user, pass);
- } else {
- return ((QueueConnectionFactory) conFactory).createQueueConnection();
- }
-
- } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(destinationType) ) {
- if (user != null && pass != null) {
- return ((TopicConnectionFactory) conFactory).createTopicConnection(user, pass);
- } else {
- return ((TopicConnectionFactory) conFactory).createTopicConnection();
- }
- } else {
- handleException("Unable to determine type of JMS Connection Factory - i.e Queue/Topic");
- }
- return null;
- }
-
- public static Session createSession(Connection con,
- boolean transacted, int acknowledgeMode, String destinationType) throws JMSException {
-
- if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(destinationType) ) {
- return ((QueueConnection) con).createQueueSession(transacted, acknowledgeMode);
- } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(destinationType) ) {
- return ((TopicConnection) con).createTopicSession(transacted, acknowledgeMode);
- } else {
- log.debug("JMS destination type not given or invalid, was '" + destinationType +
- "'. Taking the default value as queue");
- return ((QueueConnection) con).createQueueSession(transacted, acknowledgeMode);
- }
- }
-
- public static Destination createDestination(Session session, String destName,
- String destinationType) throws JMSException {
-
- if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(destinationType)) {
- return session.createQueue(destName);
- } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(destinationType) ) {
- return session.createTopic(destName);
- } else {
- log.debug("JMS destination type not given or invalid, was '" + destinationType +
- "'. Taking the default value as queue");
- return session.createQueue(destName);
- }
- }
-
- public static void createDestination(ConnectionFactory conFactory,
- String destinationJNDIName, String destinationType) throws JMSException {
-
- if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(destinationType)) {
- JMSUtils.createJMSQueue(
- ((QueueConnectionFactory) conFactory).createQueueConnection(),
- destinationJNDIName);
- } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(destinationType) ) {
- JMSUtils.createJMSTopic(
- ((TopicConnectionFactory) conFactory).createTopicConnection(),
- destinationJNDIName);
- }
- }
- public static MessageConsumer createConsumer(Session session, Destination dest)
- throws JMSException {
-
- if (dest instanceof Queue) {
- return ((QueueSession) session).createReceiver((Queue) dest);
- } else {
- return ((TopicSession) session).createSubscriber((Topic) dest);
- }
- }
-
+ /**
+ * Create a MessageConsumer for the given Destination
+ * @param session JMS Session to use
+ * @param dest Destination for which the Consumer is to be created
+ * @param messageSelector the message selector to be used if any
+ * @return a MessageConsumer for the specified Destination
+ * @throws JMSException
+ */
public static MessageConsumer createConsumer(Session session, Destination dest, String messageSelector)
throws JMSException {
@@ -728,6 +477,13 @@
}
}
+ /**
+ * Create a temp queue or topic for synchronous receipt of responses, when a reply destination
+ * is not specified
+ * @param session the JMS Session to use
+ * @return a temporary Queue or Topic, depending on the session
+ * @throws JMSException
+ */
public static Destination createTemporaryDestination(Session session) throws JMSException {
if (session instanceof QueueSession) {
@@ -737,6 +493,11 @@
}
}
+ /**
+ * Return the body length in bytes for a bytes message
+ * @param bMsg the JMS BytesMessage
+ * @return length of body in bytes
+ */
public static long getBodyLength(BytesMessage bMsg) {
try {
Method mtd = bMsg.getClass().getMethod("getBodyLength", NOARGS);
@@ -762,7 +523,13 @@
} catch (JMSException ignore) {}
return length;
}
-
+
+ /**
+ * Get the length of the message in bytes
+ * @param message
+ * @return message size (or approximation) in bytes
+ * @throws JMSException
+ */
public static long getMessageSize(Message message) throws JMSException {
if (message instanceof BytesMessage) {
return JMSUtils.getBodyLength((BytesMessage) message);
@@ -799,4 +566,497 @@
}
}
}
+
+ /**
+ * Create a ServiceTaskManager for the service passed in and its corresponding JMSConnectionFactory
+ * @param jcf
+ * @param service
+ * @param workerPool
+ * @return
+ */
+ public static ServiceTaskManager createTaskManagerForService(JMSConnectionFactory jcf,
+ AxisService service, WorkerPool workerPool) {
+
+ String name = service.getName();
+ Map<String, String> svc = getServiceStringParameters(service.getParameters());
+ Map<String, String> cf = jcf.getParameters();
+
+ ServiceTaskManager stm = new ServiceTaskManager();
+
+ stm.setServiceName(name);
+ stm.setJndiProperties(jcf.getParameters());
+
+ stm.setConnFactoryJNDIName(
+ getRqdStringProperty(JMSConstants.PARAM_CONFAC_JNDI_NAME, svc, cf));
+ stm.setDestinationJNDIName(
+ getRqdStringProperty(JMSConstants.PARAM_DESTINATION, svc, cf));
+ stm.setDestinationType(getDestinationType(svc, cf));
+
+ stm.setJmsSpec11(
+ getJMSSpecVersion(svc, cf));
+ stm.setTransactionality(
+ getTransactionality(svc, cf));
+ stm.setCacheUserTransaction(
+ getOptionalBooleanProperty(BaseConstants.PARAM_CACHE_USER_TXN, svc, cf));
+ stm.setUserTransactionJNDIName(
+ getOptionalStringProperty(BaseConstants.PARAM_USER_TXN_JNDI_NAME, svc, cf));
+ stm.setSessionTransacted(
+ getOptionalBooleanProperty(JMSConstants.PARAM_SESSION_TRANSACTED, svc, cf));
+ stm.setSessionAckMode(
+ getSessionAck(svc, cf));
+ stm.setMessageSelector(
+ getOptionalStringProperty(JMSConstants.PARAM_MSG_SELECTOR, svc, cf));
+ stm.setSubscriptionDurable(
+ getOptionalBooleanProperty(JMSConstants.PARAM_SUB_DURABLE, svc, cf));
+ stm.setDurableSubscriberName(
+ getOptionalStringProperty(JMSConstants.PARAM_DURABLE_SUB_NAME, svc, cf));
+
+ stm.setCacheLevel(
+ getCacheLevel(svc, cf));
+ stm.setPubSubNoLocal(
+ getOptionalBooleanProperty(JMSConstants.PARAM_PUBSUB_NO_LOCAL, svc, cf));
+
+ Integer value = getOptionalIntProperty(JMSConstants.PARAM_RCV_TIMEOUT, svc, cf);
+ if (value != null) {
+ stm.setReceiveTimeout(value);
+ }
+ value = getOptionalIntProperty(JMSConstants.PARAM_CONCURRENT_CONSUMERS, svc, cf);
+ if (value != null) {
+ stm.setConcurrentConsumers(value);
+ }
+ value = getOptionalIntProperty(JMSConstants.PARAM_CONCURRENT_CONSUMERS, svc, cf);
+ if (value != null) {
+ stm.setMaxConcurrentConsumers(value);
+ }
+ value = getOptionalIntProperty(JMSConstants.PARAM_IDLE_TASK_LIMIT, svc, cf);
+ if (value != null) {
+ stm.setIdleTaskExecutionLimit(value);
+ }
+ value = getOptionalIntProperty(JMSConstants.PARAM_MAX_MSGS_PER_TASK, svc, cf);
+ if (value != null) {
+ stm.setMaxMessagesPerTask(value);
+ }
+
+ value = getOptionalIntProperty(JMSConstants.PARAM_RECON_INIT_DURATION, svc, cf);
+ if (value != null) {
+ stm.setInitialReconnectDuration(value);
+ }
+ value = getOptionalIntProperty(JMSConstants.PARAM_RECON_MAX_DURATION, svc, cf);
+ if (value != null) {
+ stm.setMaxReconnectDuration(value);
+ }
+ Double dValue = getOptionalDoubleProperty(JMSConstants.PARAM_RECON_FACTOR, svc, cf);
+ if (dValue != null) {
+ stm.setReconnectionProgressionFactor(dValue);
+ }
+
+ stm.setWorkerPool(workerPool);
+ return stm;
+ }
+
+ private static Map<String, String> getServiceStringParameters(List list) {
+
+ Map<String, String> map = new HashMap<String, String>();
+ for (Object o : list) {
+ Parameter p = (Parameter) o;
+ if (p.getValue() instanceof String) {
+ map.put(p.getName(), (String) p.getValue());
+ }
+ }
+ return map;
+ }
+
+ private static String getRqdStringProperty(String key, Map svcMap, Map cfMap) {
+ String value = (String) svcMap.get(key);
+ if (value == null) {
+ value = (String) cfMap.get(key);
+ }
+ if (value == null) {
+ throw new AxisJMSException("Service/connection factory property : " + key);
+ }
+ return value;
+ }
+
+ private static String getOptionalStringProperty(String key, Map svcMap, Map cfMap) {
+ String value = (String) svcMap.get(key);
+ if (value == null) {
+ value = (String) cfMap.get(key);
+ }
+ return value;
+ }
+
+ private static Boolean getOptionalBooleanProperty(String key, Map svcMap, Map cfMap) {
+ String value = (String) svcMap.get(key);
+ if (value == null) {
+ value = (String) cfMap.get(key);
+ }
+ if (value == null) {
+ return null;
+ } else {
+ return Boolean.valueOf(value);
+ }
+ }
+
+ private static Integer getOptionalIntProperty(String key, Map svcMap, Map cfMap) {
+ String value = (String) svcMap.get(key);
+ if (value == null) {
+ value = (String) cfMap.get(key);
+ }
+ if (value != null) {
+ try {
+ return Integer.parseInt(value);
+ } catch (NumberFormatException e) {
+ throw new AxisJMSException("Invalid value : " + value + " for " + key);
+ }
+ }
+ return null;
+ }
+
+ private static Double getOptionalDoubleProperty(String key, Map svcMap, Map cfMap) {
+ String value = (String) svcMap.get(key);
+ if (value == null) {
+ value = (String) cfMap.get(key);
+ }
+ if (value != null) {
+ try {
+ return Double.parseDouble(value);
+ } catch (NumberFormatException e) {
+ throw new AxisJMSException("Invalid value : " + value + " for " + key);
+ }
+ }
+ return null;
+ }
+
+ private static int getTransactionality(Map svcMap, Map cfMap) {
+
+ String key = BaseConstants.PARAM_TRANSACTIONALITY;
+ String val = (String) svcMap.get(key);
+ if (val == null) {
+ val = (String) cfMap.get(key);
+ }
+
+ if (val == null) {
+ return BaseConstants.TRANSACTION_NONE;
+
+ } else {
+ if (BaseConstants.STR_TRANSACTION_JTA.equalsIgnoreCase(val)) {
+ return BaseConstants.TRANSACTION_JTA;
+ } else if (BaseConstants.STR_TRANSACTION_LOCAL.equalsIgnoreCase(val)) {
+ return BaseConstants.TRANSACTION_LOCAL;
+ } else {
+ throw new AxisJMSException("Invalid option : " + val + " for parameter : " +
+ BaseConstants.STR_TRANSACTION_JTA);
+ }
+ }
+ }
+
+ private static int getDestinationType(Map svcMap, Map cfMap) {
+
+ String key = JMSConstants.PARAM_DEST_TYPE;
+ String val = (String) svcMap.get(key);
+ if (val == null) {
+ val = (String) cfMap.get(key);
+ }
+
+ if (JMSConstants.DESTINATION_TYPE_TOPIC.equalsIgnoreCase(val)) {
+ return JMSConstants.TOPIC;
+ }
+ return JMSConstants.QUEUE;
+ }
+
+ private static int getSessionAck(Map svcMap, Map cfMap) {
+
+ String key = JMSConstants.PARAM_SESSION_ACK;
+ String val = (String) svcMap.get(key);
+ if (val == null) {
+ val = (String) cfMap.get(key);
+ }
+
+ if (val == null || "AUTO_ACKNOWLEDGE".equalsIgnoreCase(val)) {
+ return Session.AUTO_ACKNOWLEDGE;
+ } else if ("CLIENT_ACKNOWLEDGE".equalsIgnoreCase(val)) {
+ return Session.CLIENT_ACKNOWLEDGE;
+ } else if ("DUPS_OK_ACKNOWLEDGE".equals(val)){
+ return Session.DUPS_OK_ACKNOWLEDGE;
+ } else if ("SESSION_TRANSACTED".equals(val)) {
+ return 0; //Session.SESSION_TRANSACTED;
+ } else {
+ try {
+ return Integer.parseInt(val);
+ } catch (NumberFormatException ignore) {
+ throw new AxisJMSException("Invalid session acknowledgement mode : " + val);
+ }
+ }
+ }
+
+ private static int getCacheLevel(Map svcMap, Map cfMap) {
+
+ String key = JMSConstants.PARAM_CACHE_LEVEL;
+ String val = (String) svcMap.get(key);
+ if (val == null) {
+ val = (String) cfMap.get(key);
+ }
+
+ if ("none".equalsIgnoreCase(val)) {
+ return JMSConstants.CACHE_NONE;
+ } else if ("connection".equalsIgnoreCase(val)) {
+ return JMSConstants.CACHE_CONNECTION;
+ } else if ("session".equals(val)){
+ return JMSConstants.CACHE_SESSION;
+ } else if ("consumer".equals(val)) {
+ return JMSConstants.CACHE_CONSUMER;
+ } else if (val != null) {
+ throw new AxisJMSException("Invalid cache level : " + val);
+ }
+ return JMSConstants.CACHE_AUTO;
+ }
+
+ private static boolean getJMSSpecVersion(Map svcMap, Map cfMap) {
+
+ String key = JMSConstants.PARAM_JMS_SPEC_VER;
+ String val = (String) svcMap.get(key);
+ if (val == null) {
+ val = (String) cfMap.get(key);
+ }
+
+ if (val == null || "1.1".equals(val)) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * This is a JMS spec independent method to create a Connection. Please be cautious when
+ * making any changes
+ *
+ * @param conFac the ConnectionFactory to use
+ * @param user optional user name
+ * @param pass optional password
+ * @param jmsSpec11 should we use JMS 1.1 API ?
+ * @param isQueue is this to deal with a Queue?
+ * @return a JMS Connection as requested
+ * @throws JMSException on errors, to be handled and logged by the caller
+ */
+ public static Connection createConnection(ConnectionFactory conFac,
+ String user, String pass, boolean jmsSpec11, Boolean isQueue) throws JMSException {
+
+ Connection connection = null;
+ if (log.isDebugEnabled()) {
+ log.debug("Creating a " + (isQueue == null ? "Generic" : isQueue ? "Queue" : "Topic") +
+ "Connection using credentials : (" + user + "/" + pass + ")");
+ }
+
+ if (jmsSpec11 || isQueue == null) {
+ if (user != null && pass != null) {
+ connection = conFac.createConnection(user, pass);
+ } else {
+ connection = conFac.createConnection();
+ }
+
+ } else {
+ QueueConnectionFactory qConFac = null;
+ TopicConnectionFactory tConFac = null;
+ if (isQueue) {
+ tConFac = (TopicConnectionFactory) conFac;
+ } else {
+ qConFac = (QueueConnectionFactory) conFac;
+ }
+
+ if (user != null && pass != null) {
+ if (qConFac != null) {
+ connection = qConFac.createQueueConnection(user, pass);
+ } else if (tConFac != null) {
+ connection = tConFac.createTopicConnection(user, pass);
+ }
+ } else {
+ if (qConFac != null) {
+ connection = qConFac.createQueueConnection();
+ } else if (tConFac != null) {
+ connection = tConFac.createTopicConnection();
+ }
+ }
+ }
+ return connection;
+ }
+
+ /**
+ * This is a JMS spec independent method to create a Session. Please be cautious when
+ * making any changes
+ *
+ * @param connection the JMS Connection
+ * @param transacted should the session be transacted?
+ * @param ackMode the ACK mode for the session
+ * @param jmsSpec11 should we use the JMS 1.1 API?
+ * @param isQueue is this Session to deal with a Queue?
+ * @return a Session created for the given information
+ * @throws JMSException on errors, to be handled and logged by the caller
+ */
+ public static Session createSession(Connection connection, boolean transacted, int ackMode,
+ boolean jmsSpec11, Boolean isQueue) throws JMSException {
+
+ if (jmsSpec11 || isQueue == null) {
+ return connection.createSession(transacted, ackMode);
+
+ } else {
+ if (isQueue) {
+ return ((QueueConnection) connection).createQueueSession(transacted, ackMode);
+ } else {
+ return ((TopicConnection) connection).createTopicSession(transacted, ackMode);
+ }
+ }
+ }
+
+ /**
+ * This is a JMS spec independent method to create a MessageConsumer. Please be cautious when
+ * making any changes
+ *
+ * @param session JMS session
+ * @param destination the Destination
+ * @param isQueue is the Destination a queue?
+ * @param subscriberName optional client name to use for a durable subscription to a topic
+ * @param messageSelector optional message selector
+ * @param pubSubNoLocal should we receive messages sent by us during pub-sub?
+ * @param isDurable is this a durable topic subscription?
+ * @param jmsSpec11 should we use JMS 1.1 API ?
+ * @return a MessageConsumer to receive messages
+ * @throws JMSException on errors, to be handled and logged by the caller
+ */
+ public static MessageConsumer createConsumer(
+ Session session, Destination destination, Boolean isQueue,
+ String subscriberName, String messageSelector, boolean pubSubNoLocal,
+ boolean isDurable, boolean jmsSpec11) throws JMSException {
+
+ if (jmsSpec11 || isQueue == null) {
+ if (isDurable) {
+ return session.createDurableSubscriber(
+ (Topic) destination, subscriberName, messageSelector, pubSubNoLocal);
+ } else {
+ return session.createConsumer(destination, messageSelector, pubSubNoLocal);
+ }
+ } else {
+ if (isQueue) {
+ return ((QueueSession) session).createReceiver((Queue) destination, messageSelector);
+ } else {
+ if (isDurable) {
+ return ((TopicSession) session).createDurableSubscriber(
+ (Topic) destination, subscriberName, messageSelector, pubSubNoLocal);
+ } else {
+ return ((TopicSession) session).createSubscriber(
+ (Topic) destination, messageSelector, pubSubNoLocal);
+ }
+ }
+ }
+ }
+
+ /**
+ * This is a JMS spec independent method to create a MessageProducer. Please be cautious when
+ * making any changes
+ *
+ * @param session JMS session
+ * @param destination the Destination
+ * @param isQueue is the Destination a queue?
+ * @param jmsSpec11 should we use JMS 1.1 API ?
+ * @return a MessageProducer to send messages to the given Destination
+ * @throws JMSException on errors, to be handled and logged by the caller
+ */
+ public static MessageProducer createProducer(
+ Session session, Destination destination, Boolean isQueue, boolean jmsSpec11) throws JMSException {
+
+ if (jmsSpec11 || isQueue == null) {
+ return session.createProducer(destination);
+ } else {
+ if (isQueue) {
+ return ((QueueSession) session).createSender((Queue) destination);
+ } else {
+ return ((TopicSession) session).createPublisher((Topic) destination);
+ }
+ }
+ }
+
+ /**
+ * Create a one time MessageProducer for the given JMS OutTransport information
+ * For simplicity and best compatibility, this method uses only JMS 1.0.2b API.
+ * Please be cautious when making any changes
+ *
+ * @param jmsOut the JMS OutTransport information (contains all properties)
+ * @return a JMSSender based on one-time use resources
+ * @throws JMSException on errors, to be handled and logged by the caller
+ */
+ public static JMSMessageSender createJMSSender(JMSOutTransportInfo jmsOut)
+ throws JMSException {
+
+ // digest the targetAddress and locate CF from the EPR
+ jmsOut.loadConnectionFactoryFromProperies();
+
+ // create a one time connection and session to be used
+ Hashtable<String,String> jndiProps = jmsOut.getProperties();
+ String user = jndiProps != null ? jndiProps.get(Context.SECURITY_PRINCIPAL) : null;
+ String pass = jndiProps != null ? jndiProps.get(Context.SECURITY_CREDENTIALS) : null;
+
+ QueueConnectionFactory qConFac = null;
+ TopicConnectionFactory tConFac = null;
+
+ int destType = -1;
+ if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(jmsOut.getDestinationType())) {
+ destType = JMSConstants.QUEUE;
+ qConFac = (QueueConnectionFactory) jmsOut.getConnectionFactory();
+
+ } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(jmsOut.getDestinationType())) {
+ destType = JMSConstants.TOPIC;
+ tConFac = (TopicConnectionFactory) jmsOut.getConnectionFactory();
+ }
+
+ Connection connection = null;
+ if (user != null && pass != null) {
+ if (qConFac != null) {
+ connection = qConFac.createQueueConnection(user, pass);
+ } else if (tConFac != null) {
+ connection = tConFac.createTopicConnection(user, pass);
+ }
+ } else {
+ if (qConFac != null) {
+ connection = qConFac.createQueueConnection();
+ } else if (tConFac != null) {
+ connection = tConFac.createTopicConnection();
+ }
+ }
+
+ if (connection == null && jmsOut.getJmsConnectionFactory() != null) {
+ connection = jmsOut.getJmsConnectionFactory().getConnection();
+ }
+
+ Session session = null;
+ MessageProducer producer = null;
+ Destination destination = jmsOut.getDestination();
+
+ if (destType == JMSConstants.QUEUE) {
+ session = ((QueueConnection) connection).
+ createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
+ producer = ((QueueSession) session).createSender((Queue) destination);
+ } else {
+ session = ((TopicConnection) connection).
+ createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
+ producer = ((TopicSession) session).createPublisher((Topic) destination);
+ }
+
+ return new JMSMessageSender(connection, session, producer,
+ destination, JMSConstants.CACHE_NONE, false,
+ destType == -1 ? null : destType == JMSConstants.QUEUE ? Boolean.TRUE : Boolean.FALSE);
+ }
+
+ /**
+ * Return a String representation of the destination type
+ * @param destType the destination type indicator int
+ * @return a descriptive String
+ */
+ public static String getDestinationTypeAsString(int destType) {
+ if (destType == JMSConstants.QUEUE) {
+ return "Queue";
+ } else if (destType == JMSConstants.TOPIC) {
+ return "Topic";
+ } else {
+ return "Generic";
+ }
+ }
}
Added: webservices/commons/trunk/scratch/asankha/transport/modules/jms/src/main/java/org/apache/axis2/transport/jms/ServiceTaskManager.java
URL: http://svn.apache.org/viewvc/webservices/commons/trunk/scratch/asankha/transport/modules/jms/src/main/java/org/apache/axis2/transport/jms/ServiceTaskManager.java?rev=717873&view=auto
==============================================================================
--- webservices/commons/trunk/scratch/asankha/transport/modules/jms/src/main/java/org/apache/axis2/transport/jms/ServiceTaskManager.java (added)
+++ webservices/commons/trunk/scratch/asankha/transport/modules/jms/src/main/java/org/apache/axis2/transport/jms/ServiceTaskManager.java Sat Nov 15 08:11:11 2008
@@ -0,0 +1,1224 @@
+/*
+ * 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.axis2.transport.jms;
+
+import org.apache.axis2.transport.base.BaseConstants;
+import org.apache.axis2.transport.base.threads.WorkerPool;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.jms.*;
+import javax.jms.IllegalStateException;
+import javax.naming.InitialContext;
+import javax.naming.Context;
+import javax.naming.NamingException;
+import javax.transaction.UserTransaction;
+import javax.transaction.NotSupportedException;
+import javax.transaction.SystemException;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Collections;
+import java.util.ArrayList;
+
+/**
+ * Each service will have one ServiceTaskManager instance that will create, manage and also destroy
+ * idle tasks created for it, for message receipt. This will also allow individual tasks to cache
+ * the Connection, Session or Consumer as necessary, considering the transactionality required and
+ * user preference.
+ *
+ * This also acts as the ExceptionListener for all JMS connections made on behalf of the service.
+ * Since the ExceptionListener is notified by a JMS provider on a "serious" error, we simply try
+ * to re-connect. Thus a connection failure for a single task, will re-initialize the state afresh
+ * for the service, by discarding all connections.
+ */
+public class ServiceTaskManager implements ExceptionListener {
+
+ /** The logger */
+ private static final Log log = LogFactory.getLog(ServiceTaskManager.class);
+
+ /** The Task manager is stopped or has not started */
+ private static final int STATE_STOPPED = 0;
+ /** The Task manager is started and active */
+ private static final int STATE_STARTED = 1;
+ /** The Task manager is paused temporarily */
+ private static final int STATE_PAUSED = 2;
+ /** The Task manager is started, but a shutdown has been requested */
+ private static final int STATE_SHUTTING_DOWN = 3;
+ /** The Task manager has encountered an error */
+ private static final int STATE_FAILURE = 4;
+
+ /** The name of the service managed by this instance */
+ private String serviceName;
+ /** The ConnectionFactory MUST refer to an XAConnectionFactory to use JTA */
+ private String connFactoryJNDIName;
+ /** The JNDI name of the Destination Queue or Topic */
+ private String destinationJNDIName;
+ /** JNDI location for the JTA UserTransaction */
+ private String userTransactionJNDIName = "java:comp/UserTransaction";
+ /** The type of destination - P2P or PubSub (or JMS 1.1 API generic?) */
+ private int destinationType = JMSConstants.GENERIC;
+ /** An optional message selector */
+ private String messageSelector = null;
+
+ /** Should tasks run without transactions, using transacted Sessions (i.e. local), or JTA */
+ private int transactionality = BaseConstants.TRANSACTION_NONE;
+ /** Should created Sessions be transactional ? - should be false when using JTA */
+ private boolean sessionTransacted = true;
+ /** Session acknowledgement mode when transacted Sessions (i.e. local transactions) are used */
+ private int sessionAckMode = Session.AUTO_ACKNOWLEDGE;
+
+ /** Is the subscription durable ? */
+ private boolean subscriptionDurable = false;
+ /** The name of the durable subscriber for this client */
+ private String durableSubscriberName = null;
+ /** In PubSub mode, should I receive messages sent by me / my connection ? */
+ private boolean pubSubNoLocal = false;
+ /** Number of concurrent consumers - for PubSub, this should be 1 to prevent multiple receipt */
+ private int concurrentConsumers = 1;
+ /** Maximum number of consumers to create - see @concurrentConsumers */
+ private int maxConcurrentConsumers = 1;
+ /** The number of idle (i.e. message-less) attempts to be tried before suicide, to scale down */
+ private int idleTaskExecutionLimit = 10;
+ /** The maximum number of successful message receipts for a task - to limit thread life span */
+ private int maxMessagesPerTask = -1; // default is unlimited
+ /** The default receive timeout - a negative value means wait forever, zero dont wait at all */
+ private int receiveTimeout = 1000;
+ /** JMS Resource cache level - Connection, Session, Consumer. Auto will select safe default */
+ private int cacheLevel = JMSConstants.CACHE_AUTO;
+ /** Should we cache the UserTransaction handle from JNDI - true for almost all app servers */
+ private boolean cacheUserTransaction = true;
+ /** Shared UserTransactionHandle */
+ private UserTransaction sharedUserTransaction = null;
+ /** Should this service use JMS 1.1 ? (when false, defaults to 1.0.2b) */
+ private boolean jmsSpec11 = true;
+
+ /** Initial duration to attempt re-connection to JMS provider after failure */
+ private int initialReconnectDuration = 10000;
+ /** Progression factory for geometric series that calculates re-connection times */
+ private double reconnectionProgressionFactor = 2.0; // default to [bounded] exponential
+ /** Upper limit on reconnection attempt duration */
+ private long maxReconnectDuration = 1000 * 60 * 60; // 1 hour
+
+ /** The JNDI context properties */
+ private Hashtable<String,String> jndiProperties = null;
+ /** The JNDI Context acuired */
+ private Context context = null;
+ /** The ConnectionFactory to be used */
+ private ConnectionFactory conFactory = null;
+ /** The shared JMS Connection opened */
+ private Connection sharedConnection = null;
+ /** The shared JMS Connection opened */
+ private Session sharedSession = null;
+ /** The shared JMS Connection opened */
+ private MessageConsumer sharedConsumer = null;
+ /** The JMS Destination */
+ private Destination destination = null;
+
+ /** The list of active tasks thats managed by this instance */
+ private final List<MessageListenerTask> pollingTasks =
+ Collections.synchronizedList(new ArrayList<MessageListenerTask>());
+ /** The per-service JMS message receiver to be invoked after receipt of messages */
+ private JMSMessageReceiver jmsMessageReceiver = null;
+
+ /** State of this Task Manager */
+ private volatile int state = STATE_STOPPED;
+ /** Number of invoker tasks active */
+ private volatile int activeTaskCount = 0;
+ /** The shared thread pool from the Listener */
+ private WorkerPool workerPool = null;
+
+ /** Handle JMS Connection exceptions by re-initializing. A single connection failure could
+ * cause re-initialization of multiple MessageListenerTasks / Connections
+ */
+ public void onException(JMSException j) {
+
+ if (!isActive()) {
+ return;
+ }
+
+ // if we failed while active, update state to show failure
+ state = STATE_FAILURE;
+ log.error("JMS Connection failed : " + j.getMessage() + " - shutting down worker tasks", j);
+
+ int r = 1;
+ long retryDuration = initialReconnectDuration;
+
+ do {
+ try {
+ log.info("Reconnection attempt : " + r + " for service : " + serviceName);
+ start();
+ } catch (Exception e) {
+ log.error("Reconnection attempt : " + (r++) + " for service : " + serviceName +
+ " failed. Next retry in " + (retryDuration/1000) + "seconds", e);
+ retryDuration = (long) (retryDuration * reconnectionProgressionFactor);
+ if (retryDuration > maxReconnectDuration) {
+ retryDuration = maxReconnectDuration;
+ }
+
+ try {
+ Thread.sleep(retryDuration);
+ } catch (InterruptedException ignore) {}
+ }
+ } while (!isActive());
+ }
+
+ /**
+ * Start or re-start the Task Manager by shutting down any existing worker tasks and
+ * re-creating them. However, if this is STM is PAUSED, a start request is ignored.
+ * This applies for any connection failures during paused state as well, which then will
+ * not try to auto recover
+ */
+ public synchronized void start() {
+
+ if (state == STATE_PAUSED) {
+ log.info("Attempt to re-start paused TaskManager is ignored. Please use resume instead");
+ return;
+ }
+
+ // if any tasks are running, stop whats running now
+ if (pollingTasks.isEmpty()) {
+ stop();
+ }
+
+ if (cacheLevel == JMSConstants.CACHE_AUTO) {
+ cacheLevel =
+ transactionality == BaseConstants.TRANSACTION_NONE ?
+ JMSConstants.CACHE_CONSUMER : JMSConstants.CACHE_NONE;
+ }
+ switch (cacheLevel) {
+ case JMSConstants.CACHE_NONE:
+ log.debug("No JMS resources will be cached/shared between poller " +
+ "worker tasks of service : " + serviceName);
+ break;
+ case JMSConstants.CACHE_CONNECTION:
+ log.debug("Only the JMS Connection will be cached and shared between poller " +
+ "tasks of service : " + serviceName);
+ break;
+ case JMSConstants.CACHE_SESSION:
+ log.debug("The JMS Connection and Session will be cached and shared between " +
+ "poller tasks of service : " + serviceName);
+ break;
+ case JMSConstants.CACHE_CONSUMER:
+ log.debug("The JMS Connection, Session and MessageConsumer will be cached and " +
+ "shared between poller tasks of service : " + serviceName);
+ break;
+ default : {
+ handleException("Invalid cache level : " + cacheLevel +
+ " for service : " + serviceName);
+ }
+ }
+
+ for (int i=0; i<concurrentConsumers; i++) {
+ workerPool.execute(new MessageListenerTask());
+ }
+
+ state = STATE_STARTED;
+ log.info("Task manager for service : " + serviceName + " [re-]initialized");
+ }
+
+ /**
+ * Shutdown the tasks and release any shared resources
+ */
+ public synchronized void stop() {
+
+ if (log.isDebugEnabled()) {
+ log.debug("Stopping ServiceTaskManager for service : " + serviceName);
+ }
+
+ if (state != STATE_FAILURE) {
+ state = STATE_SHUTTING_DOWN;
+ }
+
+ synchronized(pollingTasks) {
+ for (MessageListenerTask lstTask : pollingTasks) {
+ lstTask.requestShutdown();
+ }
+ }
+
+ // try to wait a bit for task shutdown
+ for (int i=0; i<5; i++) {
+ if (activeTaskCount == 0) {
+ break;
+ }
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException ignore) {}
+ }
+
+ if (activeTaskCount > 0) {
+ log.warn("Unable to shutdown all polling tasks of service : " + serviceName);
+ }
+
+ if (sharedConsumer != null) {
+ log.debug("Closing shared Consumer - service : " + serviceName);
+ try {
+ sharedConsumer.close();
+ } catch (IllegalStateException ignore) {
+ } catch (JMSException e) {
+ logError("Error closing shared JMS consumer", e);
+ } finally {
+ sharedConsumer = null;
+ }
+ }
+
+ if (sharedSession != null) {
+ log.debug("Closing shared Session - service : " + serviceName);
+ try {
+ sharedSession.close();
+ } catch (IllegalStateException ignore) {
+ } catch (JMSException e) {
+ logError("Error closing shared JMS session", e);
+ } finally {
+ sharedSession = null;
+ }
+ }
+
+ if (sharedConnection != null) {
+ log.debug("Closing shared Connection - service : " + serviceName);
+ try {
+ sharedConnection.close();
+ } catch (IllegalStateException ignore) {
+ } catch (JMSException e) {
+ logError("Error closing shared JMS connection", e);
+ } finally {
+ sharedConnection = null;
+ }
+ }
+
+ if (state != STATE_FAILURE) {
+ state = STATE_STOPPED;
+ }
+ log.info("Task manager for service : " + serviceName + " shutdown");
+ }
+
+ /**
+ * Temporarily suspend receipt and processing of messages. Accomplished by stopping the
+ * connection / or connections used by the poller tasks
+ */
+ public void pause() {
+ for (MessageListenerTask lstTask : pollingTasks) {
+ lstTask.pause();
+ }
+
+ if (sharedConnection != null) {
+ try {
+ sharedConnection.stop();
+ } catch (JMSException e) {
+ logError("Error pausing shared JMS connection", e);
+ }
+ }
+ }
+
+ /**
+ * Resume receipt and processing of messages of paused tasks
+ */
+ public void resume() {
+ for (MessageListenerTask lstTask : pollingTasks) {
+ lstTask.resume();
+ }
+
+ if (sharedConnection != null) {
+ try {
+ sharedConnection.start();
+ } catch (JMSException e) {
+ logError("Error pausing shared JMS connection", e);
+ }
+ }
+ }
+
+ /**
+ * Start a new MessageListenerTask if we are still active, the threshold is not reached, and w
+ * e do not have any idle tasks - i.e. scale up listening
+ */
+ private void scheduleNewTaskIfAppropriate() {
+ if (state == STATE_STARTED &&
+ pollingTasks.size() < getMaxConcurrentConsumers() && getIdleTaskCount() == 0) {
+ workerPool.execute(new MessageListenerTask());
+ }
+ }
+
+ /**
+ * Get the number of MessageListenerTasks that are currently idle
+ * @return idle task count
+ */
+ private int getIdleTaskCount() {
+ int count = 0;
+ for (MessageListenerTask lstTask : pollingTasks) {
+ if (lstTask.isTaskIdle()) {
+ count++;
+ }
+ }
+ return count;
+ }
+
+ /**
+ * The actual threads/tasks that perform message polling
+ */
+ private class MessageListenerTask implements Runnable {
+
+ /** The Connection used by the polling task */
+ private Connection connection = null;
+ /** The Sesson used by the polling task */
+ private Session session = null;
+ /** The MessageConsumer used by the polling task */
+ private MessageConsumer consumer = null;
+ /** State of the worker polling task */
+ private volatile int state = STATE_STOPPED;
+ /** The number of idle (i.e. without fetching a message) polls for this task */
+ private int idleExecutionCount = 0;
+ /** Is this task idle right now? */
+ private volatile boolean idle = false;
+
+ /** As soon as we create a new polling task, add it to the STM for control later */
+ MessageListenerTask() {
+ synchronized(pollingTasks) {
+ pollingTasks.add(this);
+ }
+ }
+
+ /**
+ * Pause this polling worker task
+ */
+ public void pause() {
+ if (isActive()) {
+ if (connection != null && connection != sharedConnection) {
+ try {
+ connection.stop();
+ } catch (JMSException e) {
+ log.warn("Error pausing Message Listener task for service : " + serviceName);
+ }
+ }
+ state = STATE_PAUSED;
+ }
+ }
+
+ /**
+ * Resume this polling task
+ */
+ public void resume() {
+ if (connection != null && connection != sharedConnection) {
+ try {
+ connection.start();
+ } catch (JMSException e) {
+ log.warn("Error resuming Message Listener task for service : " + serviceName);
+ }
+ }
+ state = STATE_STARTED;
+ }
+
+ /**
+ * Execute the polling worker task
+ */
+ public void run() {
+ state = STATE_STARTED;
+ activeTaskCount++;
+ int messageCount = 0;
+
+ if (log.isDebugEnabled()) {
+ log.debug("New poll task starting : thread id = " + Thread.currentThread().getId());
+ }
+
+ while (isActive() &&
+ (getMaxMessagesPerTask() < 0 || messageCount < getMaxMessagesPerTask()) &&
+ (getConcurrentConsumers() == 1 || idleExecutionCount < getIdleTaskExecutionLimit())) {
+
+ UserTransaction ut = null;
+ try {
+ if (transactionality == BaseConstants.TRANSACTION_JTA) {
+ ut = getUserTransaction();
+ ut.begin();
+ }
+ } catch (NotSupportedException e) {
+ handleException("Listener Task is already associated with a transaction", e);
+ } catch (SystemException e) {
+ handleException("Error starting a JTA transaction", e);
+ }
+
+ // Get a message by polling, or receive null
+ Message message = receiveMessage();
+
+ if (log.isTraceEnabled()) {
+ if (message != null) {
+ try {
+ log.trace("<<<<<<< READ message with Message ID : " +
+ message.getJMSMessageID() + " from : " + destination +
+ " by Thread ID : " + Thread.currentThread().getId());
+ } catch (JMSException ignore) {}
+ } else {
+ log.trace("No message received by Thread ID : " +
+ Thread.currentThread().getId() + " for destination : " + destination);
+ }
+ }
+
+ if (message != null) {
+ idle = false;
+ idleExecutionCount = 0;
+ messageCount++;
+ // I will be busy now while processing this message, so start another if needed
+ scheduleNewTaskIfAppropriate();
+ handleMessage(message, ut);
+
+ } else {
+ idle = true;
+ idleExecutionCount++;
+ }
+ }
+
+ if (log.isTraceEnabled()) {
+ log.trace("Listener task with Thread ID : " + Thread.currentThread().getId() +
+ " is stopping after processing : " + messageCount + " messages :: " +
+ " isActive : " + isActive() + " maxMessagesPerTask : " +
+ getMaxMessagesPerTask() + " concurrentConsumers : " + getConcurrentConsumers() +
+ " idleExecutionCount : " + idleExecutionCount + " idleTaskExecutionLimit : " +
+ getIdleTaskExecutionLimit());
+ } else if (log.isDebugEnabled()) {
+ log.debug("Listener task with Thread ID : " + Thread.currentThread().getId() +
+ " is stopping after processing : " + messageCount + " messages");
+ }
+
+ activeTaskCount--;
+ synchronized(pollingTasks) {
+ pollingTasks.remove(this);
+ }
+ // My time is up, so if I am going away, create another
+ scheduleNewTaskIfAppropriate();
+
+ // close any non-shared resources
+ closeConsumer(consumer);
+ closeSession(session);
+ closeConnection(connection);
+ }
+
+ /**
+ * Poll for and return a message if available
+ *
+ * @return a message read, or null
+ */
+ private Message receiveMessage() {
+
+ // get a new connection, session and consumer to prevent a conflict.
+ // If idle, it means we can re-use what we already have
+ if (!idle) {
+ connection = getConnection();
+ session = getSession(connection);
+ consumer = getMessageConsumer(connection, session);
+ if (log.isDebugEnabled()) {
+ log.debug("Preparing a Connection, Session and Consumer to read messages");
+ }
+ }
+
+ if (log.isDebugEnabled()) {
+ log.debug("Waiting for a message for service : " + serviceName + " - duration : "
+ + (getReceiveTimeout() < 0 ? "unlimited" : (getReceiveTimeout() + "ms")));
+ }
+
+ try {
+ if (getReceiveTimeout() < 0) {
+ return consumer.receive();
+ } else {
+ return consumer.receive(getReceiveTimeout());
+ }
+ } catch (IllegalStateException ignore) {
+ // probably the consumer (shared) was closed.. which is still ok.. as we didn't read
+ } catch (JMSException e) {
+ logError("Error receiving message for service : " + serviceName, e);
+ }
+ return null;
+ }
+
+ /**
+ * Invoke ultimate message handler/listener and ack message and/or
+ * commit/rollback transactions
+ * @param message the JMS message received
+ * @param ut the UserTransaction used to receive this message, or null
+ */
+ private void handleMessage(Message message, UserTransaction ut) {
+
+ String messageId = null;
+ try {
+ messageId = message.getJMSMessageID();
+ } catch (JMSException ignore) {}
+
+ boolean commitOrAck = true;
+ try {
+ commitOrAck = jmsMessageReceiver.onMessage(message, ut);
+
+ } finally {
+
+ // if client acknowledgement is selected, and processing requested ACK
+ if (commitOrAck && getSessionAckMode() == Session.CLIENT_ACKNOWLEDGE) {
+ try {
+ message.acknowledge();
+ if (log.isDebugEnabled()) {
+ log.debug("Message : " + messageId + " acknowledged");
+ }
+ } catch (JMSException e) {
+ logError("Error acknowledging message : " + messageId, e);
+ }
+ }
+
+ // close the consumer
+ closeConsumer(consumer);
+
+ // if session was transacted, commit it or rollback
+ try {
+ if (session.getTransacted()) {
+ if (commitOrAck) {
+ session.commit();
+ if (log.isDebugEnabled()) {
+ log.debug("Session for message : " + messageId + " committed");
+ }
+ } else {
+ session.rollback();
+ if (log.isDebugEnabled()) {
+ log.debug("Session for message : " + messageId + " rolled back");
+ }
+ }
+ }
+ } catch (JMSException e) {
+ logError("Error " + (commitOrAck ? "committing" : "rolling back") +
+ " local session txn for message : " + messageId, e);
+ }
+
+ // if a JTA transaction was being used, commit it or rollback
+ try {
+ if (ut != null) {
+ if (commitOrAck) {
+ ut.commit();
+ if (log.isDebugEnabled()) {
+ log.debug("JTA txn for message : " + messageId + " committed");
+ }
+ } else {
+ ut.rollback();
+ if (log.isDebugEnabled()) {
+ log.debug("JTA txn for message : " + messageId + " rolled back");
+ }
+ }
+ }
+ } catch (Exception e) {
+ logError("Error " + (commitOrAck ? "committing" : "rolling back") +
+ " JTA txn for message : " + messageId + " from the session", e);
+ }
+
+ closeSession(session);
+ closeConnection(connection);
+ }
+ }
+
+ protected void requestShutdown() {
+ state = STATE_SHUTTING_DOWN;
+ }
+
+ private boolean isActive() {
+ return state == STATE_STARTED;
+ }
+
+ protected boolean isTaskIdle() {
+ return idle;
+ }
+ }
+
+ // -------------- mundane private methods ----------------
+ /**
+ * Close the given Connection, hiding exceptions if any which are logged
+ * @param connection the Connection to be closed
+ */
+ private void closeConnection(Connection connection) {
+ try {
+ if (connection != null && connection != sharedConnection) {
+ if (log.isDebugEnabled()) {
+ log.debug("Closing non-shared JMS connection for service : " + serviceName);
+ }
+ connection.close();
+ }
+ } catch (JMSException e) {
+ logError("Error closing JMS connection", e);
+ } finally {
+ connection = null;
+ }
+ }
+
+ /**
+ * Close the given Session, hiding exceptions if any which are logged
+ * @param session the Session to be closed
+ */
+ private void closeSession(Session session) {
+ try {
+ if (session != null && session != sharedSession) {
+ if (log.isDebugEnabled()) {
+ log.debug("Closing non-shared JMS session for service : " + serviceName);
+ }
+ session.close();
+ }
+ } catch (JMSException e) {
+ logError("Error closing JMS session", e);
+ } finally {
+ session = null;
+ }
+ }
+
+ /**
+ * Close the given Consumer, hiding exceptions if any which are logged
+ * @param consumer the Consumer to be closed
+ */
+ private void closeConsumer(MessageConsumer consumer) {
+ try {
+ if (consumer != null && consumer != sharedConsumer) {
+ if (log.isDebugEnabled()) {
+ log.debug("Closing non-shared JMS consumer for service : " + serviceName);
+ }
+ consumer.close();
+ consumer = null;
+ }
+ } catch (JMSException e) {
+ logError("Error closing JMS consumer", e);
+ } finally {
+ consumer = null;
+ }
+ }
+
+ /**
+ * Get a Connection that could/should be used by this STM - depends on the cache level to reuse
+ * @return the shared Connection if cache level is higher than CACHE_NONE, or a new Connection
+ */
+ private Connection getConnection() {
+ if (cacheLevel > JMSConstants.CACHE_NONE) {
+ return getSharedConnection();
+ } else {
+ return createConnection();
+ }
+ }
+
+ /**
+ * Get a Session that could/should be used by this STM - depends on the cache level to reuse
+ * @param connection the connection (could be the shared connection) to use to create a Session
+ * @return the shared Session if cache level is higher than CACHE_CONNECTION, or a new Session
+ * created using the Connection passed, or a new/shared connection
+ */
+ private Session getSession(Connection connection) {
+ if (cacheLevel > JMSConstants.CACHE_CONNECTION) {
+ return getSharedSession();
+ } else {
+ return createSession((connection == null ? getConnection() : connection));
+ }
+ }
+
+ /**
+ * Get a MessageConsumer that chould/should be used by this STM - depends on the cache level to
+ * reuse
+ * @param connection option Connection to be used
+ * @param session optional Session to be used
+ * @return the shared MessageConsumer if cache level is higher than CACHE_SESSION, or a new
+ * MessageConsumer possibly using the Connection and Session passed in
+ */
+ private MessageConsumer getMessageConsumer(Connection connection, Session session) {
+ if (cacheLevel > JMSConstants.CACHE_SESSION) {
+ return getSharedConsumer();
+ } else {
+ return createConsumer((session == null ? getSession(connection) : session));
+ }
+ }
+
+ /**
+ * Get the shared Connection for this STM
+ * @return shared Connection for the STM
+ */
+ private synchronized Connection getSharedConnection() {
+ if (sharedConnection == null) {
+ sharedConnection = createConnection();
+ if (log.isDebugEnabled()) {
+ log.debug("Created shared JMS Connection for service : " + serviceName);
+ }
+ }
+ return sharedConnection;
+ }
+
+ /**
+ * Get the shared Session for the STM
+ * @return shared Session for the STM
+ */
+ private synchronized Session getSharedSession() {
+ if (sharedSession == null) {
+ sharedSession = createSession(getSharedConnection());
+ if (log.isDebugEnabled()) {
+ log.debug("Created shared JMS Session for service : " + serviceName);
+ }
+ }
+ return sharedSession;
+ }
+
+ /**
+ * Get the shared MessageConsumer for the STM
+ * @return shared MessageConsumer for the STM
+ */
+ private synchronized MessageConsumer getSharedConsumer() {
+ if (sharedConsumer == null) {
+ sharedConsumer = createConsumer(getSharedSession());
+ if (log.isDebugEnabled()) {
+ log.debug("Created shared JMS MessageConsumer for service : " + serviceName);
+ }
+ }
+ return sharedConsumer;
+ }
+
+ /**
+ * Get the InitialContext for lookup using the JNDI parameters applicable to the service
+ * @return the InitialContext to be used
+ * @throws NamingException
+ */
+ private Context getInitialContext() throws NamingException {
+ if (context == null) {
+ context = new InitialContext(jndiProperties);
+ }
+ return context;
+ }
+
+ /**
+ * Return the JMS Destination for the JNDI name of the Destination from the InitialContext
+ * @return the JMS Destination to which this STM listens for messages
+ */
+ private Destination getDestination() {
+ if (destination == null) {
+ try {
+ context = getInitialContext();
+ destination = JMSUtils.lookup(context, Destination.class, getDestinationJNDIName());
+ if (log.isDebugEnabled()) {
+ log.debug("JMS Destionation with JNDI name : " + getDestinationJNDIName() +
+ " found for service " + serviceName);
+ }
+ } catch (NamingException e) {
+ handleException("Error looking up JMS destination : " + getDestinationJNDIName() +
+ " using JNDI properties : " + jndiProperties, e);
+ }
+ }
+ return destination;
+ }
+
+ /**
+ * The UserTransaction to be used, looked up from the JNDI
+ * @return The UserTransaction to be used, looked up from the JNDI
+ */
+ private UserTransaction getUserTransaction() {
+ if (!cacheUserTransaction) {
+ if (log.isDebugEnabled()) {
+ log.debug("Acquiring a new UserTransaction for service : " + serviceName);
+ }
+
+ try {
+ context = getInitialContext();
+ return
+ JMSUtils.lookup(context, UserTransaction.class, getUserTransactionJNDIName());
+ } catch (NamingException e) {
+ handleException("Error looking up UserTransaction : " + getDestinationJNDIName() +
+ " using JNDI properties : " + jndiProperties, e);
+ }
+ }
+
+ if (sharedUserTransaction == null) {
+ try {
+ context = getInitialContext();
+ sharedUserTransaction =
+ JMSUtils.lookup(context, UserTransaction.class, getUserTransactionJNDIName());
+ if (log.isDebugEnabled()) {
+ log.debug("Acquired shared UserTransaction for service : " + serviceName);
+ }
+ } catch (NamingException e) {
+ handleException("Error looking up UserTransaction : " + getDestinationJNDIName() +
+ " using JNDI properties : " + jndiProperties, e);
+ }
+ }
+ return sharedUserTransaction;
+ }
+
+ /**
+ * Create a new Connection for this STM, using JNDI properties and credentials provided
+ * @return a new Connection for this STM, using JNDI properties and credentials provided
+ */
+ private Connection createConnection() {
+
+ try {
+ conFactory = JMSUtils.lookup(
+ getInitialContext(), ConnectionFactory.class, getConnFactoryJNDIName());
+ log.info("Connected to the JMS connection factory : " + getConnFactoryJNDIName());
+ } catch (NamingException e) {
+ handleException("Error looking up connection factory : " + getConnFactoryJNDIName() +
+ " using JNDI properties : " + jndiProperties, e);
+ }
+
+ Connection connection = null;
+ try {
+ connection = JMSUtils.createConnection(
+ conFactory,
+ jndiProperties.get(Context.SECURITY_PRINCIPAL),
+ jndiProperties.get(Context.SECURITY_CREDENTIALS),
+ isJmsSpec11(), isQueue());
+
+ connection.setExceptionListener(this);
+ connection.start();
+ log.info("JMS Connection for service : " + serviceName + " created and started");
+
+ } catch (JMSException e) {
+ handleException("Error acquiring a JMS connection to : " + getConnFactoryJNDIName() +
+ " using JNDI properties : " + jndiProperties, e);
+ }
+ return connection;
+ }
+
+ /**
+ * Create a new Session for this STM
+ * @param connection the Connection to be used
+ * @return a new Session created using the Connection passed in
+ */
+ private Session createSession(Connection connection) {
+ try {
+ if (log.isDebugEnabled()) {
+ log.debug("Creating a new JMS Session for service : " + serviceName);
+ }
+ return JMSUtils.createSession(
+ connection, isSessionTransacted(), getSessionAckMode(), isJmsSpec11(), isQueue());
+
+ } catch (JMSException e) {
+ handleException("Error creating JMS session for service : " + serviceName, e);
+ }
+ return null;
+ }
+
+ /**
+ * Create a new MessageConsumer for this STM
+ * @param session the Session to be used
+ * @return a new MessageConsumer created using the Session passed in
+ */
+ private MessageConsumer createConsumer(Session session) {
+ try {
+ if (log.isDebugEnabled()) {
+ log.debug("Creating a new JMS MessageConsumer for service : " + serviceName);
+ }
+
+ return JMSUtils.createConsumer(
+ session, getDestination(), isQueue(),
+ (isSubscriptionDurable() && getDurableSubscriberName() == null ?
+ getDurableSubscriberName() : serviceName),
+ getMessageSelector(), isPubSubNoLocal(), isSubscriptionDurable(), isJmsSpec11());
+
+ } catch (JMSException e) {
+ handleException("Error creating JMS consumer for service : " + serviceName,e);
+ }
+ return null;
+ }
+
+
+ // -------------------- trivial methods ---------------------
+ private boolean isActive() {
+ return state == STATE_STARTED;
+ }
+
+ /**
+ * Is this STM bound to a Queue, Topic or a JMS 1.1 Generic Destination?
+ * @return TRUE for a Queue, FALSE for a Topic and NULL for a Generic Destination
+ */
+ private Boolean isQueue() {
+ if (destinationType == JMSConstants.GENERIC) {
+ return null;
+ } else {
+ return destinationType == JMSConstants.QUEUE;
+ }
+ }
+
+ private void logError(String msg, Exception e) {
+ log.error(msg, e);
+ }
+
+ private void handleException(String msg, Exception e) {
+ log.error(msg, e);
+ throw new AxisJMSException(msg, e);
+ }
+
+ private void handleException(String msg) {
+ log.error(msg);
+ throw new AxisJMSException(msg);
+ }
+
+ // -------------- getters and setters ------------------
+ public String getServiceName() {
+ return serviceName;
+ }
+
+ public void setServiceName(String serviceName) {
+ this.serviceName = serviceName;
+ }
+
+ public String getConnFactoryJNDIName() {
+ return connFactoryJNDIName;
+ }
+
+ public void setConnFactoryJNDIName(String connFactoryJNDIName) {
+ this.connFactoryJNDIName = connFactoryJNDIName;
+ }
+
+ public String getDestinationJNDIName() {
+ return destinationJNDIName;
+ }
+
+ public void setDestinationJNDIName(String destinationJNDIName) {
+ this.destinationJNDIName = destinationJNDIName;
+ }
+
+ public int getDestinationType() {
+ return destinationType;
+ }
+
+ public void setDestinationType(int destinationType) {
+ this.destinationType = destinationType;
+ }
+
+ public String getMessageSelector() {
+ return messageSelector;
+ }
+
+ public void setMessageSelector(String messageSelector) {
+ this.messageSelector = messageSelector;
+ }
+
+ public int getTransactionality() {
+ return transactionality;
+ }
+
+ public void setTransactionality(int transactionality) {
+ this.transactionality = transactionality;
+ sessionTransacted = (transactionality == BaseConstants.TRANSACTION_LOCAL);
+ }
+
+ public boolean isSessionTransacted() {
+ return sessionTransacted;
+ }
+
+ public void setSessionTransacted(Boolean sessionTransacted) {
+ if (sessionTransacted != null) {
+ this.sessionTransacted = sessionTransacted;
+ // sesstionTransacted means local transactions are used, however !sessionTransacted does
+ // not mean that JTA is used
+ if (sessionTransacted) {
+ transactionality = BaseConstants.TRANSACTION_LOCAL;
+ }
+ }
+ }
+
+ public int getSessionAckMode() {
+ return sessionAckMode;
+ }
+
+ public void setSessionAckMode(int sessionAckMode) {
+ this.sessionAckMode = sessionAckMode;
+ }
+
+ public boolean isSubscriptionDurable() {
+ return subscriptionDurable;
+ }
+
+ public void setSubscriptionDurable(Boolean subscriptionDurable) {
+ if (subscriptionDurable != null) {
+ this.subscriptionDurable = subscriptionDurable;
+ }
+ }
+
+ public String getDurableSubscriberName() {
+ return durableSubscriberName;
+ }
+
+ public void setDurableSubscriberName(String durableSubscriberName) {
+ this.durableSubscriberName = durableSubscriberName;
+ }
+
+ public boolean isPubSubNoLocal() {
+ return pubSubNoLocal;
+ }
+
+ public void setPubSubNoLocal(Boolean pubSubNoLocal) {
+ if (pubSubNoLocal != null) {
+ this.pubSubNoLocal = pubSubNoLocal;
+ }
+ }
+
+ public int getConcurrentConsumers() {
+ return concurrentConsumers;
+ }
+
+ public void setConcurrentConsumers(int concurrentConsumers) {
+ this.concurrentConsumers = concurrentConsumers;
+ }
+
+ public int getMaxConcurrentConsumers() {
+ return maxConcurrentConsumers;
+ }
+
+ public void setMaxConcurrentConsumers(int maxConcurrentConsumers) {
+ this.maxConcurrentConsumers = maxConcurrentConsumers;
+ }
+
+ public int getIdleTaskExecutionLimit() {
+ return idleTaskExecutionLimit;
+ }
+
+ public void setIdleTaskExecutionLimit(int idleTaskExecutionLimit) {
+ this.idleTaskExecutionLimit = idleTaskExecutionLimit;
+ }
+
+ public int getReceiveTimeout() {
+ return receiveTimeout;
+ }
+
+ public void setReceiveTimeout(int receiveTimeout) {
+ this.receiveTimeout = receiveTimeout;
+ }
+
+ public int getCacheLevel() {
+ return cacheLevel;
+ }
+
+ public void setCacheLevel(int cacheLevel) {
+ this.cacheLevel = cacheLevel;
+ }
+
+ public int getInitialReconnectDuration() {
+ return initialReconnectDuration;
+ }
+
+ public void setInitialReconnectDuration(int initialReconnectDuration) {
+ this.initialReconnectDuration = initialReconnectDuration;
+ }
+
+ public double getReconnectionProgressionFactor() {
+ return reconnectionProgressionFactor;
+ }
+
+ public void setReconnectionProgressionFactor(double reconnectionProgressionFactor) {
+ this.reconnectionProgressionFactor = reconnectionProgressionFactor;
+ }
+
+ public long getMaxReconnectDuration() {
+ return maxReconnectDuration;
+ }
+
+ public void setMaxReconnectDuration(long maxReconnectDuration) {
+ this.maxReconnectDuration = maxReconnectDuration;
+ }
+
+ public int getMaxMessagesPerTask() {
+ return maxMessagesPerTask;
+ }
+
+ public void setMaxMessagesPerTask(int maxMessagesPerTask) {
+ this.maxMessagesPerTask = maxMessagesPerTask;
+ }
+
+ public String getUserTransactionJNDIName() {
+ return userTransactionJNDIName;
+ }
+
+ public void setUserTransactionJNDIName(String userTransactionJNDIName) {
+ if (userTransactionJNDIName != null) {
+ this.userTransactionJNDIName = userTransactionJNDIName;
+ }
+ }
+
+ public boolean isCacheUserTransaction() {
+ return cacheUserTransaction;
+ }
+
+ public void setCacheUserTransaction(Boolean cacheUserTransaction) {
+ if (cacheUserTransaction != null) {
+ this.cacheUserTransaction = cacheUserTransaction;
+ }
+ }
+
+ public boolean isJmsSpec11() {
+ return jmsSpec11;
+ }
+
+ public void setJmsSpec11(boolean jmsSpec11) {
+ this.jmsSpec11 = jmsSpec11;
+ }
+
+ public Hashtable<String, String> getJndiProperties() {
+ return jndiProperties;
+ }
+
+ public void setJndiProperties(Hashtable<String, String> jndiProperties) {
+ this.jndiProperties = jndiProperties;
+ }
+
+ public Context getContext() {
+ return context;
+ }
+
+ public ConnectionFactory getConnectionFactory() {
+ return conFactory;
+ }
+
+ public List<MessageListenerTask> getPollingTasks() {
+ return pollingTasks;
+ }
+
+ public void setJmsMessageReceiver(JMSMessageReceiver jmsMessageReceiver) {
+ this.jmsMessageReceiver = jmsMessageReceiver;
+ }
+
+ public void setWorkerPool(WorkerPool workerPool) {
+ this.workerPool = workerPool;
+ }
+
+ public int getActiveTaskCount() {
+ return activeTaskCount;
+ }
+
+ //--------------------- used for development testing---------------------------
+ /*public static void main(String[] args) throws Exception {
+ //org.apache.log4j.BasicConfigurator.configure();
+ new ServiceTaskManager().testSTM();
+ }
+
+ private void testSTM() throws Exception {
+ ServiceTaskManager stm = new ServiceTaskManager();
+ Hashtable<String, String> props = new Hashtable<String, String>();
+ props.put("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory");
+ props.put("java.naming.provider.url", "t3://localhost:7001");
+ stm.setJndiProperties(props);
+ stm.setConnFactoryJNDIName("weblogic.jms.ConnectionFactory");
+ stm.setDestinationJNDIName("weblogic.examples.jms.MyQueue");
+ stm.setServiceName("test");
+ stm.setCacheLevel(JMSConstants.CACHE_CONNECTION);
+ stm.setMaxConcurrentConsumers(40);
+
+ stm.workerPool = new NativeWorkerPool(20, 40, 5, 100, "JMS-Worker", "jms");
+ stm.start();
+ }
+
+ public boolean processMessage(Message msg, UserTransaction ut) {
+ try {
+ if (msg instanceof TextMessage) {
+ System.out.println("Received : " + ((TextMessage) msg).getText());
+ }
+ return true;
+ } catch (JMSException e) {
+ e.printStackTrace();
+ return false;
+ }
+ }*/
+}