You are viewing a plain text version of this content. The canonical link for it is here.
Posted to server-dev@james.apache.org by no...@apache.org on 2010/10/11 10:00:27 UTC

svn commit: r1021268 - in /james/server/trunk: ./ queue-activemq/ queue-activemq/src/main/java/org/apache/james/queue/activemq/ queue-jms/ queue-jms/src/ queue-jms/src/main/ queue-jms/src/main/java/ queue-jms/src/main/java/org/ queue-jms/src/main/java/...

Author: norman
Date: Mon Oct 11 08:00:27 2010
New Revision: 1021268

URL: http://svn.apache.org/viewvc?rev=1021268&view=rev
Log:
Because activemq 5.4.x is buggy and sometimes corrupt the data we downgrade to activemq 5.3.2 and use "native" jms api to implement our MailQueue. This implementation can be used with every jms broker so its kind of a new feature too :)

Added:
    james/server/trunk/queue-jms/
    james/server/trunk/queue-jms/LICENSE.txt
    james/server/trunk/queue-jms/NOTICE.txt
    james/server/trunk/queue-jms/pom.xml
    james/server/trunk/queue-jms/src/
    james/server/trunk/queue-jms/src/main/
    james/server/trunk/queue-jms/src/main/java/
    james/server/trunk/queue-jms/src/main/java/org/
    james/server/trunk/queue-jms/src/main/java/org/apache/
    james/server/trunk/queue-jms/src/main/java/org/apache/james/
    james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/
    james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/
    james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/BytesMessageInputStream.java
      - copied, changed from r1001593, james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/BytesMessageInputStream.java
    james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/BytesMessageOutputStream.java
      - copied, changed from r1001593, james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/BytesMessageOutputStream.java
    james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/JMSMailQueue.java
    james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/JMSMailQueueFactory.java
Removed:
    james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/BytesMessageInputStream.java
    james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/BytesMessageOutputStream.java
Modified:
    james/server/trunk/pom.xml
    james/server/trunk/queue-activemq/pom.xml
    james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/ActiveMQMailQueue.java
    james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/ActiveMQMailQueueFactory.java
    james/server/trunk/spring-deployment/pom.xml
    james/server/trunk/spring-deployment/src/main/config/james/spring-beans.xml

Modified: james/server/trunk/pom.xml
URL: http://svn.apache.org/viewvc/james/server/trunk/pom.xml?rev=1021268&r1=1021267&r2=1021268&view=diff
==============================================================================
--- james/server/trunk/pom.xml (original)
+++ james/server/trunk/pom.xml Mon Oct 11 08:00:27 2010
@@ -67,6 +67,7 @@
     <module>spring-common</module>
     <module>mailbox-adapter</module>
     <module>queue-api</module>
+    <module>queue-jms</module>
     <module>queue-activemq</module>
   </modules>
   <ciManagement>
@@ -228,6 +229,11 @@
     </dependency>
     <dependency>
       <groupId>org.apache.james</groupId>
+      <artifactId>james-server-queue-jms</artifactId>
+      <version>${project.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.james</groupId>
       <artifactId>james-server-queue-activemq</artifactId>
       <version>${project.version}</version>
     </dependency>
@@ -1140,7 +1146,7 @@
     <productName>Apache-James Mail Server</productName>
     <derby.version>10.5.3.0_1</derby.version>
     <camel.version>2.4.0</camel.version>
-    <activemq.version>5.4.1</activemq.version>
+    <activemq.version>5.3.2</activemq.version>
     <spring.version>3.0.4.RELEASE</spring.version>
     <imap.version>0.2-SNAPSHOT</imap.version>
     <protocols.version>1.2-SNAPSHOT</protocols.version>

Modified: james/server/trunk/queue-activemq/pom.xml
URL: http://svn.apache.org/viewvc/james/server/trunk/queue-activemq/pom.xml?rev=1021268&r1=1021267&r2=1021268&view=diff
==============================================================================
--- james/server/trunk/queue-activemq/pom.xml (original)
+++ james/server/trunk/queue-activemq/pom.xml Mon Oct 11 08:00:27 2010
@@ -34,6 +34,10 @@
     </dependency>
     <dependency>
       <groupId>org.apache.james</groupId>
+      <artifactId>james-server-queue-jms</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.james</groupId>
       <artifactId>james-server-core-api</artifactId>
     </dependency>
     <dependency>
@@ -47,10 +51,12 @@
     <dependency>
       <groupId>org.apache.activemq</groupId>
       <artifactId>activemq-core</artifactId>
+      <version>5.4.1</version>
     </dependency>
    <dependency>
       <groupId>org.apache.activemq</groupId>
       <artifactId>activemq-pool</artifactId>
+      <version>5.4.1</version>
    </dependency>
     <dependency>
       <groupId>commons-logging</groupId>

Modified: james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/ActiveMQMailQueue.java
URL: http://svn.apache.org/viewvc/james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/ActiveMQMailQueue.java?rev=1021268&r1=1021267&r2=1021268&view=diff
==============================================================================
--- james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/ActiveMQMailQueue.java (original)
+++ james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/ActiveMQMailQueue.java Mon Oct 11 08:00:27 2010
@@ -19,14 +19,7 @@
 package org.apache.james.queue.activemq;
 
 import java.io.IOException;
-import java.io.Serializable;
 import java.net.MalformedURLException;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.List;
-import java.util.StringTokenizer;
-import java.util.concurrent.TimeUnit;
 
 import javax.jms.BytesMessage;
 import javax.jms.Connection;
@@ -34,11 +27,9 @@ import javax.jms.ConnectionFactory;
 import javax.jms.JMSException;
 import javax.jms.Message;
 import javax.jms.MessageConsumer;
-import javax.jms.MessageProducer;
 import javax.jms.Queue;
 import javax.jms.Session;
 import javax.mail.MessagingException;
-import javax.mail.internet.AddressException;
 import javax.mail.internet.MimeMessage;
 
 import org.apache.activemq.ActiveMQSession;
@@ -46,14 +37,13 @@ import org.apache.activemq.BlobMessage;
 import org.apache.activemq.command.ActiveMQBlobMessage;
 import org.apache.activemq.pool.PooledSession;
 import org.apache.commons.logging.Log;
-import org.apache.james.core.MailImpl;
 import org.apache.james.core.MimeMessageCopyOnWriteProxy;
 import org.apache.james.core.MimeMessageInputStream;
 import org.apache.james.core.MimeMessageInputStreamSource;
 import org.apache.james.core.MimeMessageWrapper;
 import org.apache.james.queue.MailQueue;
+import org.apache.james.queue.jms.JMSMailQueue;
 import org.apache.mailet.Mail;
-import org.apache.mailet.MailAddress;
 
 /**
  * *{@link MailQueue} implementation which use an ActiveMQ Queue.
@@ -77,53 +67,16 @@ import org.apache.mailet.MailAddress;
  * 
  *
  */
-public class ActiveMQMailQueue implements MailQueue {
+public class ActiveMQMailQueue extends JMSMailQueue {
 
-    private final String queuename;
-    private final ConnectionFactory connectionFactory;
     private long messageTreshold = -1;
-    private Log logger;
-    private final static String JAMES_MAIL_RECIPIENTS = "JAMES_MAIL_RECIPIENTS";
-    private final static String JAMES_MAIL_SENDER = "JAMES_MAIL_SENDER";
-    private final static String JAMES_MAIL_ERROR_MESSAGE = "JAMES_MAIL_ERROR_MESSAGE";
-    private final static String JAMES_MAIL_LAST_UPDATED = "JAMES_MAIL_LAST_UPDATED";
-    private final static String JAMES_MAIL_MESSAGE_SIZE = "JAMES_MAIL_MESSAGE_SIZE";
-    private final static String JAMES_MAIL_NAME = "JAMES_MAIL_NAME";
-    private final static String JAMES_MAIL_SEPERATOR = ";";
-    private final static String JAMES_MAIL_REMOTEHOST = "JAMES_MAIL_REMOTEHOST";
-    private final static String JAMES_MAIL_REMOTEADDR = "JAMES_MAIL_REMOTEADDR";
-    private final static String JAMES_MAIL_STATE = "JAMES_MAIL_STATE";
-    private final static String JAMES_MAIL_ATTRIBUTE_NAMES = "JAMES_MAIL_ATTRIBUTE_NAMES";
+    
     private final static String JAMES_BLOB_URL = "JAMES_BLOB_URL";
     
     public final static int NO_DELAY = -1;
     public final static int DISABLE_TRESHOLD = -1;
     public final static int BLOBMESSAGE_ONLY = 0;
 
-    /**
-     * Handle mail with lowest priority
-     */
-    public final static int LOW_PRIORITY = 0;
-    
-    /**
-     * Handle mail with normal priority (this is the default)
-     */
-    public final static int NORMAL_PRIORITY = 5;
-    
-    /**
-     * Handle mail with highest priority
-     */
-    public final static int HIGH_PRIORITY = 9;
-    
-    /**
-     * Attribute name for support if priority. If the attribute is set and priority handling is enabled it will take care of move the Mails with
-     * higher priority to the head of the queue (so the mails are faster handled).
-     * 
-     * For enabling the feature in AMQ and get some more informations see:
-     * 
-     * http://activemq.apache.org/how-can-i-support-priority-queues.html
-     */
-    public final static String MAIL_PRIORITY = "MAIL_PRIORITY";
     
     /**
      * Construct a new ActiveMQ based {@link MailQueue}. 
@@ -133,16 +86,18 @@ public class ActiveMQMailQueue implement
      * If you want to disable the usage of {@link BlobMessage} just use {@link #DISABLE_TRESHOLD} as value. If you want to use {@link BlobMessage} 
      * for every message (not depending of  the size) just use {@link #BLOBMESSAGE_ONLY} as value.
      * 
+     * For enabling the priority feature in AMQ see:
+     * 
+     * http://activemq.apache.org/how-can-i-support-priority-queues.html
+     * 
      * @param connectionFactory
      * @param queuename
      * @param messageTreshold
      * @param logger
      */
     public ActiveMQMailQueue(final ConnectionFactory connectionFactory, final String queuename, final long messageTreshold, final Log logger) {
-        this.connectionFactory = connectionFactory;     
-        this.queuename = queuename;
+    	super(connectionFactory, queuename, logger);
         this.messageTreshold  = messageTreshold;
-        this.logger = logger;
     }
     
     /**
@@ -227,283 +182,80 @@ public class ActiveMQMailQueue implement
 
     /*
      * (non-Javadoc)
-     * @see org.apache.james.queue.activemq.MailQueue#enQueue(org.apache.mailet.Mail, long, java.util.concurrent.TimeUnit)
-     */
-    public void enQueue(Mail mail, long delay, TimeUnit unit) throws MailQueueException, MessagingException {
-        
-        long mydelay = NO_DELAY;
-        
-        if (delay >= 0) {
-            mydelay = TimeUnit.MILLISECONDS.convert(delay, unit);
-        }
-        
-        Connection connection = null;
-        Session session = null;
-        MessageProducer producer = null;
-        
-        try {
-
-            connection = connectionFactory.createConnection();
-            connection.start();
-            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
-            Queue queue = session.createQueue(queuename);
-            producer = session.createProducer(queue);
-
-            producer.send(createMessage(session, mail, mydelay));
-        } catch (JMSException e) {
-            throw new MailQueueException("Unable to enqueue mail " + mail, e);
-        } catch (MessagingException e) {
-            if (session != null) {
-                try {
-                    session.rollback();
-                } catch (JMSException e1) {
-                    // ignore on rollback
-                }
-            }
-        } finally {
-        	try {
-        		if (producer != null) producer.close();
-        	} catch (JMSException e) {
-                // ignore here
-        	}
-            try {
-                if (session != null) session.close();
-            } catch (JMSException e) {
-                // ignore here
-            }
-            
-            try {
-                if (connection != null)  connection.close();
-            } catch (JMSException e) {
-                // ignore here
-            }
-        }
-      
-    }
-
-    
-    /*
-     * (non-Javadoc)
-     * @see org.apache.james.queue.activemq.MailQueue#enQueue(org.apache.mailet.Mail)
-     */
-    public void enQueue(Mail mail) throws MailQueueException, MessagingException {
-        enQueue(mail, NO_DELAY, null);
-    }
-
-    
-    @Override
-    public String toString() {
-        return "MailQueue:" + queuename;
-    }
-    
-    private Mail createMail(Message message) throws MailQueueException, JMSException {
-        MailImpl mail = new MailImpl();
-        populateMail(message, mail);
-        
-        try {
-            if (message instanceof BytesMessage) {
-                mail.setMessage(new MimeMessageCopyOnWriteProxy(new MimeMessageInputStreamSource(mail.getName(), new BytesMessageInputStream((BytesMessage)message))));
-            } else if (message instanceof BlobMessage) {
-                BlobMessage blobMessage = (BlobMessage) message;
-                try {
-                    // store url for later usage. Maybe we can do something smart for RemoteDelivery here
-                    // TODO: Check if this makes sense at all
-                    mail.setAttribute(JAMES_BLOB_URL, blobMessage.getURL());
-                } catch (MalformedURLException e) {
-                    // Ignore on error
-                    logger.debug("Unable to get url from blobmessage for mail " + mail.getName());
-                }
-                mail.setMessage(new MimeMessageWrapper(new MimeMessageCopyOnWriteProxy(new MimeMessageInputStreamSource(mail.getName(), blobMessage.getInputStream()))));
-                
-            } else {
-                throw new MailQueueException("Not supported JMS Message received " + message);
-            }
-        } catch (IOException e) {
-            throw new MailQueueException("Unable to prepare Mail for dequeue", e);
-        } catch (MessagingException e) {
-            throw new MailQueueException("Unable to prepare Mail for dequeue", e);
-        }
-        return mail; 
-    }
-    
-    /**
-     * Populate Mail with values from Message. This exclude the Mail message
-     * 
-     * @param message
-     * @param mail
-     * @throws JMSException
+     * @see org.apache.james.queue.jms.JMSMailQueue#populateMailMimeMessage(javax.jms.Message, org.apache.mailet.Mail)
      */
-    private void populateMail(Message message, MailImpl mail) throws JMSException {
-
-        mail.setErrorMessage(message.getStringProperty(JAMES_MAIL_ERROR_MESSAGE));
-        mail.setLastUpdated(new Date(message.getLongProperty(JAMES_MAIL_LAST_UPDATED)));
-        mail.setName(message.getStringProperty(JAMES_MAIL_NAME));
-        
-        List<MailAddress> rcpts = new ArrayList<MailAddress>();       
-        String recipients = message.getStringProperty(JAMES_MAIL_RECIPIENTS);
-        StringTokenizer recipientTokenizer = new StringTokenizer(recipients, JAMES_MAIL_SEPERATOR);
-        while(recipientTokenizer.hasMoreTokens()) {
-            try {
-                MailAddress rcpt = new MailAddress(recipientTokenizer.nextToken());
-                rcpts.add(rcpt);
-            } catch (AddressException e) {
-                // Should never happen as long as the user does not modify the the header by himself
-                // Maybe we should log it anyway
-            }
-        }
-        mail.setRecipients(rcpts);
-        mail.setRemoteAddr(message.getStringProperty(JAMES_MAIL_REMOTEADDR));
-        mail.setRemoteHost(message.getStringProperty(JAMES_MAIL_REMOTEHOST));
-        
-        String attributeNames = message.getStringProperty(JAMES_MAIL_ATTRIBUTE_NAMES);
-        StringTokenizer namesTokenizer = new StringTokenizer(attributeNames, JAMES_MAIL_SEPERATOR);
-        while (namesTokenizer.hasMoreTokens()) {
-            String name = namesTokenizer.nextToken();
-            Serializable attrValue = message.getStringProperty(name);
-            
-            mail.setAttribute(name, attrValue);
-        }
-        
-        String sender = message.getStringProperty(JAMES_MAIL_SENDER);
-        if (sender == null || sender.trim().length() <= 0) {
-            mail.setSender(null);
-        } else {
-            try {
-                mail.setSender(new MailAddress(sender));
-            } catch (AddressException e) {
-             // Should never happen as long as the user does not modify the the header by himself
-             // Maybe we should log it anyway
-            }
-        }
-        
-        mail.setState(message.getStringProperty(JAMES_MAIL_STATE));
-
-    }
-    private Message createMessage(Session session, Mail mail, long delayInMillis) throws MailQueueException{
-        try {
-            boolean useBlob = false;
-            if (messageTreshold != -1) {
-                try {
-                if (messageTreshold == 0 || mail.getMessageSize() > messageTreshold) {
-                    useBlob = true;
-                }
-                } catch (MessagingException e) {
-                    logger.info("Unable to calculate message size for mail " + mail.getName() + ". Use BytesMessage for JMS");
-                    useBlob = false;
-                }
-            }
-            if (useBlob == false) {
-                BytesMessage message  = session.createBytesMessage();
-                
-                populateJMSProperties(message, mail, delayInMillis);
-                populateJMSHeaders(message, mail);
-                mail.getMessage().writeTo(new BytesMessageOutputStream(message));;
-                return message;
-            } else {
-                ActiveMQSession amqSession;
-                if (session instanceof PooledSession) {
-                    amqSession = ((PooledSession) session).getInternalSession();
-                } else {
-                    amqSession = (ActiveMQSession) session;
-                }
-                BlobMessage message  = amqSession.createBlobMessage(new MimeMessageInputStream(mail.getMessage()));
-                populateJMSProperties(message, mail, delayInMillis);
-                populateJMSHeaders(message, mail);
-
-                return message;
-            }
-            
-
-        } catch (MessagingException e) {
-            throw new MailQueueException("Unable to prepare Mail for enqueue" , e);
-        } catch (IOException e) {
-            throw new MailQueueException("Unable to prepare Mail for enqueue" , e);
-        } catch (JMSException e) {
-            throw new MailQueueException("Unable to prepare Mail for enqueue" , e);
-        }
-    }
-    
-    
-    /**
-     * Populate JMS Message properties with values 
-     * 
-     * @param message
-     * @param mail
-     * @param delayInMillis
-     * @throws JMSException
-     * @throws MessagingException
-     */
-    @SuppressWarnings("unchecked")
-    private void populateJMSProperties(Message message, Mail mail, long delayInMillis) throws JMSException, MessagingException {
-        if (delayInMillis > 0) {
+	protected void populateMailMimeMessage(Message message, Mail mail)
+			throws MessagingException {
+		 if (message instanceof BlobMessage) {
+			 try {
+				 BlobMessage blobMessage = (BlobMessage) message;
+                 try {
+                     // store url for later usage. Maybe we can do something smart for RemoteDelivery here
+                     // TODO: Check if this makes sense at all
+                     mail.setAttribute(JAMES_BLOB_URL, blobMessage.getURL());
+                 } catch (MalformedURLException e) {
+                     // Ignore on error
+                     logger.debug("Unable to get url from blobmessage for mail " + mail.getName());
+                 }
+                 mail.setMessage(new MimeMessageWrapper(new MimeMessageCopyOnWriteProxy(new MimeMessageInputStreamSource(mail.getName(), blobMessage.getInputStream()))));
+
+			 } catch (IOException e) {
+				 throw new MailQueueException("Unable to populate MimeMessage for mail " + mail.getName(), e);
+			 } catch (JMSException e) {
+				 throw new MailQueueException("Unable to populate MimeMessage for mail " + mail.getName(), e);
+			 }
+		 } else {
+             super.populateMailMimeMessage(message, mail);
+		 }
+	}
+
+	/*
+	 * (non-Javadoc)
+	 * @see org.apache.james.queue.jms.JMSMailQueue#createMessage(javax.jms.Session, org.apache.mailet.Mail, long)
+	 */
+	protected Message createMessage(Session session, Mail mail,
+			long delayInMillis) throws JMSException, IOException, MessagingException {
+
+		boolean useBlob = false;
+		if (messageTreshold != -1) {
+			try {
+				if (messageTreshold == 0 || mail.getMessageSize() > messageTreshold) {
+					useBlob = true;
+				}
+			} catch (MessagingException e) {
+				logger.info("Unable to calculate message size for mail " + mail.getName() + ". Use BytesMessage for JMS");
+				useBlob = false;
+			}
+		}
+		if (useBlob) {
+			ActiveMQSession amqSession;
+			if (session instanceof PooledSession) {
+				amqSession = ((PooledSession) session).getInternalSession();
+			} else {
+				amqSession = (ActiveMQSession) session;
+			}
+			BlobMessage message = amqSession.createBlobMessage(new MimeMessageInputStream(mail.getMessage()));
+			return message;
+		} else {
+			return super.createMessage(session, mail, delayInMillis);
+		}
+
+	}
+
+	/*
+	 * (non-Javadoc)
+	 * @see org.apache.james.queue.jms.JMSMailQueue#populateJMSProperties(javax.jms.Message, org.apache.mailet.Mail, long)
+	 */
+	protected void populateJMSProperties(Message message, Mail mail,
+			long delayInMillis) throws JMSException, MessagingException {
+		if (delayInMillis > 0) {
             // This will get picked up by activemq for delay message
             message.setLongProperty(org.apache.activemq.ScheduledMessage.AMQ_SCHEDULED_DELAY, delayInMillis);
         }
-        
-        message.setStringProperty(JAMES_MAIL_ERROR_MESSAGE, mail.getErrorMessage());
-        message.setLongProperty(JAMES_MAIL_LAST_UPDATED, mail.getLastUpdated().getTime());
-        message.setLongProperty(JAMES_MAIL_MESSAGE_SIZE, mail.getMessageSize());
-        message.setStringProperty(JAMES_MAIL_NAME, mail.getName());
-        
-        StringBuilder recipientsBuilder = new StringBuilder();
-        
-        Iterator<MailAddress> recipients = mail.getRecipients().iterator();
-        while (recipients.hasNext()) {
-            String recipient = recipients.next().toString();
-            recipientsBuilder.append(recipient.trim());
-            if (recipients.hasNext()) {
-                recipientsBuilder.append(JAMES_MAIL_SEPERATOR);
-            }
-        }
-        message.setStringProperty(JAMES_MAIL_RECIPIENTS, recipientsBuilder.toString());
-        message.setStringProperty(JAMES_MAIL_REMOTEADDR, mail.getRemoteAddr());
-        message.setStringProperty(JAMES_MAIL_REMOTEHOST, mail.getRemoteHost());
-        
-        String sender;
-        MailAddress s = mail.getSender();
-        if (s == null) {
-            sender = "";
-        } else {
-            sender = mail.getSender().toString();
-        }
-        
-        StringBuilder attrsBuilder = new StringBuilder();
-        Iterator<String> attrs = mail.getAttributeNames();
-        while (attrs.hasNext()) {
-            String attrName = attrs.next();
-            attrsBuilder.append(attrName);
-            
-            Object value = convertAttributeValue(mail.getAttribute(attrName));
-            message.setObjectProperty(attrName, value);
-            
-            if (attrs.hasNext()) {
-                attrsBuilder.append(JAMES_MAIL_SEPERATOR);
-            }
-        }
-        message.setStringProperty(JAMES_MAIL_ATTRIBUTE_NAMES, attrsBuilder.toString());
-        message.setStringProperty(JAMES_MAIL_SENDER, sender);
-        message.setStringProperty(JAMES_MAIL_STATE, mail.getState());
-        
-        
-    }
-    
-    private void populateJMSHeaders(Message message, Mail mail) throws JMSException, MessagingException {
-    	Object prio = mail.getAttribute(MAIL_PRIORITY);
-    	if (prio instanceof Integer) {
-        	message.setJMSPriority((Integer) prio);
-    	}
-    }
-    
-    /**
-     * Convert the attribute value if necessary. 
-     * 
-     * @param value
-     * @return convertedValue
-     */
-    protected Object convertAttributeValue(Object value){
-        if (value == null || value instanceof String || value instanceof Byte || value instanceof Long || value instanceof Double || value instanceof Boolean || value instanceof Integer || value instanceof Short || value instanceof Float) {
-            return value;
-        }
-        return value.toString();
-    }
+		
+		super.populateJMSProperties(message, mail, delayInMillis);
+	}
+	
+	
+
 }

Modified: james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/ActiveMQMailQueueFactory.java
URL: http://svn.apache.org/viewvc/james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/ActiveMQMailQueueFactory.java?rev=1021268&r1=1021267&r2=1021268&view=diff
==============================================================================
--- james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/ActiveMQMailQueueFactory.java (original)
+++ james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/ActiveMQMailQueueFactory.java Mon Oct 11 08:00:27 2010
@@ -18,19 +18,13 @@
  ****************************************************************/
 package org.apache.james.queue.activemq;
 
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.annotation.Resource;
 import javax.jms.BytesMessage;
-import javax.jms.ConnectionFactory;
 import javax.jms.Message;
 
 import org.apache.activemq.BlobMessage;
-import org.apache.commons.logging.Log;
-import org.apache.james.lifecycle.LogEnabled;
 import org.apache.james.queue.MailQueue;
 import org.apache.james.queue.MailQueueFactory;
+import org.apache.james.queue.jms.JMSMailQueueFactory;
 
 
 /**
@@ -40,20 +34,10 @@ import org.apache.james.queue.MailQueueF
  * 
  *
  */
-public class ActiveMQMailQueueFactory implements MailQueueFactory, LogEnabled{
+public class ActiveMQMailQueueFactory extends JMSMailQueueFactory{
 
-    
-    
-    private final Map<String, MailQueue> queues = new HashMap<String, MailQueue>();
-    private ConnectionFactory connectionFactory;
     private long sizeTreshold = ActiveMQMailQueue.DISABLE_TRESHOLD;
-    private Log log;
-    
-    @Resource(name="jmsConnectionFactory")
-    public void setConnectionFactory(ConnectionFactory connectionFactory) {
-        this.connectionFactory = connectionFactory;
-    }
-    
+  
     /**
      * The size treshold which will be used for setting if a {@link BlobMessage} or {@link BytesMessage} will be used
      * as {@link Message} type. See {@link ActiveMQMailQueue} for more details
@@ -66,29 +50,10 @@ public class ActiveMQMailQueueFactory im
     
     
     
-    /*
-     * 
-     * (non-Javadoc)
-     * @see org.apache.james.queue.activemq.MailQueueFactory#getQueue(java.lang.String)
-     */
-    public synchronized MailQueue getQueue(String name) {
-        MailQueue queue = queues.get(name);
-        if (queue == null) {
-            queue = new ActiveMQMailQueue(connectionFactory, name, sizeTreshold, log);
-            queues.put(name, queue);
-        }
-
-        return queue;
-    }
-
 
-
-    /*
-     * (non-Javadoc)
-     * @see org.apache.james.lifecycle.LogEnabled#setLog(org.apache.commons.logging.Log)
-     */
-    public void setLog(Log log) {
-        this.log = log;
-    }
+    @Override
+	protected MailQueue createMailQueue(String name) {
+    	return new ActiveMQMailQueue(connectionFactory, name, sizeTreshold, log);
+	}
 
 }

Added: james/server/trunk/queue-jms/LICENSE.txt
URL: http://svn.apache.org/viewvc/james/server/trunk/queue-jms/LICENSE.txt?rev=1021268&view=auto
==============================================================================
--- james/server/trunk/queue-jms/LICENSE.txt (added)
+++ james/server/trunk/queue-jms/LICENSE.txt Mon Oct 11 08:00:27 2010
@@ -0,0 +1,218 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+   
+   
+   
+
+   THIS PRODUCT ALSO INCLUDES THIRD PARTY SOFTWARE REDISTRIBUTED UNDER THE
+   FOLLOWING LICENSES:
+   
+   
+   
+   Concurrent, Public Domain (see lib/concurrent.LICENSE)
+   
+   BouncyCastle, MIT License (see lib/BouncyCastle.LICENSE)
+     http://www.bouncycastle.org/licence.html
+     
+   DnsJava, BSD License (see lib/dnsjava.LICENSE)
+     http://www.dnsjava.org/README 
+     
+   JavaBeans Activation Framework, CDDL License
+     http://glassfish.dev.java.net/public/CDDLv1.0.html
+     
+   JavaMail, CDDL License
+     http://glassfish.dev.java.net/public/CDDLv1.0.html
+   
+   QDox, ASL 1.1 License (see tools/lib/qdox.LICENSE)
+     http://qdox.codehaus.org/license.html
+     
+   MX4J, ASL 1.1 License (see phoenix-bin/bin/lib/mx4j.LICENSE)
+   
+   Spice, ASL 1.1 License (see phoenix-bin/bin/lib/spice.LICENSE)
+     http://spice.codehaus.org/license.html
+     
+   Wrapper, MIT License (see phoenix-bin/bin/Wrapper.LICENSE)
+     http://wrapper.tanukisoftware.org/doc/english/license.html
+     
+   ISO-Relax, MIT License (see phoenix-bin/tools/lib/isorelax.LICENSE)
+
+   MSV, BSD License (see phoenix-bin/tools/lib/msv.LICENSE)
+
+   RelaxNG-Datatype, BSD License (see phoenix-bin/tools/lib/relaxngDatatype.LICENSE)
+   
+   XSDLib, BSD License (see phoenix-bin/tools/lib/xsdlib.LICENSE)
+   
\ No newline at end of file

Added: james/server/trunk/queue-jms/NOTICE.txt
URL: http://svn.apache.org/viewvc/james/server/trunk/queue-jms/NOTICE.txt?rev=1021268&view=auto
==============================================================================
--- james/server/trunk/queue-jms/NOTICE.txt (added)
+++ james/server/trunk/queue-jms/NOTICE.txt Mon Oct 11 08:00:27 2010
@@ -0,0 +1,11 @@
+
+=========================================================================
+==      NOTICE file for use with the Apache License, Version 2.0,      ==
+=========================================================================
+
+Apache JAMES 
+Copyright 2007 The Apache Software Foundation
+
+This product includes software developed at
+The Apache Software Foundation (http://www.apache.org/).
+            
\ No newline at end of file

Added: james/server/trunk/queue-jms/pom.xml
URL: http://svn.apache.org/viewvc/james/server/trunk/queue-jms/pom.xml?rev=1021268&view=auto
==============================================================================
--- james/server/trunk/queue-jms/pom.xml (added)
+++ james/server/trunk/queue-jms/pom.xml Mon Oct 11 08:00:27 2010
@@ -0,0 +1,64 @@
+<?xml version="1.0" encoding="ISO-8859-15"?>
+<!--
+  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">
+  <parent>
+    <artifactId>james-server</artifactId>
+    <groupId>org.apache.james</groupId>
+    <version>3.0-SNAPSHOT</version>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.apache.james</groupId>
+  <artifactId>james-server-queue-jms</artifactId>
+  <name>Apache James Server JMS Mail Queue</name>
+  <dependencies>
+    <dependency>
+      <groupId>org.apache.james</groupId>
+      <artifactId>james-server-queue-api</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.james</groupId>
+      <artifactId>james-server-core-api</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.james</groupId>
+      <artifactId>james-server-core-library</artifactId>
+    </dependency>
+     <dependency>
+      <groupId>org.apache.james</groupId>
+      <artifactId>apache-mailet</artifactId>
+    </dependency>   
+    <dependency>
+      <groupId>commons-logging</groupId>
+      <artifactId>commons-logging-api</artifactId>
+    </dependency> 
+    <dependency>
+      <groupId>org.apache.geronimo.specs</groupId>
+      <artifactId>geronimo-jms_1.1_spec</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>${javax.mail.groupId}</groupId>
+      <artifactId>${javax.mail.artifactId}</artifactId>
+    </dependency>
+    <dependency>
+       <groupId>org.apache.geronimo.specs</groupId>
+       <artifactId>geronimo-annotation_1.0_spec</artifactId>
+    </dependency>
+  </dependencies>
+</project>

Copied: james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/BytesMessageInputStream.java (from r1001593, james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/BytesMessageInputStream.java)
URL: http://svn.apache.org/viewvc/james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/BytesMessageInputStream.java?p2=james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/BytesMessageInputStream.java&p1=james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/BytesMessageInputStream.java&r1=1001593&r2=1021268&rev=1021268&view=diff
==============================================================================
--- james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/BytesMessageInputStream.java (original)
+++ james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/BytesMessageInputStream.java Mon Oct 11 08:00:27 2010
@@ -16,7 +16,7 @@
  * specific language governing permissions and limitations      *
  * under the License.                                           *
  ****************************************************************/
-package org.apache.james.queue.activemq;
+package org.apache.james.queue.jms;
 
 import java.io.IOException;
 import java.io.InputStream;

Copied: james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/BytesMessageOutputStream.java (from r1001593, james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/BytesMessageOutputStream.java)
URL: http://svn.apache.org/viewvc/james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/BytesMessageOutputStream.java?p2=james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/BytesMessageOutputStream.java&p1=james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/BytesMessageOutputStream.java&r1=1001593&r2=1021268&rev=1021268&view=diff
==============================================================================
--- james/server/trunk/queue-activemq/src/main/java/org/apache/james/queue/activemq/BytesMessageOutputStream.java (original)
+++ james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/BytesMessageOutputStream.java Mon Oct 11 08:00:27 2010
@@ -16,7 +16,7 @@
  * specific language governing permissions and limitations      *
  * under the License.                                           *
  ****************************************************************/
-package org.apache.james.queue.activemq;
+package org.apache.james.queue.jms;
 
 import java.io.IOException;
 import java.io.OutputStream;

Added: james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/JMSMailQueue.java
URL: http://svn.apache.org/viewvc/james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/JMSMailQueue.java?rev=1021268&view=auto
==============================================================================
--- james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/JMSMailQueue.java (added)
+++ james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/JMSMailQueue.java Mon Oct 11 08:00:27 2010
@@ -0,0 +1,447 @@
+/****************************************************************
+ * 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.james.queue.jms;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import java.util.StringTokenizer;
+import java.util.concurrent.TimeUnit;
+
+import javax.jms.BytesMessage;
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.mail.MessagingException;
+import javax.mail.internet.AddressException;
+import javax.mail.internet.MimeMessage;
+
+import org.apache.commons.logging.Log;
+import org.apache.james.core.MailImpl;
+import org.apache.james.core.MimeMessageCopyOnWriteProxy;
+import org.apache.james.core.MimeMessageInputStreamSource;
+import org.apache.james.core.MimeMessageWrapper;
+import org.apache.james.queue.MailQueue;
+import org.apache.mailet.Mail;
+import org.apache.mailet.MailAddress;
+
+/**
+ * {@link MailQueue} implementation which use a JMS Queue for the {@link MailQueue}. This implementation should work with every JMS 1.1.0 implementation
+ * 
+ *
+ */
+public class JMSMailQueue implements MailQueue{
+
+	protected final String queuename;
+	protected final ConnectionFactory connectionFactory;
+	protected final Log logger;
+    protected final static String JAMES_MAIL_RECIPIENTS = "JAMES_MAIL_RECIPIENTS";
+    protected final static String JAMES_MAIL_SENDER = "JAMES_MAIL_SENDER";
+    protected final static String JAMES_MAIL_ERROR_MESSAGE = "JAMES_MAIL_ERROR_MESSAGE";
+    protected final static String JAMES_MAIL_LAST_UPDATED = "JAMES_MAIL_LAST_UPDATED";
+    protected final static String JAMES_MAIL_MESSAGE_SIZE = "JAMES_MAIL_MESSAGE_SIZE";
+    protected final static String JAMES_MAIL_NAME = "JAMES_MAIL_NAME";
+    protected final static String JAMES_MAIL_SEPERATOR = ";";
+    protected final static String JAMES_MAIL_REMOTEHOST = "JAMES_MAIL_REMOTEHOST";
+    protected final static String JAMES_MAIL_REMOTEADDR = "JAMES_MAIL_REMOTEADDR";
+    protected final static String JAMES_MAIL_STATE = "JAMES_MAIL_STATE";
+    protected final static String JAMES_MAIL_ATTRIBUTE_NAMES = "JAMES_MAIL_ATTRIBUTE_NAMES";
+    protected final static String JAMES_NEXT_DELIVERY = "JAMES_NEXT_DELIVERY";
+
+
+    /**
+     * Handle mail with lowest priority
+     */
+    public final static int LOW_PRIORITY = 0;
+    
+    /**
+     * Handle mail with normal priority (this is the default)
+     */
+    public final static int NORMAL_PRIORITY = 5;
+    
+    /**
+     * Handle mail with highest priority
+     */
+    public final static int HIGH_PRIORITY = 9;
+    
+    /**
+     * Attribute name for support if priority. If the attribute is set and priority handling is enabled it will take care of move the Mails with
+     * higher priority to the head of the queue (so the mails are faster handled).
+     * 
+     */
+    public final static String MAIL_PRIORITY = "MAIL_PRIORITY";
+    
+    public JMSMailQueue(final ConnectionFactory connectionFactory, final String queuename, final Log logger) {
+        this.connectionFactory = connectionFactory;
+        this.queuename = queuename;
+        this.logger = logger;
+    }
+    
+    /**
+     * Execute the given {@link DequeueOperation} when a mail is ready to precoess. As JMS does not support delay scheduling out-of-the box, we use 
+     * a messageselector to check if a mail is ready. For this a {@link MessageConsumer#receive(long) is used with a timeout of 10 seconds. 
+     * 
+     * Many JMS implementations support better solutions for this, so this should get overridden by these implementations
+     * 
+     * @see org.apache.james.queue.MailQueue#deQueue(org.apache.james.queue.MailQueue.DequeueOperation)
+     */
+    public void deQueue(DequeueOperation operation) throws MailQueueException, MessagingException {   
+        Connection connection = null;
+        Session session = null;
+        Message message = null;
+        MessageConsumer consumer = null;
+        boolean received = false;
+        
+        while(received == false) {
+            try {
+                connection = connectionFactory.createConnection();
+                connection.start();
+            
+                session = connection.createSession(true, Session.SESSION_TRANSACTED);
+                Queue queue = session.createQueue(queuename);
+                consumer = session.createConsumer(queue, JAMES_NEXT_DELIVERY +  " <= " + System.currentTimeMillis());
+            
+                message = consumer.receive(10000);
+           
+                if (message != null) {
+                	received = true;
+                    Mail mail = createMail(message);
+                    operation.process(mail);
+                }
+                session.commit();
+         
+            } catch (JMSException e) {
+                throw new MailQueueException("Unable to dequeue next message", e);
+            } catch (MessagingException e) {
+        	
+                if (session != null) {
+                    try {
+                        session.rollback();
+                    } catch (JMSException e1) {
+                    // ignore on rollback
+                    }
+                }
+            } finally {
+            	if (consumer != null) {
+        		
+        		    try {
+		    			consumer.close();
+			    	} catch (JMSException e1) {
+                        // ignore on rollback
+				    }
+				}
+				try {
+					if (session != null)
+						session.close();
+				} catch (JMSException e) {
+					// ignore here
+				}
+
+				try {
+					if (connection != null)
+						connection.close();
+				} catch (JMSException e) {
+					// ignore here
+				}
+            }
+        }
+       
+    }
+    
+    /*
+     * (non-Javadoc)
+     * @see org.apache.james.queue.MailQueue#enQueue(org.apache.mailet.Mail, long, java.util.concurrent.TimeUnit)
+     */
+	public void enQueue(Mail mail, long delay, TimeUnit unit)
+			throws MailQueueException, MessagingException {
+		Connection connection = null;
+		Session session = null;
+		MessageProducer producer = null;
+        
+        long mydelay = 0;
+        
+        if (delay > 0) {
+            mydelay = TimeUnit.MILLISECONDS.convert(delay, unit);
+        }
+        
+		try {
+
+			connection = connectionFactory.createConnection();
+			connection.start();
+			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+			Queue queue = session.createQueue(queuename);
+			producer = session.createProducer(queue);
+			Message message = createMessage(session, mail, mydelay);
+			populateJMSProperties(message, mail, mydelay);
+			populateJMSHeaders(message, mail);
+			
+			producer.send(message);
+		} catch (Exception e) {
+			if (session != null) {
+				try {
+					session.rollback();
+				} catch (JMSException e1) {
+					// ignore on rollback
+				}
+			}
+			throw new MailQueueException("Unable to enqueue mail " + mail, e);
+		
+		} finally {
+			
+			try {
+				if (producer != null)
+					producer.close();
+			} catch (JMSException e) {
+				// ignore here
+			}
+			try {
+				if (session != null)
+					session.close();
+			} catch (JMSException e) {
+				// ignore here
+			}
+
+			try {
+				if (connection != null)
+					connection.close();
+			} catch (JMSException e) {
+				// ignore here
+			}
+		}
+	}
+
+	
+	/*
+	 * (non-Javadoc)
+	 * @see org.apache.james.queue.MailQueue#enQueue(org.apache.mailet.Mail)
+	 */
+	public void enQueue(Mail mail) throws MailQueueException,
+			MessagingException {
+		enQueue(mail, 0, TimeUnit.MILLISECONDS);
+	}
+	
+	/**
+	 * Create Message which holds the {@link MimeMessage} of the given Mail
+	 * 
+	 * @param session
+	 * @param mail
+	 * @return jmsMessage
+	 * @throws JMSException
+	 * @throws IOException
+	 * @throws MessagingException
+	 * @throws IOException 
+	 */
+	protected Message createMessage(Session session, Mail mail, long delayInMillis) throws JMSException, MessagingException, IOException {
+        BytesMessage message  = session.createBytesMessage();
+        mail.getMessage().writeTo(new BytesMessageOutputStream(message));;
+        return message;
+	}
+	/**
+     * Populate JMS Message properties with values 
+     * 
+     * @param message
+     * @param mail
+     * @param delayInMillis
+     * @throws JMSException
+     * @throws MessagingException
+     */
+    @SuppressWarnings("unchecked")
+	protected void populateJMSProperties(Message message, Mail mail, long delayInMillis) throws JMSException, MessagingException {
+        long nextDelivery = System.currentTimeMillis() + delayInMillis;
+        message.setLongProperty(JAMES_NEXT_DELIVERY, nextDelivery);
+        message.setStringProperty(JAMES_MAIL_ERROR_MESSAGE, mail.getErrorMessage());
+        message.setLongProperty(JAMES_MAIL_LAST_UPDATED, mail.getLastUpdated().getTime());
+        message.setLongProperty(JAMES_MAIL_MESSAGE_SIZE, mail.getMessageSize());
+        message.setStringProperty(JAMES_MAIL_NAME, mail.getName());
+        
+        StringBuilder recipientsBuilder = new StringBuilder();
+        
+        Iterator<MailAddress> recipients = mail.getRecipients().iterator();
+        while (recipients.hasNext()) {
+            String recipient = recipients.next().toString();
+            recipientsBuilder.append(recipient.trim());
+            if (recipients.hasNext()) {
+                recipientsBuilder.append(JAMES_MAIL_SEPERATOR);
+            }
+        }
+        message.setStringProperty(JAMES_MAIL_RECIPIENTS, recipientsBuilder.toString());
+        message.setStringProperty(JAMES_MAIL_REMOTEADDR, mail.getRemoteAddr());
+        message.setStringProperty(JAMES_MAIL_REMOTEHOST, mail.getRemoteHost());
+        
+        String sender;
+        MailAddress s = mail.getSender();
+        if (s == null) {
+            sender = "";
+        } else {
+            sender = mail.getSender().toString();
+        }
+        
+        StringBuilder attrsBuilder = new StringBuilder();
+        Iterator<String> attrs = mail.getAttributeNames();
+        while (attrs.hasNext()) {
+            String attrName = attrs.next();
+            attrsBuilder.append(attrName);
+            
+            Object value = convertAttributeValue(mail.getAttribute(attrName));
+            message.setObjectProperty(attrName, value);
+            
+            if (attrs.hasNext()) {
+                attrsBuilder.append(JAMES_MAIL_SEPERATOR);
+            }
+        }
+        message.setStringProperty(JAMES_MAIL_ATTRIBUTE_NAMES, attrsBuilder.toString());
+        message.setStringProperty(JAMES_MAIL_SENDER, sender);
+        message.setStringProperty(JAMES_MAIL_STATE, mail.getState());
+        
+        
+    }
+    
+    /**
+     * Populate the JMS Message Headers from the given {@link Mail}
+     * 
+     * @param message
+     * @param mail
+     * @throws JMSException
+     * @throws MessagingException
+     */
+    protected void populateJMSHeaders(Message message, Mail mail) throws JMSException, MessagingException {
+    	Object prio = mail.getAttribute(MAIL_PRIORITY);
+    	if (prio instanceof Integer) {
+        	message.setJMSPriority((Integer) prio);
+    	}
+    }
+    
+    /**
+     * Create the complete Mail from the JMS Message. So the created {@link Mail} is completly populated
+     * 
+     * @param message
+     * @return
+     * @throws MessagingException
+     * @throws JMSException
+     */
+    protected final Mail createMail(Message message) throws MessagingException, JMSException {
+        MailImpl mail = new MailImpl();
+        populateMail(message, mail);
+        populateMailMimeMessage(message, mail);
+
+        return mail; 
+    }
+
+    /**
+     * Populat the given {@link Mail} instance with a {@link MimeMessage}. The {@link MimeMessage} is read from the JMS Message. This implementation
+     * use a {@link BytesMessage}
+     * 
+     * @param message
+     * @param mail
+     * @throws MessagingException
+     */
+	protected void populateMailMimeMessage(Message message, Mail mail)
+			throws MessagingException {
+		if (message instanceof BytesMessage) {
+			mail.setMessage(new MimeMessageWrapper(new MimeMessageCopyOnWriteProxy(new MimeMessageInputStreamSource(mail.getName(),new BytesMessageInputStream((BytesMessage) message)))));
+		} else {
+			throw new MailQueueException("Not supported JMS Message received "+ message);
+		}
+
+	}
+    
+    /**
+     * Populate Mail with values from Message. This exclude the {@link MimeMessage}
+     * 
+     * @param message
+     * @param mail
+     * @throws JMSException
+     */
+    protected void populateMail(Message message, MailImpl mail) throws JMSException {
+
+        mail.setErrorMessage(message.getStringProperty(JAMES_MAIL_ERROR_MESSAGE));
+        mail.setLastUpdated(new Date(message.getLongProperty(JAMES_MAIL_LAST_UPDATED)));
+        mail.setName(message.getStringProperty(JAMES_MAIL_NAME));
+        
+        List<MailAddress> rcpts = new ArrayList<MailAddress>();       
+        String recipients = message.getStringProperty(JAMES_MAIL_RECIPIENTS);
+        StringTokenizer recipientTokenizer = new StringTokenizer(recipients, JAMES_MAIL_SEPERATOR);
+        while(recipientTokenizer.hasMoreTokens()) {
+            try {
+                MailAddress rcpt = new MailAddress(recipientTokenizer.nextToken());
+                rcpts.add(rcpt);
+            } catch (AddressException e) {
+                // Should never happen as long as the user does not modify the the header by himself
+                // Maybe we should log it anyway
+            }
+        }
+        mail.setRecipients(rcpts);
+        mail.setRemoteAddr(message.getStringProperty(JAMES_MAIL_REMOTEADDR));
+        mail.setRemoteHost(message.getStringProperty(JAMES_MAIL_REMOTEHOST));
+        
+        String attributeNames = message.getStringProperty(JAMES_MAIL_ATTRIBUTE_NAMES);
+        StringTokenizer namesTokenizer = new StringTokenizer(attributeNames, JAMES_MAIL_SEPERATOR);
+        while (namesTokenizer.hasMoreTokens()) {
+            String name = namesTokenizer.nextToken();
+            Serializable attrValue = message.getStringProperty(name);
+            
+            mail.setAttribute(name, attrValue);
+        }
+        
+        String sender = message.getStringProperty(JAMES_MAIL_SENDER);
+        if (sender == null || sender.trim().length() <= 0) {
+            mail.setSender(null);
+        } else {
+            try {
+                mail.setSender(new MailAddress(sender));
+            } catch (AddressException e) {
+             // Should never happen as long as the user does not modify the the header by himself
+             // Maybe we should log it anyway
+            }
+        }
+        
+        mail.setState(message.getStringProperty(JAMES_MAIL_STATE));
+
+	}
+
+    
+    
+    /**
+     * Convert the attribute value if necessary. 
+     * 
+     * @param value
+     * @return convertedValue
+     */
+    protected Object convertAttributeValue(Object value){
+        if (value == null || value instanceof String || value instanceof Byte || value instanceof Long || value instanceof Double || value instanceof Boolean || value instanceof Integer || value instanceof Short || value instanceof Float) {
+            return value;
+        }
+        return value.toString();
+    }
+    
+    
+    @Override
+    public String toString() {
+        return "MailQueue:" + queuename;
+    }
+
+}

Added: james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/JMSMailQueueFactory.java
URL: http://svn.apache.org/viewvc/james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/JMSMailQueueFactory.java?rev=1021268&view=auto
==============================================================================
--- james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/JMSMailQueueFactory.java (added)
+++ james/server/trunk/queue-jms/src/main/java/org/apache/james/queue/jms/JMSMailQueueFactory.java Mon Oct 11 08:00:27 2010
@@ -0,0 +1,83 @@
+/****************************************************************
+ * 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.james.queue.jms;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.annotation.Resource;
+import javax.jms.ConnectionFactory;
+
+import org.apache.commons.logging.Log;
+import org.apache.james.lifecycle.LogEnabled;
+import org.apache.james.queue.MailQueue;
+import org.apache.james.queue.MailQueueFactory;
+
+/**
+ * {@link MailQueueFactory} implementation which use JMS
+ * 
+ *
+ */
+public class JMSMailQueueFactory implements MailQueueFactory, LogEnabled{
+
+    
+    
+    private final Map<String, MailQueue> queues = new HashMap<String, MailQueue>();
+    protected ConnectionFactory connectionFactory;
+    protected Log log;
+    
+    @Resource(name="jmsConnectionFactory")
+    public void setConnectionFactory(ConnectionFactory connectionFactory) {
+        this.connectionFactory = connectionFactory;
+    }
+    
+    /*
+     * 
+     * (non-Javadoc)
+     * @see org.apache.james.queue.activemq.MailQueueFactory#getQueue(java.lang.String)
+     */
+    public synchronized final MailQueue getQueue(String name) {
+        MailQueue queue = queues.get(name);
+        if (queue == null) {
+            queue = createMailQueue(name);
+            queues.put(name, queue);
+        }
+
+        return queue;
+    }
+
+
+    /**
+     * Create a {@link MailQueue} for the given name
+     * 
+     * @param name
+     * @return queue
+     */
+    protected MailQueue createMailQueue(String name) {
+    	return new JMSMailQueue(connectionFactory, name, log);
+    }
+
+    /*
+     * (non-Javadoc)
+     * @see org.apache.james.lifecycle.LogEnabled#setLog(org.apache.commons.logging.Log)
+     */
+    public void setLog(Log log) {
+        this.log = log;
+    }
+}
\ No newline at end of file

Modified: james/server/trunk/spring-deployment/pom.xml
URL: http://svn.apache.org/viewvc/james/server/trunk/spring-deployment/pom.xml?rev=1021268&r1=1021267&r2=1021268&view=diff
==============================================================================
--- james/server/trunk/spring-deployment/pom.xml (original)
+++ james/server/trunk/spring-deployment/pom.xml Mon Oct 11 08:00:27 2010
@@ -511,6 +511,11 @@
     </dependency>
     <dependency>
       <groupId>org.apache.james</groupId>
+      <artifactId>james-server-queue-jms</artifactId>
+      <scope>runtime</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.james</groupId>
       <artifactId>james-server-queue-activemq</artifactId>
       <scope>runtime</scope>
     </dependency>

Modified: james/server/trunk/spring-deployment/src/main/config/james/spring-beans.xml
URL: http://svn.apache.org/viewvc/james/server/trunk/spring-deployment/src/main/config/james/spring-beans.xml?rev=1021268&r1=1021267&r2=1021268&view=diff
==============================================================================
--- james/server/trunk/spring-deployment/src/main/config/james/spring-beans.xml (original)
+++ james/server/trunk/spring-deployment/src/main/config/james/spring-beans.xml Mon Oct 11 08:00:27 2010
@@ -129,11 +129,12 @@
     </camel:camelContext>
 
     <!--  lets create an embedded ActiveMQ Broker -->
-    <amq:broker useJmx="false" persistent="true" brokerName="james" dataDirectory="filesystem=file://var/activemq-data/" schedulerSupport="true" useShutdownHook="false" id="broker">
+    <amq:broker useJmx="false" persistent="true" brokerName="james" dataDirectory="filesystem=file://var/activemq-data/" useShutdownHook="false" id="broker">
         <amq:destinationPolicy>
             <amq:policyMap>
                 <amq:policyEntries>
                     <!-- Support priority handling of messages -->
+                    <!-- This will not work till we use activemq 5.4+ -->
                     <!-- http://activemq.apache.org/how-can-i-support-priority-queues.html -->
                     <!-- 
                     <amq:policyEntry queue=">" prioritizedMessages="true"/>
@@ -149,24 +150,18 @@
 
     <amq:connectionFactory id="amqConnectionFactory" brokerURL="vm://james?create=false" />
 
-    <!-- CachingConnectionFactory Definition, sessionCacheSize property is the number of sessions to cache -->
-    <bean id="jmsConnectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
-        <constructor-arg ref="amqConnectionFactory" />
-        <property name="sessionCacheSize" value="100" />
+    <bean id="jmsConnectionFactory"  class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
+        <property name="connectionFactory" ref="amqConnectionFactory"/>
     </bean>
 
+
     <!-- setup spring jms TX manager -->
     <bean id="jmsTransactionManager" class="org.springframework.jms.connection.JmsTransactionManager">
         <property name="connectionFactory" ref="jmsConnectionFactory"/>
     </bean>
 
-    <bean id="mailQueueFactory" class="org.apache.james.queue.activemq.ActiveMQMailQueueFactory" depends-on="broker">
-        <!-- Allow to specify if BlobMessage or BytesMessage should be used for storing the Mail in the queue-->
-        <!-- Please have a look at the javadocs of ActiveMQMailQueue for more information -->
-        <!-- By default only BytesMessage is used -->
-        <property name="sizeTreshold" value="-1"/>
-    </bean>
-   
+    <!-- Use JMSMailQueueFactory till activemq 5.5.0 is released -->
+    <bean id="mailQueueFactory" class="org.apache.james.queue.jms.JMSMailQueueFactory" depends-on="broker"/>
         
     <!-- Build the camelroute from the spoolmanager.xml -->
     <bean id="mailProcessor" name="processorRoute" class="org.apache.james.mailetcontainer.camel.CamelMailProcessorList"/>



---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org