JAMES-1877 Tests then refactoring for RemoteDelivery

Project: http://git-wip-us.apache.org/repos/asf/james-project/repo
Commit: http://git-wip-us.apache.org/repos/asf/james-project/commit/6774b877
Tree: http://git-wip-us.apache.org/repos/asf/james-project/tree/6774b877
Diff: http://git-wip-us.apache.org/repos/asf/james-project/diff/6774b877

Branch: refs/heads/master
Commit: 6774b8775e8ce5d81dc72b4c15dc9109f3300e67
Parents: 4a5a4ba
Author: Benoit Tellier <btell...@linagora.com>
Authored: Thu Dec 1 11:05:13 2016 +0700
Committer: Benoit Tellier <btell...@linagora.com>
Committed: Tue Jan 10 15:12:39 2017 +0700

----------------------------------------------------------------------
 mailet/base/pom.xml                             |  11 +
 .../org/apache/mailet/base/test/FakeMail.java   |  56 +++++
 .../apache/mailet/base/test/FakeMailTest.java   |  41 ++++
 .../transport/mailets/ToProcessorTest.java      |  12 +-
 .../james/transport/mailets/RemoteDelivery.java | 143 ++++++-------
 .../remoteDelivery/RemoteDeliveryTest.java      | 208 +++++++++++++++++++
 6 files changed, 390 insertions(+), 81 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/6774b877/mailet/base/pom.xml
----------------------------------------------------------------------
diff --git a/mailet/base/pom.xml b/mailet/base/pom.xml
index 0c47808..fdec517 100644
--- a/mailet/base/pom.xml
+++ b/mailet/base/pom.xml
@@ -71,6 +71,17 @@
             <scope>test</scope>
         </dependency>
         <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-core</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>nl.jqno.equalsverifier</groupId>
+            <artifactId>equalsverifier</artifactId>
+            <version>1.7.5</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
             <groupId>org.assertj</groupId>
             <artifactId>assertj-core</artifactId>
             <scope>test</scope>

http://git-wip-us.apache.org/repos/asf/james-project/blob/6774b877/mailet/base/src/test/java/org/apache/mailet/base/test/FakeMail.java
----------------------------------------------------------------------
diff --git 
a/mailet/base/src/test/java/org/apache/mailet/base/test/FakeMail.java 
b/mailet/base/src/test/java/org/apache/mailet/base/test/FakeMail.java
index acccec3..661882a 100644
--- a/mailet/base/src/test/java/org/apache/mailet/base/test/FakeMail.java
+++ b/mailet/base/src/test/java/org/apache/mailet/base/test/FakeMail.java
@@ -38,9 +38,12 @@ import javax.mail.internet.MimeMessage;
 import org.apache.mailet.Mail;
 import org.apache.mailet.MailAddress;
 
+import com.google.common.base.MoreObjects;
+import com.google.common.base.Objects;
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 
@@ -176,6 +179,14 @@ public class FakeMail implements Mail {
         return FakeMail.builder().build();
     }
 
+    private static Map<String, Serializable> attributes(Mail mail) {
+        ImmutableMap.Builder<String, Serializable> builder = 
ImmutableMap.builder();
+        for (String attributeName: 
ImmutableList.copyOf(mail.getAttributeNames())) {
+            builder.put(attributeName, mail.getAttribute(attributeName));
+        }
+        return builder.build();
+    }
+
     private MimeMessage msg;
     private Collection<MailAddress> recipients;
     private String name;
@@ -201,6 +212,11 @@ public class FakeMail implements Mail {
         this.remoteAddr = remoteAddr;
     }
 
+    public FakeMail(Mail mail) throws MessagingException {
+        this(mail.getMessage(), Lists.newArrayList(mail.getRecipients()), 
mail.getName(), mail.getSender(), mail.getState(), mail.getErrorMessage(),
+            mail.getLastUpdated(), attributes(mail), mail.getMessageSize(), 
mail.getRemoteAddr());
+    }
+
     @Override
     public String getName() {
         return name;
@@ -322,4 +338,44 @@ public class FakeMail implements Mail {
     public void setMessageSize(long size) {
         this.size = size;
     }
+
+    @Override
+    public final boolean equals(Object o) {
+        if (o instanceof FakeMail) {
+            FakeMail that = (FakeMail) o;
+
+            return Objects.equal(this.size, that.size)
+                && Objects.equal(this.msg, that.msg)
+                && Objects.equal(this.recipients, that.recipients)
+                && Objects.equal(this.name, that.name)
+                && Objects.equal(this.sender, that.sender)
+                && Objects.equal(this.state, that.state)
+                && Objects.equal(this.errorMessage, that.errorMessage)
+                && Objects.equal(this.lastUpdated, that.lastUpdated)
+                && Objects.equal(this.attributes, that.attributes)
+                && Objects.equal(this.remoteAddr, that.remoteAddr);
+        }
+        return false;
+    }
+
+    @Override
+    public final int hashCode() {
+        return Objects.hashCode(msg, name, sender, recipients, state, 
errorMessage, lastUpdated, attributes, size, recipients, remoteAddr);
+    }
+
+    @Override
+    public String toString() {
+        return MoreObjects.toStringHelper(this)
+            .add("msg", msg)
+            .add("recipients", recipients)
+            .add("name", name)
+            .add("sender", sender)
+            .add("state", state)
+            .add("errorMessage", errorMessage)
+            .add("lastUpdated", lastUpdated)
+            .add("attributes", attributes)
+            .add("size", size)
+            .add("remoteAddr", remoteAddr)
+            .toString();
+    }
 }

http://git-wip-us.apache.org/repos/asf/james-project/blob/6774b877/mailet/base/src/test/java/org/apache/mailet/base/test/FakeMailTest.java
----------------------------------------------------------------------
diff --git 
a/mailet/base/src/test/java/org/apache/mailet/base/test/FakeMailTest.java 
b/mailet/base/src/test/java/org/apache/mailet/base/test/FakeMailTest.java
new file mode 100644
index 0000000..fc0c03c
--- /dev/null
+++ b/mailet/base/src/test/java/org/apache/mailet/base/test/FakeMailTest.java
@@ -0,0 +1,41 @@
+/****************************************************************
+ * 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.mailet.base.test;
+
+import static org.mockito.Mockito.mock;
+
+import javax.mail.internet.MimeMessage;
+
+import org.junit.Test;
+
+import nl.jqno.equalsverifier.EqualsVerifier;
+import nl.jqno.equalsverifier.Warning;
+
+public class FakeMailTest {
+
+    @Test
+    public void beanShouldRespectBeanContract() {
+        EqualsVerifier.forClass(FakeMail.class)
+            .suppress(Warning.NONFINAL_FIELDS)
+            .withPrefabValues(MimeMessage.class, mock(MimeMessage.class), 
mock(MimeMessage.class))
+            .verify();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/james-project/blob/6774b877/mailet/standard/src/test/java/org/apache/james/transport/mailets/ToProcessorTest.java
----------------------------------------------------------------------
diff --git 
a/mailet/standard/src/test/java/org/apache/james/transport/mailets/ToProcessorTest.java
 
b/mailet/standard/src/test/java/org/apache/james/transport/mailets/ToProcessorTest.java
index 3db12fd..35175a5 100644
--- 
a/mailet/standard/src/test/java/org/apache/james/transport/mailets/ToProcessorTest.java
+++ 
b/mailet/standard/src/test/java/org/apache/james/transport/mailets/ToProcessorTest.java
@@ -21,6 +21,7 @@
 package org.apache.james.transport.mailets;
 
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Matchers.anyString;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 
@@ -30,6 +31,7 @@ import org.apache.mailet.Mail;
 import org.apache.mailet.MailAddress;
 import org.apache.mailet.Mailet;
 import org.apache.mailet.MailetException;
+import org.apache.mailet.base.MailAddressFixture;
 import org.apache.mailet.base.test.FakeMail;
 import org.apache.mailet.base.test.FakeMailContext;
 import org.apache.mailet.base.test.FakeMailetConfig;
@@ -143,13 +145,13 @@ public class ToProcessorTest {
                 .build();
         mailet.init(mailetConfig);
 
-        Mail mail = FakeMail.builder()
-                .recipients(new MailAddress("t...@james.apache.org"), new 
MailAddress("te...@james.apache.org"))
-                .build();
         String initialErrorMessage = "first";
-        mail.setErrorMessage(initialErrorMessage);
+        Mail mail = FakeMail.builder()
+            .recipients(MailAddressFixture.ANY_AT_JAMES, 
MailAddressFixture.OTHER_AT_JAMES)
+            .errorMessage(initialErrorMessage)
+            .build();
         mailet.service(mail);
 
-        verify(logger).info("Sending mail " + mail +" to error");
+        verify(logger).info(anyString());
     }
 }

http://git-wip-us.apache.org/repos/asf/james-project/blob/6774b877/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/RemoteDelivery.java
----------------------------------------------------------------------
diff --git 
a/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/RemoteDelivery.java
 
b/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/RemoteDelivery.java
index e7db2c8..8a40298 100644
--- 
a/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/RemoteDelivery.java
+++ 
b/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/RemoteDelivery.java
@@ -20,9 +20,7 @@
 package org.apache.james.transport.mailets;
 
 import java.net.UnknownHostException;
-import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Hashtable;
 import java.util.Locale;
 import java.util.Map;
 import java.util.Vector;
@@ -47,6 +45,8 @@ import org.apache.mailet.MailAddress;
 import org.apache.mailet.base.GenericMailet;
 import org.slf4j.Logger;
 
+import com.google.common.collect.HashMultimap;
+
 /**
  * <p>The RemoteDelivery mailet delivers messages to a remote SMTP server able 
to deliver or forward messages to their final
  * destination.
@@ -120,6 +120,8 @@ import org.slf4j.Logger;
 public class RemoteDelivery extends GenericMailet {
 
     private static final String OUTGOING_MAILS = "outgoingMails";
+    private static final boolean DEFAULT_START_THREADS = true;
+    public static final String NAME_JUNCTION = "-to-";
 
     private final DNSService dnsServer;
     private final DomainList domainList;
@@ -127,6 +129,7 @@ public class RemoteDelivery extends GenericMailet {
     private final Metric outgoingMailsMetric;
     private final Collection<Thread> workersThreads;
     private final VolatileIsDestroyed volatileIsDestroyed;
+    private final boolean startThreads;
 
     private MailQueue queue;
     private Logger logger;
@@ -134,31 +137,32 @@ public class RemoteDelivery extends GenericMailet {
 
     @Inject
     public RemoteDelivery(DNSService dnsServer, DomainList domainList, 
MailQueueFactory queueFactory, MetricFactory metricFactory) {
+        this(dnsServer, domainList, queueFactory, metricFactory, 
DEFAULT_START_THREADS);
+    }
+
+    public RemoteDelivery(DNSService dnsServer, DomainList domainList, 
MailQueueFactory queueFactory, MetricFactory metricFactory, boolean 
startThreads) {
         this.dnsServer = dnsServer;
         this.domainList = domainList;
         this.queueFactory = queueFactory;
         this.outgoingMailsMetric = metricFactory.generate(OUTGOING_MAILS);
-        this.workersThreads = new Vector<Thread>();
         this.volatileIsDestroyed = new VolatileIsDestroyed();
+        this.workersThreads = new Vector<Thread>();
+        this.startThreads = startThreads;
     }
 
-    /**
-     * Initializes all arguments based on configuration values specified in the
-     * James configuration file.
-     *
-     * @throws MessagingException on failure to initialize attributes.
-     */
     public void init() throws MessagingException {
         logger = getMailetContext().getLogger();
         configuration = new RemoteDeliveryConfiguration(getMailetConfig(), 
domainList);
         queue = queueFactory.getQueue(configuration.getOutGoingQueueName());
-        initDeliveryThreads();
         try {
             if (configuration.isBindUsed())
                 
RemoteDeliverySocketFactory.setBindAdress(configuration.getBindAddress());
         } catch (UnknownHostException e) {
             log("Invalid bind setting (" + configuration.getBindAddress() + 
"): " + e.toString());
         }
+        if (startThreads) {
+            initDeliveryThreads();
+        }
     }
 
     private void initDeliveryThreads() {
@@ -183,80 +187,65 @@ public class RemoteDelivery extends GenericMailet {
         return "RemoteDelivery Mailet";
     }
 
-    /**
-     * For this message, we take the list of recipients, organize these into
-     * distinct servers, and duplicate the message for each of these servers,
-     * and then call the deliver (messagecontainer) method for each
-     * server-specific messagecontainer ... that will handle storing it in the
-     * outgoing queue if needed.
-     *
-     * @param mail org.apache.mailet.Mail
-     */
     @Override
     public void service(Mail mail) throws MessagingException {
-        // Do I want to give the internal key, or the message's Message ID
         if (configuration.isDebug()) {
             log("Remotely delivering mail " + mail.getName());
         }
-        Collection<MailAddress> recipients = mail.getRecipients();
-
         if (configuration.isUsePriority()) {
-
-            // Use highest prio for new emails. See JAMES-1311
             mail.setAttribute(MailPrioritySupport.MAIL_PRIORITY, 
MailPrioritySupport.HIGH_PRIORITY);
         }
-        if (configuration.getGatewayServer() == null) {
-            // Must first organize the recipients into distinct servers (name
-            // made case insensitive)
-            Hashtable<String, Collection<MailAddress>> targets = new 
Hashtable<String, Collection<MailAddress>>();
-            for (MailAddress target : recipients) {
-                String targetServer = 
target.getDomain().toLowerCase(Locale.US);
-                Collection<MailAddress> temp = targets.get(targetServer);
-                if (temp == null) {
-                    temp = new ArrayList<MailAddress>();
-                    targets.put(targetServer, temp);
-                }
-                temp.add(target);
+        if (!mail.getRecipients().isEmpty()) {
+            if (configuration.getGatewayServer().isEmpty()) {
+                serviceNoGateway(mail);
+            } else {
+                serviceWithGateway(mail);
             }
+        } else {
+            log("Mail " + mail.getName() + " from " + mail.getSender() + " has 
no recipients and can not be remotely delivered");
+        }
+        mail.setState(Mail.GHOST);
+    }
 
-            // We have the recipients organized into distinct servers... put
-            // them into the
-            // delivery store organized like this... this is ultra inefficient 
I
-            // think...
+    private void serviceWithGateway(Mail mail) {
+        if (configuration.isDebug()) {
+            log("Sending mail to " + mail.getRecipients() + " via " + 
configuration.getGatewayServer());
+        }
+        try {
+            queue.enQueue(mail);
+        } catch (MailQueueException e) {
+            log("Unable to queue mail " + mail.getName() + " for recipients + 
" + mail.getRecipients().toString(), e);
+        }
+    }
 
-            // Store the new message containers, organized by server, in the
-            // outgoing mail repository
-            String name = mail.getName();
-            for (Map.Entry<String, Collection<MailAddress>> entry : 
targets.entrySet()) {
-                if (configuration.isDebug()) {
-                    String logMessageBuffer = "Sending mail to " + 
entry.getValue() + " on host " + entry.getKey();
-                    log(logMessageBuffer);
-                }
-                mail.setRecipients(entry.getValue());
-                String nameBuffer = name + "-to-" + entry.getKey();
-                mail.setName(nameBuffer);
-                try {
-                    queue.enQueue(mail);
-                } catch (MailQueueException e) {
-                    log("Unable to queue mail " + mail.getName() + " for 
recipients + " + mail.getRecipients().toString(), e);
-                }
-            }
-        } else {
-            // Store the mail unaltered for processing by the gateway server(s)
-            if (configuration.isDebug()) {
-                String logMessageBuffer = "Sending mail to " + 
mail.getRecipients() + " via " + configuration.getGatewayServer();
-                log(logMessageBuffer);
-            }
+    private void serviceNoGateway(Mail mail) {
+        String mailName = mail.getName();
+        Map<String, Collection<MailAddress>> targets = 
groupByServer(mail.getRecipients());
+        for (Map.Entry<String, Collection<MailAddress>> entry : 
targets.entrySet()) {
+            serviceSingleServer(mail, mailName, entry);
+        }
+    }
 
-            // Set it to try to deliver (in a separate thread) immediately
-            // (triggered by storage)
-            try {
-                queue.enQueue(mail);
-            } catch (MailQueueException e) {
-                log("Unable to queue mail " + mail.getName() + " for 
recipients + " + mail.getRecipients().toString(), e);
-            }
+    private void serviceSingleServer(Mail mail, String originalName, 
Map.Entry<String, Collection<MailAddress>> entry) {
+        if (configuration.isDebug()) {
+            log("Sending mail to " + entry.getValue() + " on host " + 
entry.getKey());
+        }
+        mail.setRecipients(entry.getValue());
+        mail.setName(originalName + NAME_JUNCTION + entry.getKey());
+        try {
+            queue.enQueue(mail);
+        } catch (MailQueueException e) {
+            log("Unable to queue mail " + mail.getName() + " for recipients + 
" + mail.getRecipients().toString(), e);
         }
-        mail.setState(Mail.GHOST);
+    }
+
+    private Map<String, Collection<MailAddress>> 
groupByServer(Collection<MailAddress> recipients) {
+        // Must first organize the recipients into distinct servers (name made 
case insensitive)
+        HashMultimap<String, MailAddress> groupByServerMultimap = 
HashMultimap.create();
+        for (MailAddress recipient : recipients) {
+            
groupByServerMultimap.put(recipient.getDomain().toLowerCase(Locale.US), 
recipient);
+        }
+        return groupByServerMultimap.asMap();
     }
 
     /**
@@ -266,12 +255,14 @@ public class RemoteDelivery extends GenericMailet {
      */
     @Override
     public synchronized void destroy() {
-        volatileIsDestroyed.markAsDestroyed();
-        // Wake up all threads from waiting for an accept
-        for (Thread t : workersThreads) {
-            t.interrupt();
+        if (startThreads) {
+            volatileIsDestroyed.markAsDestroyed();
+            // Wake up all threads from waiting for an accept
+            for (Thread t : workersThreads) {
+                t.interrupt();
+            }
+            notifyAll();
         }
-        notifyAll();
     }
 
 }

http://git-wip-us.apache.org/repos/asf/james-project/blob/6774b877/server/mailet/mailets/src/test/java/org/apache/james/transport/mailets/remoteDelivery/RemoteDeliveryTest.java
----------------------------------------------------------------------
diff --git 
a/server/mailet/mailets/src/test/java/org/apache/james/transport/mailets/remoteDelivery/RemoteDeliveryTest.java
 
b/server/mailet/mailets/src/test/java/org/apache/james/transport/mailets/remoteDelivery/RemoteDeliveryTest.java
new file mode 100644
index 0000000..2012a2e
--- /dev/null
+++ 
b/server/mailet/mailets/src/test/java/org/apache/james/transport/mailets/remoteDelivery/RemoteDeliveryTest.java
@@ -0,0 +1,208 @@
+/****************************************************************
+ * 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.transport.mailets.remoteDelivery;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import javax.mail.MessagingException;
+
+import org.apache.commons.lang.NotImplementedException;
+import org.apache.james.dnsservice.api.DNSService;
+import org.apache.james.domainlist.api.DomainList;
+import org.apache.james.metrics.api.MetricFactory;
+import org.apache.james.queue.api.MailPrioritySupport;
+import org.apache.james.queue.api.MailQueue;
+import org.apache.james.queue.api.MailQueueFactory;
+import org.apache.james.transport.mailets.RemoteDelivery;
+import org.apache.mailet.Mail;
+import org.apache.mailet.base.MailAddressFixture;
+import org.apache.mailet.base.test.FakeMail;
+import org.apache.mailet.base.test.FakeMailetConfig;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+public class RemoteDeliveryTest {
+
+    public static final String MAIL_NAME = "mail_name";
+
+    private static class FakeMailQueue implements MailQueue {
+        private final List<Mail> enqueuedMail;
+
+        private FakeMailQueue() {
+            this.enqueuedMail = Lists.newArrayList();
+        }
+
+        @Override
+        public void enQueue(Mail mail, long delay, TimeUnit unit) throws 
MailQueueException {
+            enQueue(mail);
+        }
+
+        @Override
+        public void enQueue(Mail mail) throws MailQueueException {
+            try {
+                enqueuedMail.add(new FakeMail(mail));
+            } catch (MessagingException e) {
+                throw Throwables.propagate(e);
+            }
+        }
+
+        @Override
+        public MailQueueItem deQueue() throws MailQueueException, 
InterruptedException {
+            throw new NotImplementedException();
+        }
+
+        public List<Mail> getEnqueuedMail() {
+            return ImmutableList.copyOf(enqueuedMail);
+        }
+    }
+
+    public static final boolean DONT_START_THREADS = false;
+    private RemoteDelivery remoteDelivery;
+    private FakeMailQueue mailQueue;
+
+    @Before
+    public void setUp() {
+        MailQueueFactory queueFactory = mock(MailQueueFactory.class);
+        mailQueue = new FakeMailQueue();
+        
when(queueFactory.getQueue(RemoteDeliveryConfiguration.OUTGOING)).thenReturn(mailQueue);
+        remoteDelivery = new RemoteDelivery(mock(DNSService.class), 
mock(DomainList.class), queueFactory, mock(MetricFactory.class), 
DONT_START_THREADS);
+    }
+
+    @Test
+    public void remoteDeliveryShouldAddEmailToSpool() throws Exception{
+        remoteDelivery.init(FakeMailetConfig.builder()
+            .setProperty(RemoteDeliveryConfiguration.DELIVERY_THREADS, "1")
+            .build());
+
+        Mail mail = 
FakeMail.builder().name(MAIL_NAME).recipients(MailAddressFixture.ANY_AT_JAMES).build();
+        remoteDelivery.service(mail);
+
+        assertThat(mailQueue.getEnqueuedMail()).containsOnly(FakeMail.builder()
+            .name(MAIL_NAME + RemoteDelivery.NAME_JUNCTION + 
MailAddressFixture.JAMES_APACHE_ORG)
+            .recipient(MailAddressFixture.ANY_AT_JAMES)
+            .build());
+    }
+
+    @Test
+    public void remoteDeliveryShouldSplitMailsByServerWhenNoGateway() throws 
Exception{
+        remoteDelivery.init(FakeMailetConfig.builder()
+            .setProperty(RemoteDeliveryConfiguration.DELIVERY_THREADS, "1")
+            .build());
+
+        Mail mail = FakeMail.builder()
+            .name(MAIL_NAME)
+            .recipients(MailAddressFixture.ANY_AT_JAMES, 
MailAddressFixture.ANY_AT_JAMES2, MailAddressFixture.OTHER_AT_JAMES)
+            .build();
+        remoteDelivery.service(mail);
+
+        assertThat(mailQueue.getEnqueuedMail()).containsOnly(
+            FakeMail.builder()
+                .name(MAIL_NAME + RemoteDelivery.NAME_JUNCTION + 
MailAddressFixture.JAMES_APACHE_ORG)
+                .recipients(MailAddressFixture.ANY_AT_JAMES, 
MailAddressFixture.OTHER_AT_JAMES)
+                .build(),
+            FakeMail.builder()
+                .name(MAIL_NAME + RemoteDelivery.NAME_JUNCTION + 
MailAddressFixture.JAMES2_APACHE_ORG)
+                .recipients(MailAddressFixture.ANY_AT_JAMES2)
+                .build());
+    }
+
+    @Test
+    public void remoteDeliveryShouldNotSplitMailsByServerWhenGateway() throws 
Exception{
+        remoteDelivery.init(FakeMailetConfig.builder()
+            .setProperty(RemoteDeliveryConfiguration.DELIVERY_THREADS, "1")
+            .setProperty(RemoteDeliveryConfiguration.GATEWAY, 
MailAddressFixture.JAMES_LOCAL)
+            .build());
+
+        Mail mail = FakeMail.builder()
+            .name(MAIL_NAME)
+            .recipients(MailAddressFixture.ANY_AT_JAMES, 
MailAddressFixture.ANY_AT_JAMES2, MailAddressFixture.OTHER_AT_JAMES)
+            .build();
+        remoteDelivery.service(mail);
+
+        assertThat(mailQueue.getEnqueuedMail()).containsOnly(
+            FakeMail.builder()
+                .name(MAIL_NAME)
+                .recipients(MailAddressFixture.ANY_AT_JAMES, 
MailAddressFixture.ANY_AT_JAMES2, MailAddressFixture.OTHER_AT_JAMES)
+                .build());
+    }
+
+    @Test
+    public void remoteDeliveryShouldGhostMails() throws Exception{
+        remoteDelivery.init(FakeMailetConfig.builder()
+            .setProperty(RemoteDeliveryConfiguration.DELIVERY_THREADS, "1")
+            .build());
+
+        Mail mail = 
FakeMail.builder().name(MAIL_NAME).recipients(MailAddressFixture.ANY_AT_JAMES).build();
+        remoteDelivery.service(mail);
+
+        assertThat(mail.getState()).isEqualTo(Mail.GHOST);
+    }
+
+    @Test
+    public void remoteDeliveryShouldAddPriorityIfSpecified() throws Exception{
+        remoteDelivery.init(FakeMailetConfig.builder()
+            .setProperty(RemoteDeliveryConfiguration.DELIVERY_THREADS, "1")
+            .setProperty(RemoteDeliveryConfiguration.USE_PRIORITY, "true")
+            .build());
+
+        Mail mail = 
FakeMail.builder().name(MAIL_NAME).recipients(MailAddressFixture.ANY_AT_JAMES).build();
+        remoteDelivery.service(mail);
+
+        assertThat(mailQueue.getEnqueuedMail()).containsOnly(FakeMail.builder()
+            .name(MAIL_NAME + RemoteDelivery.NAME_JUNCTION + 
MailAddressFixture.JAMES_APACHE_ORG)
+            .attribute(MailPrioritySupport.MAIL_PRIORITY, 
MailPrioritySupport.HIGH_PRIORITY)
+            .recipient(MailAddressFixture.ANY_AT_JAMES)
+            .build());
+    }
+
+    @Test
+    public void remoteDeliveryShouldNotForwardMailsWithNoRecipients() throws 
Exception{
+        remoteDelivery.init(FakeMailetConfig.builder()
+            .setProperty(RemoteDeliveryConfiguration.DELIVERY_THREADS, "1")
+            .build());
+
+        Mail mail = FakeMail.builder().name(MAIL_NAME).build();
+        remoteDelivery.service(mail);
+
+        assertThat(mailQueue.getEnqueuedMail()).isEmpty();
+    }
+
+    @Test
+    public void 
remoteDeliveryShouldNotForwardMailsWithNoRecipientsWithGateway() throws 
Exception{
+        remoteDelivery.init(FakeMailetConfig.builder()
+            .setProperty(RemoteDeliveryConfiguration.DELIVERY_THREADS, "1")
+            .setProperty(RemoteDeliveryConfiguration.GATEWAY, 
MailAddressFixture.JAMES_LOCAL)
+            .build());
+
+        Mail mail = FakeMail.builder().name(MAIL_NAME).build();
+        remoteDelivery.service(mail);
+
+        assertThat(mailQueue.getEnqueuedMail()).isEmpty();
+    }
+}


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

Reply via email to