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 bt...@apache.org on 2018/08/03 08:52:14 UTC

[01/20] james-project git commit: JAMES-2470 SpamAssassin can be static in mailet integration tests

Repository: james-project
Updated Branches:
  refs/heads/master c3715e708 -> d3f6f1ada


JAMES-2470 SpamAssassin can be static in mailet integration tests

No feedback is tested there hence SPamAssassin container is stateless.

Gain of 30s on that test


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

Branch: refs/heads/master
Commit: dffc54e10147e7c3469946cfa61095887cbfc52d
Parents: c3715e7
Author: Benoit Tellier <bt...@linagora.com>
Authored: Fri Aug 3 11:29:50 2018 +0700
Committer: Benoit Tellier <bt...@linagora.com>
Committed: Fri Aug 3 11:29:50 2018 +0700

----------------------------------------------------------------------
 .../org/apache/james/transport/mailets/SpamAssassinTest.java    | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/dffc54e1/server/mailet/integration-testing/src/test/java/org/apache/james/transport/mailets/SpamAssassinTest.java
----------------------------------------------------------------------
diff --git a/server/mailet/integration-testing/src/test/java/org/apache/james/transport/mailets/SpamAssassinTest.java b/server/mailet/integration-testing/src/test/java/org/apache/james/transport/mailets/SpamAssassinTest.java
index 1f33b14..ac3887e 100644
--- a/server/mailet/integration-testing/src/test/java/org/apache/james/transport/mailets/SpamAssassinTest.java
+++ b/server/mailet/integration-testing/src/test/java/org/apache/james/transport/mailets/SpamAssassinTest.java
@@ -48,6 +48,7 @@ import org.apache.james.utils.SMTPMessageSender;
 import org.apache.mailet.base.test.FakeMail;
 import org.junit.After;
 import org.junit.Before;
+import org.junit.ClassRule;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.TemporaryFolder;
@@ -56,8 +57,8 @@ import org.testcontainers.containers.wait.strategy.HostPortWaitStrategy;
 public class SpamAssassinTest {
     private static final String SPAM_CONTENT = "XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X";
 
-    @Rule
-    public SwarmGenericContainer spamAssassinContainer = new SwarmGenericContainer(Images.SPAMASSASSIN)
+    @ClassRule
+    public static SwarmGenericContainer spamAssassinContainer = new SwarmGenericContainer(Images.SPAMASSASSIN)
         .withExposedPorts(783)
         .withAffinityToContainer()
         .waitingFor(new HostPortWaitStrategy());


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


[06/20] james-project git commit: JAMES-2506 Remove org.easymock

Posted by bt...@apache.org.
JAMES-2506 Remove org.easymock


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

Branch: refs/heads/master
Commit: 47968eaf99ae10efb622a0b2e320d9d9b8880d39
Parents: de033f3
Author: duc <dt...@linagora.com>
Authored: Tue Jul 31 11:40:12 2018 +0700
Committer: Benoit Tellier <bt...@linagora.com>
Committed: Fri Aug 3 15:51:21 2018 +0700

----------------------------------------------------------------------
 mailbox/elasticsearch/pom.xml                   |   6 -
 .../parser/SearchCommandParserCharsetTest.java  |   2 +-
 server/container/cli/pom.xml                    |   5 +-
 .../org/apache/james/cli/ServerCmdTest.java     | 778 ++++++-------------
 4 files changed, 248 insertions(+), 543 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/47968eaf/mailbox/elasticsearch/pom.xml
----------------------------------------------------------------------
diff --git a/mailbox/elasticsearch/pom.xml b/mailbox/elasticsearch/pom.xml
index 193e472..03c53fa 100644
--- a/mailbox/elasticsearch/pom.xml
+++ b/mailbox/elasticsearch/pom.xml
@@ -144,12 +144,6 @@
             <scope>test</scope>
         </dependency>
         <dependency>
-            <groupId>org.easymock</groupId>
-            <artifactId>easymock</artifactId>
-            <version>3.3.1</version>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
             <groupId>org.elasticsearch</groupId>
             <artifactId>elasticsearch</artifactId>
             <version>2.2.1</version>

http://git-wip-us.apache.org/repos/asf/james-project/blob/47968eaf/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserCharsetTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserCharsetTest.java b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserCharsetTest.java
index 250721a..bc6d203 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserCharsetTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserCharsetTest.java
@@ -85,7 +85,7 @@ public class SearchCommandParserCharsetTest {
     }
 
     @Test
-    public void testBadCharsetMockito() throws Exception {
+    public void testBadCharset() throws Exception {
         ImapRequestLineReader reader = new ImapRequestStreamLineReader(
                 new ByteArrayInputStream("CHARSET BOGUS ".getBytes("US-ASCII")),
                 new ByteArrayOutputStream());

http://git-wip-us.apache.org/repos/asf/james-project/blob/47968eaf/server/container/cli/pom.xml
----------------------------------------------------------------------
diff --git a/server/container/cli/pom.xml b/server/container/cli/pom.xml
index 4018412..4ed2792 100644
--- a/server/container/cli/pom.xml
+++ b/server/container/cli/pom.xml
@@ -72,9 +72,8 @@
             <scope>test</scope>
         </dependency>
         <dependency>
-            <groupId>org.easymock</groupId>
-            <artifactId>easymock</artifactId>
-            <version>3.3.1</version>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-core</artifactId>
             <scope>test</scope>
         </dependency>
     </dependencies>

http://git-wip-us.apache.org/repos/asf/james-project/blob/47968eaf/server/container/cli/src/test/java/org/apache/james/cli/ServerCmdTest.java
----------------------------------------------------------------------
diff --git a/server/container/cli/src/test/java/org/apache/james/cli/ServerCmdTest.java b/server/container/cli/src/test/java/org/apache/james/cli/ServerCmdTest.java
index 0724cf1..c46c771 100644
--- a/server/container/cli/src/test/java/org/apache/james/cli/ServerCmdTest.java
+++ b/server/container/cli/src/test/java/org/apache/james/cli/ServerCmdTest.java
@@ -21,9 +21,9 @@ package org.apache.james.cli;
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.easymock.EasyMock.createControl;
-import static org.easymock.EasyMock.expect;
-import static org.easymock.EasyMock.expectLastCall;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -44,7 +44,6 @@ import org.apache.james.mailbox.store.probe.QuotaProbe;
 import org.apache.james.mailbox.store.probe.SieveProbe;
 import org.apache.james.probe.DataProbe;
 import org.apache.james.rrt.lib.MappingsImpl;
-import org.easymock.IMocksControl;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -52,8 +51,7 @@ import com.google.common.collect.ImmutableList;
 
 public class ServerCmdTest {
 
-    public static final String ADDITIONAL_ARGUMENT = "additionalArgument";
-    private IMocksControl control;
+    private static final String ADDITIONAL_ARGUMENT = "additionalArgument";
 
     private DataProbe dataProbe;
     private MailboxProbe mailboxProbe;
@@ -64,11 +62,10 @@ public class ServerCmdTest {
 
     @Before
     public void setup() {
-        control = createControl();
-        dataProbe = control.createMock(DataProbe.class);
-        mailboxProbe = control.createMock(MailboxProbe.class);
-        quotaProbe = control.createMock(QuotaProbe.class);
-        sieveProbe = control.createMock(SieveProbe.class);
+        dataProbe = mock(DataProbe.class);
+        mailboxProbe = mock(MailboxProbe.class);
+        quotaProbe = mock(QuotaProbe.class);
+        sieveProbe = mock(SieveProbe.class);
         testee = new ServerCmd(dataProbe, mailboxProbe, quotaProbe, sieveProbe);
     }
 
@@ -78,12 +75,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.ADDDOMAIN.getCommand(), domain};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        dataProbe.addDomain(domain);
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(dataProbe).addDomain(domain);
     }
 
     @Test
@@ -92,12 +86,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REMOVEDOMAIN.getCommand(), domain};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        dataProbe.removeDomain(domain);
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(dataProbe).removeDomain(domain);
     }
 
     @Test
@@ -106,11 +97,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.CONTAINSDOMAIN.getCommand(), domain};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        expect(dataProbe.containsDomain(domain)).andReturn(true);
+        when(dataProbe.containsDomain(domain)).thenReturn(true);
 
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
     }
 
     @Test
@@ -118,11 +107,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.LISTDOMAINS.getCommand()};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        expect(dataProbe.listDomains()).andReturn(ImmutableList.<String>of());
+        when(dataProbe.listDomains()).thenReturn(ImmutableList.of());
 
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
     }
 
     @Test
@@ -132,12 +119,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.ADDUSER.getCommand(), user, password};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        dataProbe.addUser(user, password);
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(dataProbe).addUser(user, password);
     }
 
     @Test
@@ -146,12 +130,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REMOVEUSER.getCommand(), user};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        dataProbe.removeUser(user);
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(dataProbe).removeUser(user);
     }
 
     @Test
@@ -160,11 +141,9 @@ public class ServerCmdTest {
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
         String[] res = {};
-        expect(dataProbe.listUsers()).andReturn(res);
+        when(dataProbe.listUsers()).thenReturn(res);
 
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
     }
 
     @Test
@@ -172,11 +151,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.LISTMAPPINGS.getCommand()};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        expect(dataProbe.listMappings()).andReturn(new HashMap<>());
+        when(dataProbe.listMappings()).thenReturn(new HashMap<>());
 
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
     }
 
     @Test
@@ -186,11 +163,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.LISTUSERDOMAINMAPPINGS.getCommand(), user, domain};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        expect(dataProbe.listUserDomainMappings(user, domain)).andReturn(MappingsImpl.empty());
+        when(dataProbe.listUserDomainMappings(user, domain)).thenReturn(MappingsImpl.empty());
 
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
     }
 
     @Test
@@ -201,12 +176,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.ADDADDRESSMAPPING.getCommand(), user, domain, address};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        dataProbe.addAddressMapping(user, domain, address);
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(dataProbe).addAddressMapping(user, domain, address);
     }
 
     @Test
@@ -217,12 +189,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REMOVEADDRESSMAPPING.getCommand(), user, domain, address};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        dataProbe.removeAddressMapping(user, domain, address);
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(dataProbe).removeAddressMapping(user, domain, address);
     }
 
     @Test
@@ -233,12 +202,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.ADDREGEXMAPPING.getCommand(), user, domain, regex};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        dataProbe.addRegexMapping(user, domain, regex);
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(dataProbe).addRegexMapping(user, domain, regex);
     }
 
     @Test
@@ -249,12 +215,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REMOVEREGEXMAPPING.getCommand(), user, domain, regex};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        dataProbe.removeRegexMapping(user, domain, regex);
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(dataProbe).removeRegexMapping(user, domain, regex);
     }
 
     @Test
@@ -264,12 +227,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.SETPASSWORD.getCommand(), user, password};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        dataProbe.setPassword(user, password);
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(dataProbe).setPassword(user, password);
     }
 
     @Test
@@ -279,12 +239,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.COPYMAILBOX.getCommand(), srcBean, dstBean};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        mailboxProbe.copyMailbox(srcBean, dstBean);
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(mailboxProbe).copyMailbox(srcBean, dstBean);
     }
 
     @Test
@@ -293,12 +250,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.DELETEUSERMAILBOXES.getCommand(), user};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        mailboxProbe.deleteUserMailboxesNames(user);
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(mailboxProbe).deleteUserMailboxesNames(user);
     }
 
     @Test
@@ -309,11 +263,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.CREATEMAILBOX.getCommand(), namespace, user, name};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        expect(mailboxProbe.createMailbox(namespace, user, name)).andReturn(control.createMock(MailboxId.class));
+        when(mailboxProbe.createMailbox(namespace, user, name)).thenReturn(mock(MailboxId.class));
 
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
     }
 
     @Test
@@ -324,12 +276,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.DELETEMAILBOX.getCommand(), namespace, user, name};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        mailboxProbe.deleteMailbox(namespace, user, name);
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(mailboxProbe).deleteMailbox(namespace, user, name);
     }
     
     @Test
@@ -341,12 +290,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.IMPORTEML.getCommand(), namespace, user, name, emlpath};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        mailboxProbe.importEmlFileToMailbox(namespace, user, name, emlpath);
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(mailboxProbe).importEmlFileToMailbox(namespace, user, name, emlpath);
     }
 
     @Test
@@ -355,11 +301,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.LISTUSERMAILBOXES.getCommand(), user};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        expect(mailboxProbe.listUserMailboxes(user)).andReturn(new ArrayList<>());
+        when(mailboxProbe.listUserMailboxes(user)).thenReturn(new ArrayList<>());
 
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
     }
 
     @Test
@@ -370,11 +314,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.GETQUOTAROOT.getCommand(), namespace, user, name};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        expect(quotaProbe.getQuotaRoot(namespace, user, name)).andReturn(namespace + "&" + user);
+        when(quotaProbe.getQuotaRoot(namespace, user, name)).thenReturn(namespace + "&" + user);
 
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
     }
 
     @Test
@@ -382,11 +324,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.GETGLOBALMAXMESSAGECOUNTQUOTA.getCommand()};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        expect(quotaProbe.getGlobalMaxMessageCount()).andReturn(new SerializableQuotaValue<>(QuotaCount.count(1024L * 1024L)));
+        when(quotaProbe.getGlobalMaxMessageCount()).thenReturn(new SerializableQuotaValue<>(QuotaCount.count(1024L * 1024L)));
 
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
     }
 
     @Test
@@ -394,11 +334,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.GETGLOBALMAXSTORAGEQUOTA.getCommand()};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        expect(quotaProbe.getGlobalMaxStorage()).andReturn(new SerializableQuotaValue<>(QuotaSize.size(1024L * 1024L * 1024L)));
+        when(quotaProbe.getGlobalMaxStorage()).thenReturn(new SerializableQuotaValue<>(QuotaSize.size(1024L * 1024L * 1024L)));
 
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
     }
 
     @Test
@@ -406,12 +344,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.SETGLOBALMAXMESSAGECOUNTQUOTA.getCommand(), "1054"};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        quotaProbe.setGlobalMaxMessageCount(new SerializableQuotaValue<>(QuotaCount.count(1054)));
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(quotaProbe).setGlobalMaxMessageCount(new SerializableQuotaValue<>(QuotaCount.count(1054)));
     }
 
     @Test
@@ -419,20 +354,18 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", "--", CmdType.SETGLOBALMAXMESSAGECOUNTQUOTA.getCommand(), "-1"};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        quotaProbe.setGlobalMaxMessageCount(new SerializableQuotaValue<>(QuotaCount.unlimited()));
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(quotaProbe).setGlobalMaxMessageCount(new SerializableQuotaValue<>(QuotaCount.unlimited()));
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void setGlobalMaxMessageCountCommandShouldThrowWhenNegativeAndNotUnlimited() throws Exception {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", "--", CmdType.SETGLOBALMAXMESSAGECOUNTQUOTA.getCommand(), "-2"};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        testee.executeCommandLine(commandLine);
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(IllegalArgumentException.class);
     }
 
     @Test
@@ -440,12 +373,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.SETGLOBALMAXSTORAGEQUOTA.getCommand(), "1G"};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        quotaProbe.setGlobalMaxStorage(new SerializableQuotaValue<>(QuotaSize.size(1024 * 1024 * 1024)));
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(quotaProbe).setGlobalMaxStorage(new SerializableQuotaValue<>(QuotaSize.size(1024 * 1024 * 1024)));
     }
 
     @Test
@@ -453,20 +383,18 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", "--", CmdType.SETGLOBALMAXSTORAGEQUOTA.getCommand(), "-1"};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        quotaProbe.setGlobalMaxStorage(new SerializableQuotaValue<>(QuotaSize.unlimited()));
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(quotaProbe).setGlobalMaxStorage(new SerializableQuotaValue<>(QuotaSize.unlimited()));
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void setGlobalMaxStorageCommandShouldThrowWhenNegativeAndNotUnlimited() throws Exception {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", "--", CmdType.SETGLOBALMAXSTORAGEQUOTA.getCommand(), "-2"};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        testee.executeCommandLine(commandLine);
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(IllegalArgumentException.class);
     }
 
     @Test
@@ -475,12 +403,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.SETMAXMESSAGECOUNTQUOTA.getCommand(), quotaroot, "1000"};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        quotaProbe.setMaxMessageCount(quotaroot, new SerializableQuotaValue<>(QuotaCount.count(1000)));
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(quotaProbe).setMaxMessageCount(quotaroot, new SerializableQuotaValue<>(QuotaCount.count(1000)));
     }
 
     @Test
@@ -489,21 +414,19 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", "--", CmdType.SETMAXMESSAGECOUNTQUOTA.getCommand(), quotaroot, "-1"};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        quotaProbe.setMaxMessageCount(quotaroot, new SerializableQuotaValue<>(QuotaCount.unlimited()));
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(quotaProbe).setMaxMessageCount(quotaroot, new SerializableQuotaValue<>(QuotaCount.unlimited()));
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void setMaxMessageCountCommandShouldThrowWhenNegativeAndNotUnlimited() throws Exception {
         String quotaroot = "#private&user@domain";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", "--", CmdType.SETMAXMESSAGECOUNTQUOTA.getCommand(), quotaroot, "-2"};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        testee.executeCommandLine(commandLine);
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(IllegalArgumentException.class);
     }
 
     @Test
@@ -512,12 +435,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.SETMAXSTORAGEQUOTA.getCommand(), quotaroot, "5M"};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        quotaProbe.setMaxStorage(quotaroot, new SerializableQuotaValue<>(QuotaSize.size(5 * 1024 * 1024)));
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(quotaProbe).setMaxStorage(quotaroot, new SerializableQuotaValue<>(QuotaSize.size(5 * 1024 * 1024)));
     }
 
     @Test
@@ -526,21 +446,19 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", "--", CmdType.SETMAXSTORAGEQUOTA.getCommand(), quotaroot, "-1"};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        quotaProbe.setMaxStorage(quotaroot, new SerializableQuotaValue<>(QuotaSize.unlimited()));
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(quotaProbe).setMaxStorage(quotaroot, new SerializableQuotaValue<>(QuotaSize.unlimited()));
     }
 
-    @Test(expected = IllegalArgumentException.class)
+    @Test
     public void setMaxStorageCommandShouldThrowWhenNegativeAndNotUnlimited() throws Exception {
         String quotaroot = "#private&user@domain";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", "--", CmdType.SETMAXSTORAGEQUOTA.getCommand(), quotaroot, "-2"};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        testee.executeCommandLine(commandLine);
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(IllegalArgumentException.class);
     }
 
     @Test
@@ -549,11 +467,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.GETMAXMESSAGECOUNTQUOTA.getCommand(), quotaroot};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        expect(quotaProbe.getMaxMessageCount(quotaroot)).andReturn(new SerializableQuotaValue<>(QuotaCount.unlimited()));
+        when(quotaProbe.getMaxMessageCount(quotaroot)).thenReturn(new SerializableQuotaValue<>(QuotaCount.unlimited()));
 
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
     }
 
     @Test
@@ -562,11 +478,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.GETMAXSTORAGEQUOTA.getCommand(), quotaroot};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        expect(quotaProbe.getMaxStorage(quotaroot)).andReturn(new SerializableQuotaValue<>(QuotaSize.unlimited()));
+        when(quotaProbe.getMaxStorage(quotaroot)).thenReturn(new SerializableQuotaValue<>(QuotaSize.unlimited()));
 
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
     }
 
     @Test
@@ -575,11 +489,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.GETSTORAGEQUOTA.getCommand(), quotaroot};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        expect(quotaProbe.getStorageQuota(quotaroot)).andReturn(SerializableQuota.newInstance(QuotaSize.unlimited(), QuotaSize.size(12)));
+        when(quotaProbe.getStorageQuota(quotaroot)).thenReturn(SerializableQuota.newInstance(QuotaSize.unlimited(), QuotaSize.size(12)));
 
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
     }
 
     @Test
@@ -588,11 +500,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.GETMESSAGECOUNTQUOTA.getCommand(), quotaroot};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        expect(quotaProbe.getMessageCountQuota(quotaroot)).andReturn(SerializableQuota.newInstance(QuotaCount.unlimited(), QuotaCount.count(12)));
+        when(quotaProbe.getMessageCountQuota(quotaroot)).thenReturn(SerializableQuota.newInstance(QuotaCount.unlimited(), QuotaCount.count(12)));
 
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
     }
 
     @Test
@@ -600,12 +510,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REINDEXALL.getCommand()};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        mailboxProbe.reIndexAll();
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(mailboxProbe).reIndexAll();
     }
 
     @Test
@@ -616,12 +523,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REINDEXMAILBOX.getCommand(), namespace, user, name};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        mailboxProbe.reIndexMailbox(namespace, user, name);
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(mailboxProbe).reIndexMailbox(namespace, user, name);
     }
 
     @Test
@@ -629,12 +533,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.SETSIEVEQUOTA.getCommand(), "2K"};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        sieveProbe.setSieveQuota(2048);
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(sieveProbe).setSieveQuota(2048);
     }
 
     @Test
@@ -643,12 +544,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.SETSIEVEUSERQUOTA.getCommand(), user, "1K"};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        sieveProbe.setSieveQuota(user, 1024);
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(sieveProbe).setSieveQuota(user, 1024);
     }
 
     @Test
@@ -656,12 +554,11 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.GETSIEVEQUOTA.getCommand()};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        expect(sieveProbe.getSieveQuota()).andReturn(18L);
-        expectLastCall();
+        when(sieveProbe.getSieveQuota()).thenReturn(18L);
 
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(sieveProbe).getSieveQuota();
     }
 
     @Test
@@ -670,12 +567,11 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.GETSIEVEUSERQUOTA.getCommand(), user};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        expect(sieveProbe.getSieveQuota(user)).andReturn(18L);
-        expectLastCall();
+        when(sieveProbe.getSieveQuota(user)).thenReturn(18L);
 
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(sieveProbe).getSieveQuota(user);
     }
 
     @Test
@@ -683,12 +579,9 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REMOVESIEVEQUOTA.getCommand()};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        sieveProbe.removeSieveQuota();
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(sieveProbe).removeSieveQuota();
     }
 
     @Test
@@ -697,227 +590,164 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REMOVESIEVEUSERQUOTA.getCommand(), user};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        sieveProbe.removeSieveQuota(user);
-        expectLastCall();
-
-        control.replay();
         testee.executeCommandLine(commandLine);
-        control.verify();
+
+        verify(sieveProbe).removeSieveQuota(user);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void addDomainCommandShouldThrowOnMissingArguments() throws Exception {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.ADDDOMAIN.getCommand()};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void removeDomainCommandShouldThrowOnMissingArguments() throws Exception {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REMOVEDOMAIN.getCommand()};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
-
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void containsDomainCommandShouldThrowOnMissingArguments() throws Exception {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.CONTAINSDOMAIN.getCommand()};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void addUserCommandShouldThrowOnMissingArguments() throws Exception {
         String user = "user@domain";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.ADDUSER.getCommand(), user};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void removeUserCommandShouldThrowOnMissingArguments() throws Exception {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REMOVEUSER.getCommand()};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void listUserDomainMappingsCommandShouldThrowOnMissingArguments() throws Exception {
         String user = "user@domain";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.LISTUSERDOMAINMAPPINGS.getCommand(), user};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void addAddressCommandShouldThrowOnMissingArguments() throws Exception {
         String user = "user@domain";
         String domain = "domain";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.ADDADDRESSMAPPING.getCommand(), user, domain};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void removeAddressCommandShouldThrowOnMissingArguments() throws Exception {
         String user = "user@domain";
         String domain = "domain";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REMOVEADDRESSMAPPING.getCommand(), user, domain};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void addRegexMappingCommandShouldThrowOnMissingArguments() throws Exception {
         String user = "user@domain";
         String domain = "domain";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.ADDREGEXMAPPING.getCommand(), user, domain};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void removeRegexMappingCommandShouldThrowOnMissingArguments() throws Exception {
         String user = "user@domain";
         String domain = "domain";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REMOVEREGEXMAPPING.getCommand(), user, domain};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void setPasswordMappingCommandShouldThrowOnMissingArguments() throws Exception {
         String user = "user@domain";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.SETPASSWORD.getCommand(), user};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void copyMailboxMappingCommandShouldThrowOnMissingArguments() throws Exception {
         String srcBean = "srcBean";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.COPYMAILBOX.getCommand(), srcBean};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void deleteUserMailboxesMappingCommandShouldThrowOnMissingArguments() throws Exception {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.DELETEUSERMAILBOXES.getCommand()};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void createMailboxMappingCommandShouldThrowOnMissingArguments() throws Exception {
         String user = "user@domain";
         String namespace = "#private";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.CREATEMAILBOX.getCommand(), namespace, user};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void deleteMailboxMappingCommandShouldThrowOnMissingArguments() throws Exception {
         String user = "user@domain";
         String namespace = "#private";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.DELETEMAILBOX.getCommand(), namespace, user};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void importEmlFileToMailboxCommandShouldThrowOnMissingArguments() throws Exception {
         String user = "user@domain";
         String namespace = "#private";
@@ -925,153 +755,109 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.IMPORTEML.getCommand(), namespace, user, name};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void listUserMailboxesMappingsCommandShouldThrowOnMissingArguments() throws Exception {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.LISTUSERMAILBOXES.getCommand()};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void addDomainCommandShouldThrowOnAdditionalArguments() throws Exception {
         String domain = "example.com";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.ADDDOMAIN.getCommand(), domain, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void removeDomainCommandShouldThrowOnAdditionalArguments() throws Exception {
         String domain = "example.com";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REMOVEDOMAIN.getCommand(), domain, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void containsDomainCommandShouldThrowOnAdditionalArguments() throws Exception {
         String domain = "example.com";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.CONTAINSDOMAIN.getCommand(), domain, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void listDomainsCommandShouldThrowOnAdditionalArguments() throws Exception {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.LISTDOMAINS.getCommand(), ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void addUserCommandShouldThrowOnAdditionalArguments() throws Exception {
         String user = "user@domain";
         String password = "password";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.ADDUSER.getCommand(), user, password, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void removeUserCommandShouldThrowOnAdditionalArguments() throws Exception {
         String user = "user@domain";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REMOVEUSER.getCommand(), user, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void listUsersCommandShouldThrowOnAdditionalArguments() throws Exception {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.LISTUSERS.getCommand(), ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void listMappingsCommandShouldThrowOnAdditionalArguments() throws Exception {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.LISTMAPPINGS.getCommand(), ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void listUserDomainMappingsCommandShouldThrowOnAdditionalArguments() throws Exception {
         String user = "user@domain";
         String domain = "domain";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.LISTUSERDOMAINMAPPINGS.getCommand(), user, domain, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void addAddressCommandShouldThrowOnAdditionalArguments() throws Exception {
         String user = "user@domain";
         String domain = "domain";
@@ -1079,15 +865,11 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.ADDADDRESSMAPPING.getCommand(), user, domain, address, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void removeAddressCommandShouldThrowOnAdditionalArguments() throws Exception {
         String user = "user@domain";
         String domain = "domain";
@@ -1095,15 +877,11 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REMOVEADDRESSMAPPING.getCommand(), user, domain, address, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void addRegexMappingCommandShouldThrowOnAdditionalArguments() throws Exception {
         String user = "user@domain";
         String domain = "domain";
@@ -1111,15 +889,11 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.ADDREGEXMAPPING.getCommand(), user, domain, regex, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void removeRegexMappingCommandShouldThrowOnAdditionalArguments() throws Exception {
         String user = "user@domain";
         String domain = "domain";
@@ -1127,59 +901,43 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REMOVEREGEXMAPPING.getCommand(), user, domain, regex, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void setPasswordMappingCommandShouldThrowOnAdditionalArguments() throws Exception {
         String user = "user@domain";
         String password = "pass";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.SETPASSWORD.getCommand(), user, password, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void copyMailboxMappingCommandShouldThrowOnAdditionalArguments() throws Exception {
         String srcBean = "srcBean";
         String dstBean = "dstBean";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.COPYMAILBOX.getCommand(), srcBean, dstBean, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void deleteUserMailboxesMappingCommandShouldThrowOnAdditionalArguments() throws Exception {
         String user = "user@domain";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.DELETEUSERMAILBOXES.getCommand(), user, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void createMailboxMappingCommandShouldThrowOnAdditionalArguments() throws Exception {
         String user = "user@domain";
         String namespace = "#private";
@@ -1187,15 +945,11 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.CREATEMAILBOX.getCommand(), namespace, user, name, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void deleteMailboxMappingCommandShouldThrowOnAdditionalArguments() throws Exception {
         String user = "user@domain";
         String namespace = "#private";
@@ -1203,15 +957,11 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.DELETEMAILBOX.getCommand(), namespace, user, name, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void importEmlFileToMailboxCommandShouldThrowOnAdditionalArguments() throws Exception {
         String user = "user@domain";
         String namespace = "#private";
@@ -1220,42 +970,30 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.IMPORTEML.getCommand(), namespace, user, name, emlpath, ADDITIONAL_ARGUMENT};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void listUserMailboxesMappingsCommandShouldThrowOnAdditionalArguments() throws Exception {
         String user = "user@domain";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.LISTUSERMAILBOXES.getCommand(), user, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void reIndexAllCommandShouldThrowOnAdditionalArguments() throws Exception {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REINDEXALL.getCommand(), ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void reIndexMailboxCommandShouldThrowOnAdditionalArguments() throws Exception {
         String user = "user@domain";
         String namespace = "#private";
@@ -1263,124 +1001,98 @@ public class ServerCmdTest {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REINDEXMAILBOX.getCommand(), namespace, user, name, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void removeSieveQuotaCommandShouldThrowOnAdditionalArguments() throws Exception {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REMOVESIEVEQUOTA.getCommand(), ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void removeSieveUserQuotaCommandShouldThrowOnAdditionalArguments() throws Exception {
         String user = "user@domain";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.REMOVESIEVEUSERQUOTA.getCommand(), user, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void getSieveQuotaCommandShouldThrowOnAdditionalArguments() throws Exception {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.GETSIEVEQUOTA.getCommand(), ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void setSieveQuotaCommandShouldThrowOnAdditionalArguments() throws Exception {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.SETSIEVEQUOTA.getCommand(), "64K", ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void getSieveUserQuotaCommandShouldThrowOnAdditionalArguments() throws Exception {
         String user = "user@domain";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.GETSIEVEUSERQUOTA.getCommand(), user, ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = InvalidArgumentNumberException.class)
+    @Test
     public void setSieveUserQuotaCommandShouldThrowOnAdditionalArguments() throws Exception {
         String user = "user@domain";
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", CmdType.SETSIEVEUSERQUOTA.getCommand(), user, "64K", ADDITIONAL_ARGUMENT };
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(InvalidArgumentNumberException.class);
     }
 
-    @Test(expected = UnrecognizedCommandException.class)
+    @Test
     public void executeCommandLineShouldThrowOnUnrecognizedCommands() throws Exception {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999", "wrongCommand"};
         CommandLine commandLine = ServerCmd.parseCommandLine(arguments);
 
-        control.replay();
-        try {
-            testee.executeCommandLine(commandLine);
-        } finally {
-            control.verify();
-        }
+        assertThatThrownBy(() -> testee.executeCommandLine(commandLine))
+            .isInstanceOf(UnrecognizedCommandException.class);
     }
 
-    @Test(expected = MissingCommandException.class)
+    @Test
     public void parseCommandLineShouldThrowWhenOnlyOptionAreProvided() throws Exception {
         String[] arguments = { "-h", "127.0.0.1", "-p", "9999" };
-        ServerCmd.parseCommandLine(arguments);
+
+        assertThatThrownBy(() -> ServerCmd.parseCommandLine(arguments))
+            .isInstanceOf(MissingCommandException.class);
     }
 
-    @Test(expected = ParseException.class)
+    @Test
     public void parseCommandLineShouldThrowWhenInvalidOptionIsProvided() throws Exception {
         String[] arguments = { "-v", "-h", "127.0.0.1", "-p", "9999" };
-        ServerCmd.parseCommandLine(arguments);
+
+        assertThatThrownBy(() -> ServerCmd.parseCommandLine(arguments))
+            .isInstanceOf(ParseException.class);
     }
 
-    @Test(expected = ParseException.class)
+    @Test
     public void parseCommandLineShouldThrowWhenMandatoryOptionIsMissing() throws Exception {
         String[] arguments = { "-v", "-h", "127.0.0.1", "-p", "9999" };
-        ServerCmd.parseCommandLine(arguments);
+
+        assertThatThrownBy(() -> ServerCmd.parseCommandLine(arguments))
+            .isInstanceOf(ParseException.class);
     }
 
     @Test


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


[15/20] james-project git commit: JAMES-2513 Turn DomainList autoDetect autoDetection off in tests

Posted by bt...@apache.org.
JAMES-2513 Turn DomainList autoDetect autoDetection off in tests


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

Branch: refs/heads/master
Commit: 5f45d496735102e1b36d9efaa7b2e4db18a33471
Parents: 3c275fe
Author: benwa <bt...@linagora.com>
Authored: Thu Aug 2 09:29:25 2018 +0700
Committer: Benoit Tellier <bt...@linagora.com>
Committed: Fri Aug 3 15:51:29 2018 +0700

----------------------------------------------------------------------
 .../apache/james/CassandraJamesServerTest.java  |  2 +-
 .../org/apache/james/CassandraWithTikaTest.java |  2 +-
 .../src/test/resources/domainlist.xml           | 24 ++++++++++++++++++++
 .../james/CassandraLdapJamesServerTest.java     |  2 +-
 .../src/test/resources/domainlist.xml           | 24 ++++++++++++++++++++
 .../jpa-guice/src/test/resources/domainlist.xml | 24 ++++++++++++++++++++
 .../src/test/resources/domainlist.xml           | 24 ++++++++++++++++++++
 .../jpa-smtp/src/test/resources/domainlist.xml  | 24 ++++++++++++++++++++
 .../org/apache/james/MemoryJamesServerTest.java |  6 +++--
 .../src/test/resources/domainlist.xml           | 24 ++++++++++++++++++++
 .../james/AbstractJmapJamesServerTest.java      |  9 ++++++++
 .../src/test/resources/domainlist.xml           | 24 ++++++++++++++++++++
 12 files changed, 184 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/5f45d496/server/container/guice/cassandra-guice/src/test/java/org/apache/james/CassandraJamesServerTest.java
----------------------------------------------------------------------
diff --git a/server/container/guice/cassandra-guice/src/test/java/org/apache/james/CassandraJamesServerTest.java b/server/container/guice/cassandra-guice/src/test/java/org/apache/james/CassandraJamesServerTest.java
index 50b5cbe..0a13642 100644
--- a/server/container/guice/cassandra-guice/src/test/java/org/apache/james/CassandraJamesServerTest.java
+++ b/server/container/guice/cassandra-guice/src/test/java/org/apache/james/CassandraJamesServerTest.java
@@ -34,7 +34,7 @@ public class CassandraJamesServerTest extends AbstractJmapJamesServerTest {
 
     @Override
     protected GuiceJamesServer createJamesServer() throws IOException {
-        return cassandraJmap.jmapServer(cassandra.getModule());
+        return cassandraJmap.jmapServer(cassandra.getModule(), DOMAIN_LIST_CONFIGURATION_MODULE);
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/james-project/blob/5f45d496/server/container/guice/cassandra-guice/src/test/java/org/apache/james/CassandraWithTikaTest.java
----------------------------------------------------------------------
diff --git a/server/container/guice/cassandra-guice/src/test/java/org/apache/james/CassandraWithTikaTest.java b/server/container/guice/cassandra-guice/src/test/java/org/apache/james/CassandraWithTikaTest.java
index eef9a48..408fef0 100644
--- a/server/container/guice/cassandra-guice/src/test/java/org/apache/james/CassandraWithTikaTest.java
+++ b/server/container/guice/cassandra-guice/src/test/java/org/apache/james/CassandraWithTikaTest.java
@@ -36,7 +36,7 @@ public class CassandraWithTikaTest extends AbstractJmapJamesServerTest {
 
     @Override
     protected GuiceJamesServer createJamesServer() throws IOException {
-        return cassandraJmap.jmapServer(guiceTikaRule.getModule(), cassandra.getModule());
+        return cassandraJmap.jmapServer(guiceTikaRule.getModule(), cassandra.getModule(), DOMAIN_LIST_CONFIGURATION_MODULE);
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/james-project/blob/5f45d496/server/container/guice/cassandra-guice/src/test/resources/domainlist.xml
----------------------------------------------------------------------
diff --git a/server/container/guice/cassandra-guice/src/test/resources/domainlist.xml b/server/container/guice/cassandra-guice/src/test/resources/domainlist.xml
new file mode 100644
index 0000000..fe17431
--- /dev/null
+++ b/server/container/guice/cassandra-guice/src/test/resources/domainlist.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one   
+  or more contributor license agreements.  See the NOTICE file 
+  distributed with this work for additional information        
+  regarding copyright ownership.  The ASF licenses this file   
+  to you under the Apache License, Version 2.0 (the            
+  "License"); you may not use this file except in compliance   
+  with the License.  You may obtain a copy of the License at   
+                                                               
+    http://www.apache.org/licenses/LICENSE-2.0                 
+                                                               
+  Unless required by applicable law or agreed to in writing,   
+  software distributed under the License is distributed on an  
+  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       
+  KIND, either express or implied.  See the License for the    
+  specific language governing permissions and limitations      
+  under the License.                                           
+ -->
+
+<domainlist>
+    <autodetect>false</autodetect>
+    <autodetectIP>false</autodetectIP>
+</domainlist>

http://git-wip-us.apache.org/repos/asf/james-project/blob/5f45d496/server/container/guice/cassandra-ldap-guice/src/test/java/org/apache/james/CassandraLdapJamesServerTest.java
----------------------------------------------------------------------
diff --git a/server/container/guice/cassandra-ldap-guice/src/test/java/org/apache/james/CassandraLdapJamesServerTest.java b/server/container/guice/cassandra-ldap-guice/src/test/java/org/apache/james/CassandraLdapJamesServerTest.java
index 5954d0d..5aa6c35 100644
--- a/server/container/guice/cassandra-ldap-guice/src/test/java/org/apache/james/CassandraLdapJamesServerTest.java
+++ b/server/container/guice/cassandra-ldap-guice/src/test/java/org/apache/james/CassandraLdapJamesServerTest.java
@@ -68,7 +68,7 @@ public class CassandraLdapJamesServerTest extends AbstractJmapJamesServerTest {
     @Override
     protected GuiceJamesServer createJamesServer() throws IOException {
         ldapContainer.start();
-        return cassandraLdapJmap.jmapServer(ldapContainer.getLdapHost());
+        return cassandraLdapJmap.jmapServer(ldapContainer.getLdapHost(), DOMAIN_LIST_CONFIGURATION_MODULE);
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/james-project/blob/5f45d496/server/container/guice/cassandra-ldap-guice/src/test/resources/domainlist.xml
----------------------------------------------------------------------
diff --git a/server/container/guice/cassandra-ldap-guice/src/test/resources/domainlist.xml b/server/container/guice/cassandra-ldap-guice/src/test/resources/domainlist.xml
new file mode 100644
index 0000000..fe17431
--- /dev/null
+++ b/server/container/guice/cassandra-ldap-guice/src/test/resources/domainlist.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one   
+  or more contributor license agreements.  See the NOTICE file 
+  distributed with this work for additional information        
+  regarding copyright ownership.  The ASF licenses this file   
+  to you under the Apache License, Version 2.0 (the            
+  "License"); you may not use this file except in compliance   
+  with the License.  You may obtain a copy of the License at   
+                                                               
+    http://www.apache.org/licenses/LICENSE-2.0                 
+                                                               
+  Unless required by applicable law or agreed to in writing,   
+  software distributed under the License is distributed on an  
+  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       
+  KIND, either express or implied.  See the License for the    
+  specific language governing permissions and limitations      
+  under the License.                                           
+ -->
+
+<domainlist>
+    <autodetect>false</autodetect>
+    <autodetectIP>false</autodetectIP>
+</domainlist>

http://git-wip-us.apache.org/repos/asf/james-project/blob/5f45d496/server/container/guice/jpa-guice/src/test/resources/domainlist.xml
----------------------------------------------------------------------
diff --git a/server/container/guice/jpa-guice/src/test/resources/domainlist.xml b/server/container/guice/jpa-guice/src/test/resources/domainlist.xml
new file mode 100644
index 0000000..fe17431
--- /dev/null
+++ b/server/container/guice/jpa-guice/src/test/resources/domainlist.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one   
+  or more contributor license agreements.  See the NOTICE file 
+  distributed with this work for additional information        
+  regarding copyright ownership.  The ASF licenses this file   
+  to you under the Apache License, Version 2.0 (the            
+  "License"); you may not use this file except in compliance   
+  with the License.  You may obtain a copy of the License at   
+                                                               
+    http://www.apache.org/licenses/LICENSE-2.0                 
+                                                               
+  Unless required by applicable law or agreed to in writing,   
+  software distributed under the License is distributed on an  
+  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       
+  KIND, either express or implied.  See the License for the    
+  specific language governing permissions and limitations      
+  under the License.                                           
+ -->
+
+<domainlist>
+    <autodetect>false</autodetect>
+    <autodetectIP>false</autodetectIP>
+</domainlist>

http://git-wip-us.apache.org/repos/asf/james-project/blob/5f45d496/server/container/guice/jpa-smtp-mariadb/src/test/resources/domainlist.xml
----------------------------------------------------------------------
diff --git a/server/container/guice/jpa-smtp-mariadb/src/test/resources/domainlist.xml b/server/container/guice/jpa-smtp-mariadb/src/test/resources/domainlist.xml
new file mode 100644
index 0000000..fe17431
--- /dev/null
+++ b/server/container/guice/jpa-smtp-mariadb/src/test/resources/domainlist.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one   
+  or more contributor license agreements.  See the NOTICE file 
+  distributed with this work for additional information        
+  regarding copyright ownership.  The ASF licenses this file   
+  to you under the Apache License, Version 2.0 (the            
+  "License"); you may not use this file except in compliance   
+  with the License.  You may obtain a copy of the License at   
+                                                               
+    http://www.apache.org/licenses/LICENSE-2.0                 
+                                                               
+  Unless required by applicable law or agreed to in writing,   
+  software distributed under the License is distributed on an  
+  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       
+  KIND, either express or implied.  See the License for the    
+  specific language governing permissions and limitations      
+  under the License.                                           
+ -->
+
+<domainlist>
+    <autodetect>false</autodetect>
+    <autodetectIP>false</autodetectIP>
+</domainlist>

http://git-wip-us.apache.org/repos/asf/james-project/blob/5f45d496/server/container/guice/jpa-smtp/src/test/resources/domainlist.xml
----------------------------------------------------------------------
diff --git a/server/container/guice/jpa-smtp/src/test/resources/domainlist.xml b/server/container/guice/jpa-smtp/src/test/resources/domainlist.xml
new file mode 100644
index 0000000..fe17431
--- /dev/null
+++ b/server/container/guice/jpa-smtp/src/test/resources/domainlist.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one   
+  or more contributor license agreements.  See the NOTICE file 
+  distributed with this work for additional information        
+  regarding copyright ownership.  The ASF licenses this file   
+  to you under the Apache License, Version 2.0 (the            
+  "License"); you may not use this file except in compliance   
+  with the License.  You may obtain a copy of the License at   
+                                                               
+    http://www.apache.org/licenses/LICENSE-2.0                 
+                                                               
+  Unless required by applicable law or agreed to in writing,   
+  software distributed under the License is distributed on an  
+  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       
+  KIND, either express or implied.  See the License for the    
+  specific language governing permissions and limitations      
+  under the License.                                           
+ -->
+
+<domainlist>
+    <autodetect>false</autodetect>
+    <autodetectIP>false</autodetectIP>
+</domainlist>

http://git-wip-us.apache.org/repos/asf/james-project/blob/5f45d496/server/container/guice/memory-guice/src/test/java/org/apache/james/MemoryJamesServerTest.java
----------------------------------------------------------------------
diff --git a/server/container/guice/memory-guice/src/test/java/org/apache/james/MemoryJamesServerTest.java b/server/container/guice/memory-guice/src/test/java/org/apache/james/MemoryJamesServerTest.java
index e4f2410..90e27bd 100644
--- a/server/container/guice/memory-guice/src/test/java/org/apache/james/MemoryJamesServerTest.java
+++ b/server/container/guice/memory-guice/src/test/java/org/apache/james/MemoryJamesServerTest.java
@@ -21,16 +21,18 @@ package org.apache.james;
 
 import java.io.IOException;
 
+import org.apache.james.domainlist.lib.DomainListConfiguration;
 import org.junit.Rule;
 
-public class MemoryJamesServerTest extends AbstractJmapJamesServerTest {
+import com.google.inject.Module;
 
+public class MemoryJamesServerTest extends AbstractJmapJamesServerTest {
     @Rule
     public MemoryJmapTestRule memoryJmap = new MemoryJmapTestRule();
 
     @Override
     protected GuiceJamesServer createJamesServer() throws IOException {
-        return memoryJmap.jmapServer();
+        return memoryJmap.jmapServer(DOMAIN_LIST_CONFIGURATION_MODULE);
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/james-project/blob/5f45d496/server/container/guice/memory-guice/src/test/resources/domainlist.xml
----------------------------------------------------------------------
diff --git a/server/container/guice/memory-guice/src/test/resources/domainlist.xml b/server/container/guice/memory-guice/src/test/resources/domainlist.xml
new file mode 100644
index 0000000..fe17431
--- /dev/null
+++ b/server/container/guice/memory-guice/src/test/resources/domainlist.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one   
+  or more contributor license agreements.  See the NOTICE file 
+  distributed with this work for additional information        
+  regarding copyright ownership.  The ASF licenses this file   
+  to you under the Apache License, Version 2.0 (the            
+  "License"); you may not use this file except in compliance   
+  with the License.  You may obtain a copy of the License at   
+                                                               
+    http://www.apache.org/licenses/LICENSE-2.0                 
+                                                               
+  Unless required by applicable law or agreed to in writing,   
+  software distributed under the License is distributed on an  
+  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       
+  KIND, either express or implied.  See the License for the    
+  specific language governing permissions and limitations      
+  under the License.                                           
+ -->
+
+<domainlist>
+    <autodetect>false</autodetect>
+    <autodetectIP>false</autodetectIP>
+</domainlist>

http://git-wip-us.apache.org/repos/asf/james-project/blob/5f45d496/server/container/guice/protocols/jmap/src/test/java/org/apache/james/AbstractJmapJamesServerTest.java
----------------------------------------------------------------------
diff --git a/server/container/guice/protocols/jmap/src/test/java/org/apache/james/AbstractJmapJamesServerTest.java b/server/container/guice/protocols/jmap/src/test/java/org/apache/james/AbstractJmapJamesServerTest.java
index 3e10b05..1abae59 100644
--- a/server/container/guice/protocols/jmap/src/test/java/org/apache/james/AbstractJmapJamesServerTest.java
+++ b/server/container/guice/protocols/jmap/src/test/java/org/apache/james/AbstractJmapJamesServerTest.java
@@ -31,18 +31,27 @@ import java.nio.channels.SocketChannel;
 import java.nio.charset.Charset;
 import java.nio.charset.StandardCharsets;
 
+import org.apache.james.domainlist.lib.DomainListConfiguration;
 import org.apache.james.utils.DataProbeImpl;
 import org.apache.james.utils.JmapGuiceProbe;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 
+import com.google.inject.Module;
+
 import io.restassured.RestAssured;
 import io.restassured.builder.RequestSpecBuilder;
 import io.restassured.http.ContentType;
 
 public abstract class AbstractJmapJamesServerTest {
 
+    public static final Module DOMAIN_LIST_CONFIGURATION_MODULE = binder -> binder.bind(DomainListConfiguration.class)
+        .toInstance(DomainListConfiguration.builder()
+            .autoDetect(true)
+            .autoDetectIp(false)
+            .build());
+
     private static final int IMAP_PORT_SSL = 1993;
     private static final int POP3_PORT = 1110;
     private static final int SMTP_PORT = 1025;

http://git-wip-us.apache.org/repos/asf/james-project/blob/5f45d496/server/protocols/webadmin-integration-test/src/test/resources/domainlist.xml
----------------------------------------------------------------------
diff --git a/server/protocols/webadmin-integration-test/src/test/resources/domainlist.xml b/server/protocols/webadmin-integration-test/src/test/resources/domainlist.xml
new file mode 100644
index 0000000..fe17431
--- /dev/null
+++ b/server/protocols/webadmin-integration-test/src/test/resources/domainlist.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one   
+  or more contributor license agreements.  See the NOTICE file 
+  distributed with this work for additional information        
+  regarding copyright ownership.  The ASF licenses this file   
+  to you under the Apache License, Version 2.0 (the            
+  "License"); you may not use this file except in compliance   
+  with the License.  You may obtain a copy of the License at   
+                                                               
+    http://www.apache.org/licenses/LICENSE-2.0                 
+                                                               
+  Unless required by applicable law or agreed to in writing,   
+  software distributed under the License is distributed on an  
+  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       
+  KIND, either express or implied.  See the License for the    
+  specific language governing permissions and limitations      
+  under the License.                                           
+ -->
+
+<domainlist>
+    <autodetect>false</autodetect>
+    <autodetectIP>false</autodetectIP>
+</domainlist>


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


[17/20] james-project git commit: JAMES-2513 Improve AbstractDomainListPrivateMethodsTest

Posted by bt...@apache.org.
JAMES-2513 Improve AbstractDomainListPrivateMethodsTest

 - Avoid using mocks. Prefer relying on the configuration POJO
 - Avoid throwing needless exceptions


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

Branch: refs/heads/master
Commit: 8daad381b28b95ad560f7ece08ab6bb3f7fd34d3
Parents: 5f45d49
Author: benwa <bt...@linagora.com>
Authored: Thu Aug 2 09:40:51 2018 +0700
Committer: Benoit Tellier <bt...@linagora.com>
Committed: Fri Aug 3 15:51:29 2018 +0700

----------------------------------------------------------------------
 .../domainlist/lib/AbstractDomainList.java      |   4 +
 .../domainlist/lib/DomainListConfiguration.java |   5 +
 .../AbstractDomainListPrivateMethodsTest.java   | 131 ++++++++-----------
 3 files changed, 62 insertions(+), 78 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/8daad381/server/data/data-library/src/main/java/org/apache/james/domainlist/lib/AbstractDomainList.java
----------------------------------------------------------------------
diff --git a/server/data/data-library/src/main/java/org/apache/james/domainlist/lib/AbstractDomainList.java b/server/data/data-library/src/main/java/org/apache/james/domainlist/lib/AbstractDomainList.java
index e8fddd4..e27ed5e 100644
--- a/server/data/data-library/src/main/java/org/apache/james/domainlist/lib/AbstractDomainList.java
+++ b/server/data/data-library/src/main/java/org/apache/james/domainlist/lib/AbstractDomainList.java
@@ -86,6 +86,10 @@ public abstract class AbstractDomainList implements DomainList, Configurable {
         addEnvDomain();
         addConfiguredDomains(domainListConfiguration.getConfiguredDomains());
     }
+    
+    public void configure(DomainListConfiguration.Builder configurationBuilder) throws ConfigurationException {
+        configure(configurationBuilder.build());
+    }
 
     protected void addConfiguredDomains(List<Domain> domains) {
         domains.stream()

http://git-wip-us.apache.org/repos/asf/james-project/blob/8daad381/server/data/data-library/src/main/java/org/apache/james/domainlist/lib/DomainListConfiguration.java
----------------------------------------------------------------------
diff --git a/server/data/data-library/src/main/java/org/apache/james/domainlist/lib/DomainListConfiguration.java b/server/data/data-library/src/main/java/org/apache/james/domainlist/lib/DomainListConfiguration.java
index 8302b3f..5930fbe 100644
--- a/server/data/data-library/src/main/java/org/apache/james/domainlist/lib/DomainListConfiguration.java
+++ b/server/data/data-library/src/main/java/org/apache/james/domainlist/lib/DomainListConfiguration.java
@@ -19,6 +19,7 @@
 
 package org.apache.james.domainlist.lib;
 
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.List;
 import java.util.Objects;
@@ -85,6 +86,10 @@ public class DomainListConfiguration {
             return this;
         }
 
+        public Builder addConfiguredDomains(Domain... domains) {
+            return this.addConfiguredDomains(Arrays.asList(domains));
+        }
+
         public DomainListConfiguration build() {
             return new DomainListConfiguration(
                 autoDetectIp.orElse(true),

http://git-wip-us.apache.org/repos/asf/james-project/blob/8daad381/server/data/data-library/src/test/java/org/apache/james/domainlist/lib/AbstractDomainListPrivateMethodsTest.java
----------------------------------------------------------------------
diff --git a/server/data/data-library/src/test/java/org/apache/james/domainlist/lib/AbstractDomainListPrivateMethodsTest.java b/server/data/data-library/src/test/java/org/apache/james/domainlist/lib/AbstractDomainListPrivateMethodsTest.java
index 787e3e8..4ecd689 100644
--- a/server/data/data-library/src/test/java/org/apache/james/domainlist/lib/AbstractDomainListPrivateMethodsTest.java
+++ b/server/data/data-library/src/test/java/org/apache/james/domainlist/lib/AbstractDomainListPrivateMethodsTest.java
@@ -25,14 +25,11 @@ import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verifyZeroInteractions;
 import static org.mockito.Mockito.when;
 
-import java.net.Inet4Address;
 import java.net.InetAddress;
 import java.util.List;
 
-import org.apache.commons.configuration.HierarchicalConfiguration;
 import org.apache.james.core.Domain;
 import org.apache.james.dnsservice.api.DNSService;
-import org.apache.james.domainlist.api.DomainListException;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -55,28 +52,28 @@ public class AbstractDomainListPrivateMethodsTest {
 
         private List<Domain> domains;
 
-        public MyDomainList(DNSService dns, EnvDetector envDetector) {
+        MyDomainList(DNSService dns, EnvDetector envDetector) {
             super(dns, envDetector);
             this.domains = Lists.newArrayList();
         }
 
         @Override
-        protected boolean containsDomainInternal(Domain domain) throws DomainListException {
+        protected boolean containsDomainInternal(Domain domain) {
             return domains.contains(domain);
         }
 
         @Override
-        public void addDomain(Domain domain) throws DomainListException {
+        public void addDomain(Domain domain) {
             domains.add(domain);
         }
 
         @Override
-        public void removeDomain(Domain domain) throws DomainListException {
+        public void removeDomain(Domain domain) {
             domains.remove(domain);
         }
 
         @Override
-        protected List<Domain> getDomainListInternal() throws DomainListException {
+        protected List<Domain> getDomainListInternal() {
             return domains;
         }
     }
@@ -136,24 +133,20 @@ public class AbstractDomainListPrivateMethodsTest {
 
     @Test
     public void getDomainsShouldNotDetectDomainsWhenDisabled() throws Exception {
-        HierarchicalConfiguration configuration = mock(HierarchicalConfiguration.class);
+        Domain domain = Domain.of("domain.tld");
+        domainList.configure(DomainListConfiguration.builder()
+            .autoDetect(false)
+            .autoDetectIp(false)
+            .defaultDomain(domain));
 
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT, null)).thenReturn(false);
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT_IP, null)).thenReturn(false);
-        String domain = "domain.tld";
-        when(configuration.getString(AbstractDomainList.CONFIGURE_DEFAULT_DOMAIN, null)).thenReturn(domain);
-        domainList.configure(configuration);
-
-        assertThat(domainList.getDomains()).containsOnly(Domain.of(domain));
+        assertThat(domainList.getDomains()).containsOnly(domain);
     }
 
     @Test
     public void getDomainsShouldNotInteractWithDNSWhenDisabled() throws Exception {
-        HierarchicalConfiguration configuration = mock(HierarchicalConfiguration.class);
-
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT, true)).thenReturn(false);
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT_IP, true)).thenReturn(false);
-        domainList.configure(configuration);
+        domainList.configure(DomainListConfiguration.builder()
+            .autoDetect(false)
+            .autoDetectIp(false));
         domainList.getDomains();
 
         verifyZeroInteractions(dnsService);
@@ -161,11 +154,9 @@ public class AbstractDomainListPrivateMethodsTest {
 
     @Test
     public void getDomainsShouldContainDetectedDomains() throws Exception {
-        HierarchicalConfiguration configuration = mock(HierarchicalConfiguration.class);
-
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT, null)).thenReturn(true);
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT_IP, null)).thenReturn(false);
-        domainList.configure(configuration);
+        domainList.configure(DomainListConfiguration.builder()
+            .autoDetect(true)
+            .autoDetectIp(false));
 
         String detected = "detected.tld";
         when(dnsService.getLocalHost()).thenReturn(InetAddress.getByName("127.0.0.1"));
@@ -176,11 +167,9 @@ public class AbstractDomainListPrivateMethodsTest {
 
     @Test
     public void getDomainsShouldContainDetectedDomainsAndIps() throws Exception {
-        HierarchicalConfiguration configuration = mock(HierarchicalConfiguration.class);
-
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT, null)).thenReturn(true);
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT_IP, null)).thenReturn(true);
-        domainList.configure(configuration);
+        domainList.configure(DomainListConfiguration.builder()
+            .autoDetect(true)
+            .autoDetectIp(true));
 
         String detected = "detected.tld";
         String detectedIp = "148.25.32.1";
@@ -195,11 +184,9 @@ public class AbstractDomainListPrivateMethodsTest {
 
     @Test
     public void getDomainsShouldContainDetectedDomainsAndIpsOfAddedDomains() throws Exception {
-        HierarchicalConfiguration configuration = mock(HierarchicalConfiguration.class);
-
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT, null)).thenReturn(true);
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT_IP, null)).thenReturn(true);
-        domainList.configure(configuration);
+        domainList.configure(DomainListConfiguration.builder()
+            .autoDetect(true)
+            .autoDetectIp(true));
 
         String added = "added.tld";
         String detected = "detected.tld";
@@ -222,15 +209,15 @@ public class AbstractDomainListPrivateMethodsTest {
 
     @Test
     public void getDomainsShouldListAddedDomain() throws Exception {
-        HierarchicalConfiguration configuration = mock(HierarchicalConfiguration.class);
-
         Domain defaultDomain = Domain.of("default.tld");
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT, null)).thenReturn(false);
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT_IP, null)).thenReturn(false);
-        when(configuration.getString(AbstractDomainList.CONFIGURE_DEFAULT_DOMAIN, null)).thenReturn(defaultDomain.asString());
         Domain domain = Domain.of("added.tld");
+
         domainList.addDomain(domain);
-        domainList.configure(configuration);
+
+        domainList.configure(DomainListConfiguration.builder()
+            .autoDetect(false)
+            .autoDetectIp(false)
+            .defaultDomain(defaultDomain));
 
         assertThat(domainList.getDomains()).containsOnly(domain, defaultDomain);
     }
@@ -250,36 +237,31 @@ public class AbstractDomainListPrivateMethodsTest {
 
     @Test
     public void containsDomainShouldReturnTrueWhenDomainIsContained() throws Exception {
-        HierarchicalConfiguration configuration = mock(HierarchicalConfiguration.class);
-
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT, true)).thenReturn(false);
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT_IP, true)).thenReturn(false);
         Domain domain = Domain.of("added.tld");
         domainList.addDomain(domain);
-        domainList.configure(configuration);
+        domainList.configure(DomainListConfiguration.builder()
+            .autoDetect(false)
+            .autoDetectIp(false));
 
         assertThat(domainList.containsDomain(domain)).isTrue();
     }
 
     @Test
     public void containsDomainShouldReturnFalseWhenDomainIsNotContained() throws Exception {
-        HierarchicalConfiguration configuration = mock(HierarchicalConfiguration.class);
-
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT, true)).thenReturn(false);
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT_IP, true)).thenReturn(false);
         Domain domain = Domain.of("added.tld");
-        domainList.configure(configuration);
+
+        domainList.configure(DomainListConfiguration.builder()
+            .autoDetect(false)
+            .autoDetectIp(false));
 
         assertThat(domainList.containsDomain(domain)).isFalse();
     }
 
     @Test
     public void containsDomainShouldNotInteractWithDNSWhenDisabled() throws Exception {
-        HierarchicalConfiguration configuration = mock(HierarchicalConfiguration.class);
-
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT, true)).thenReturn(false);
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT_IP, true)).thenReturn(false);
-        domainList.configure(configuration);
+        domainList.configure(DomainListConfiguration.builder()
+            .autoDetect(false)
+            .autoDetectIp(false));
         domainList.containsDomain(Domain.of("added.tld"));
 
         verifyZeroInteractions(dnsService);
@@ -287,11 +269,9 @@ public class AbstractDomainListPrivateMethodsTest {
 
     @Test
     public void containsDomainShouldReturnDetectedDomains() throws Exception {
-        HierarchicalConfiguration configuration = mock(HierarchicalConfiguration.class);
-
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT, null)).thenReturn(true);
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT_IP, null)).thenReturn(false);
-        domainList.configure(configuration);
+        domainList.configure(DomainListConfiguration.builder()
+            .autoDetect(true)
+            .autoDetectIp(false));
 
         String detected = "detected.tld";
         when(dnsService.getLocalHost()).thenReturn(InetAddress.getByName("127.0.0.1"));
@@ -305,30 +285,25 @@ public class AbstractDomainListPrivateMethodsTest {
         String envDomain = "env.tld";
         when(envDetector.getEnv(AbstractDomainList.ENV_DOMAIN)).thenReturn(envDomain);
 
-        HierarchicalConfiguration configuration = mock(HierarchicalConfiguration.class);
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT, true)).thenReturn(true);
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT_IP, true)).thenReturn(false);
-        domainList.configure(configuration);
+
+        domainList.configure(DomainListConfiguration.builder()
+            .autoDetect(true)
+            .autoDetectIp(false));
 
         assertThat(domainList.containsDomain(Domain.of(envDomain))).isTrue();
     }
 
     @Test
     public void configuredDomainShouldBeAddedUponConfiguration() throws Exception {
-        String domain1 = "conf1.tld";
-        String domain2 = "conf2.tld";
-        String[] configuredDomain = new String[] {domain1, domain2};
+        Domain domain1 = Domain.of("conf1.tld");
+        Domain domain2 = Domain.of("conf2.tld");
 
-        HierarchicalConfiguration configuration = mock(HierarchicalConfiguration.class);
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT, null)).thenReturn(true);
-        when(configuration.getBoolean(AbstractDomainList.CONFIGURE_AUTODETECT_IP, null)).thenReturn(false);
-        when(configuration.getStringArray(AbstractDomainList.CONFIGURE_DOMAIN_NAMES)).thenReturn(configuredDomain);
-        domainList.configure(configuration);
+        domainList.configure(DomainListConfiguration.builder()
+            .autoDetect(false)
+            .autoDetectIp(false)
+            .addConfiguredDomains(domain1, domain2));
 
-        assertThat(domainList.getDomains())
-            .contains(
-                Domain.of(domain1),
-                Domain.of(domain2));
+        assertThat(domainList.getDomains()).contains(domain1, domain2);
     }
 
 }


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


[04/20] james-project git commit: JAMES-2506 Remove jmock from protocols-imap

Posted by bt...@apache.org.
http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/processor/GetQuotaRootProcessorTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/processor/GetQuotaRootProcessorTest.java b/protocols/imap/src/test/java/org/apache/james/imap/processor/GetQuotaRootProcessorTest.java
index bf1e169..a221e72 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/processor/GetQuotaRootProcessorTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/processor/GetQuotaRootProcessorTest.java
@@ -19,6 +19,15 @@
 
 package org.apache.james.imap.processor;
 
+import static org.apache.james.imap.api.message.response.StatusResponse.Type.OK;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.only;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.List;
 import java.util.Optional;
 
 import org.apache.james.core.quota.QuotaCount;
@@ -26,6 +35,7 @@ import org.apache.james.core.quota.QuotaSize;
 import org.apache.james.imap.api.ImapCommand;
 import org.apache.james.imap.api.ImapSessionState;
 import org.apache.james.imap.api.ImapSessionUtils;
+import org.apache.james.imap.api.message.response.ImapResponseMessage;
 import org.apache.james.imap.api.message.response.StatusResponse;
 import org.apache.james.imap.api.process.ImapProcessor;
 import org.apache.james.imap.api.process.ImapSession;
@@ -44,11 +54,9 @@ import org.apache.james.mailbox.model.QuotaRoot;
 import org.apache.james.mailbox.quota.QuotaManager;
 import org.apache.james.mailbox.quota.QuotaRootResolver;
 import org.apache.james.metrics.api.NoopMetricFactory;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
+import org.mockito.ArgumentCaptor;
 
 public class GetQuotaRootProcessorTest {
 
@@ -60,7 +68,6 @@ public class GetQuotaRootProcessorTest {
         Quota.<QuotaSize>builder().used(QuotaSize.size(240)).computedLimit(QuotaSize.size(15890)).build();
 
     private GetQuotaRootProcessor testee;
-    private Mockery mockery;
     private ImapSession mockedImapSession;
     private ImapProcessor.Responder mockedResponder;
     private QuotaManager mockedQuotaManager;
@@ -71,122 +78,86 @@ public class GetQuotaRootProcessorTest {
     @Before
     public void setUp() {
         mailboxSession = new MockMailboxSession("plop");
-        mockery = new JUnit4Mockery();
         UnpooledStatusResponseFactory statusResponseFactory = new UnpooledStatusResponseFactory();
-        mockedImapSession = mockery.mock(ImapSession.class);
-        mockedQuotaManager = mockery.mock(QuotaManager.class);
-        mockedQuotaRootResolver = mockery.mock(QuotaRootResolver.class);
-        mockedResponder = mockery.mock(ImapProcessor.Responder.class);
-        mockedMailboxManager = mockery.mock(MailboxManager.class);
-        testee = new GetQuotaRootProcessor(mockery.mock(ImapProcessor.class), mockedMailboxManager,
+        mockedImapSession = mock(ImapSession.class);
+        mockedQuotaManager = mock(QuotaManager.class);
+        mockedQuotaRootResolver = mock(QuotaRootResolver.class);
+        mockedResponder = mock(ImapProcessor.Responder.class);
+        mockedMailboxManager = mock(MailboxManager.class);
+        testee = new GetQuotaRootProcessor(mock(ImapProcessor.class), mockedMailboxManager,
             statusResponseFactory, mockedQuotaRootResolver, mockedQuotaManager, new NoopMetricFactory());
     }
 
     @Test
     public void processorShouldWorkOnValidRights() throws Exception {
         GetQuotaRootRequest getQuotaRootRequest = new GetQuotaRootRequest("A004", ImapCommand.anyStateCommand("Name"), "INBOX");
-        Expectations expectations = new Expectations();
 
-        expectations.allowing(mockedImapSession).getState();
-        expectations.will(Expectations.returnValue(ImapSessionState.AUTHENTICATED));
-
-        expectations.allowing(mockedImapSession).getAttribute(expectations.with(ImapSessionUtils.MAILBOX_SESSION_ATTRIBUTE_SESSION_KEY));
-        expectations.will(Expectations.returnValue(mailboxSession));
-
-        expectations.allowing(mockedQuotaRootResolver).getQuotaRoot(expectations.with(MAILBOX_PATH));
-        expectations.will(Expectations.returnValue(QUOTA_ROOT));
-
-        expectations.allowing(mockedMailboxManager).hasRight(expectations.with(MAILBOX_PATH),
-            expectations.with(MailboxACL.Right.Read), expectations.with(mailboxSession));
-        expectations.will(Expectations.returnValue(true));
-
-        expectations.allowing(mockedQuotaManager).getMessageQuota(expectations.with(QUOTA_ROOT));
-        expectations.will(Expectations.returnValue(MESSAGE_QUOTA));
-
-        expectations.allowing(mockedQuotaManager).getStorageQuota(expectations.with(QUOTA_ROOT));
-        expectations.will(Expectations.returnValue(STORAGE_QUOTA));
-
-        expectations.allowing(mockedMailboxManager).startProcessingRequest(expectations.with(mailboxSession));
-
-        expectations.allowing(mockedMailboxManager).endProcessingRequest(expectations.with(mailboxSession));
+        when(mockedImapSession.getState()).thenReturn(ImapSessionState.AUTHENTICATED);
+        when(mockedImapSession.getAttribute(ImapSessionUtils.MAILBOX_SESSION_ATTRIBUTE_SESSION_KEY)).thenReturn(mailboxSession);
+        when(mockedQuotaRootResolver.getQuotaRoot(MAILBOX_PATH)).thenReturn(QUOTA_ROOT);
+        when(mockedMailboxManager.hasRight(MAILBOX_PATH, MailboxACL.Right.Read, mailboxSession)).thenReturn(true);
+        when(mockedQuotaManager.getMessageQuota(QUOTA_ROOT)).thenReturn(MESSAGE_QUOTA);
+        when(mockedQuotaManager.getStorageQuota(QUOTA_ROOT)).thenReturn(STORAGE_QUOTA);
 
         final QuotaResponse storageQuotaResponse = new QuotaResponse("STORAGE", "plop", STORAGE_QUOTA);
         final QuotaResponse messageQuotaResponse = new QuotaResponse("MESSAGE", "plop", MESSAGE_QUOTA);
         final QuotaRootResponse quotaRootResponse = new QuotaRootResponse("INBOX", "plop");
 
-        mockery.checking(expectations);
+        testee.doProcess(getQuotaRootRequest, mockedResponder, mockedImapSession);
 
-        mockery.checking(new Expectations() {
-            {
-                oneOf(mockedResponder).respond(with(equal(quotaRootResponse)));
-                oneOf(mockedResponder).respond(with(equal(storageQuotaResponse)));
-                oneOf(mockedResponder).respond(with(equal(messageQuotaResponse)));
-                oneOf(mockedResponder).respond(with(new StatusResponseTypeMatcher(StatusResponse.Type.OK)));
-            }
-        });
+        verify(mockedMailboxManager, times(1)).startProcessingRequest(mailboxSession);
+        verify(mockedMailboxManager, times(1)).endProcessingRequest(mailboxSession);
 
-        testee.doProcess(getQuotaRootRequest, mockedResponder, mockedImapSession);
+        ArgumentCaptor<ImapResponseMessage> responseCaptor = ArgumentCaptor.forClass(ImapResponseMessage.class);
+        verify(mockedResponder, times(4)).respond(responseCaptor.capture());
+
+        List<ImapResponseMessage> captorValues = responseCaptor.getAllValues();
+        assertThat(captorValues).contains(quotaRootResponse, storageQuotaResponse, messageQuotaResponse);
+        assertThat(captorValues).anySatisfy(response -> assertThat(response).isInstanceOfSatisfying(
+            StatusResponse.class,
+            st -> assertThat(st.getServerResponseType()).isEqualTo(OK)));
     }
 
     @Test
     public void processorShouldWorkOnErrorThrown() throws Exception {
         GetQuotaRootRequest getQuotaRootRequest = new GetQuotaRootRequest("A004", ImapCommand.anyStateCommand("Name"), "INBOX");
-        Expectations expectations = new Expectations();
-
-        expectations.allowing(mockedImapSession).getState();
-        expectations.will(Expectations.returnValue(ImapSessionState.AUTHENTICATED));
 
-        expectations.allowing(mockedImapSession).getAttribute(expectations.with(ImapSessionUtils.MAILBOX_SESSION_ATTRIBUTE_SESSION_KEY));
-        expectations.will(Expectations.returnValue(mailboxSession));
-
-        expectations.allowing(mockedMailboxManager).hasRight(expectations.with(MAILBOX_PATH),
-            expectations.with(MailboxACL.Right.Read), expectations.with(mailboxSession));
-        expectations.will(Expectations.throwException(new MailboxException()));
-
-        expectations.allowing(mockedMailboxManager).startProcessingRequest(expectations.with(mailboxSession));
-
-        expectations.allowing(mockedMailboxManager).endProcessingRequest(expectations.with(mailboxSession));
+        when(mockedImapSession.getState()).thenReturn(ImapSessionState.AUTHENTICATED);
+        when(mockedImapSession.getAttribute(ImapSessionUtils.MAILBOX_SESSION_ATTRIBUTE_SESSION_KEY)).thenReturn(mailboxSession);
+        when(mockedMailboxManager.hasRight(MAILBOX_PATH, MailboxACL.Right.Read, mailboxSession)).thenThrow(new MailboxException());
 
+        testee.doProcess(getQuotaRootRequest, mockedResponder, mockedImapSession);
 
-        mockery.checking(expectations);
+        verify(mockedMailboxManager).startProcessingRequest(mailboxSession);
+        verify(mockedMailboxManager).endProcessingRequest(mailboxSession);
 
-        mockery.checking(new Expectations() {
-            {
-                oneOf(mockedResponder).respond(with(new StatusResponseTypeMatcher(StatusResponse.Type.BAD)));
-            }
-        });
+        ArgumentCaptor<StatusResponse> responseCaptor = ArgumentCaptor.forClass(StatusResponse.class);
+        verify(mockedResponder, only()).respond(responseCaptor.capture());
 
-        testee.doProcess(getQuotaRootRequest, mockedResponder, mockedImapSession);
+        assertThat(responseCaptor.getValue())
+            .extracting(StatusResponse::getServerResponseType)
+            .containsOnlyOnce(StatusResponse.Type.BAD);
     }
 
     @Test
     public void processorShouldWorkOnNonValidRights() throws Exception {
         GetQuotaRootRequest getQuotaRootRequest = new GetQuotaRootRequest("A004", ImapCommand.anyStateCommand("Name"), "INBOX");
-        Expectations expectations = new Expectations();
 
-        expectations.allowing(mockedImapSession).getState();
-        expectations.will(Expectations.returnValue(ImapSessionState.AUTHENTICATED));
+        when(mockedImapSession.getState()).thenReturn(ImapSessionState.AUTHENTICATED);
+        when(mockedImapSession.getAttribute(ImapSessionUtils.MAILBOX_SESSION_ATTRIBUTE_SESSION_KEY)).thenReturn(mailboxSession);
+        when(mockedMailboxManager.hasRight(MAILBOX_PATH, MailboxACL.Right.Read, mailboxSession)).thenReturn(false);
 
-        expectations.allowing(mockedImapSession).getAttribute(expectations.with(ImapSessionUtils.MAILBOX_SESSION_ATTRIBUTE_SESSION_KEY));
-        expectations.will(Expectations.returnValue(mailboxSession));
-
-        expectations.allowing(mockedMailboxManager).hasRight(expectations.with(MAILBOX_PATH),
-            expectations.with(MailboxACL.Right.Read), expectations.with(mailboxSession));
-        expectations.will(Expectations.returnValue(false));
-
-        expectations.allowing(mockedMailboxManager).startProcessingRequest(expectations.with(mailboxSession));
-
-        expectations.allowing(mockedMailboxManager).endProcessingRequest(expectations.with(mailboxSession));
+        testee.doProcess(getQuotaRootRequest, mockedResponder, mockedImapSession);
 
-        mockery.checking(expectations);
+        verify(mockedMailboxManager).startProcessingRequest(mailboxSession);
+        verify(mockedMailboxManager).endProcessingRequest(mailboxSession);
 
-        mockery.checking(new Expectations() {
-            {
-                oneOf(mockedResponder).respond(with(new StatusResponseTypeMatcher(StatusResponse.Type.NO)));
-            }
-        });
+        ArgumentCaptor<StatusResponse> responseCaptor = ArgumentCaptor.forClass(StatusResponse.class);
+        verify(mockedResponder, only()).respond(responseCaptor.capture());
 
-        testee.doProcess(getQuotaRootRequest, mockedResponder, mockedImapSession);
+        assertThat(responseCaptor.getValue())
+            .extracting(StatusResponse::getServerResponseType)
+            .containsOnlyOnce(StatusResponse.Type.NO);
     }
 
 }

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/processor/LSubProcessorTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/processor/LSubProcessorTest.java b/protocols/imap/src/test/java/org/apache/james/imap/processor/LSubProcessorTest.java
index 67d7414..648d139 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/processor/LSubProcessorTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/processor/LSubProcessorTest.java
@@ -19,6 +19,12 @@
 
 package org.apache.james.imap.processor;
 
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.same;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
@@ -38,9 +44,6 @@ import org.apache.james.mailbox.MailboxSession;
 import org.apache.james.mailbox.SubscriptionManager;
 import org.apache.james.mailbox.model.MailboxMetaData;
 import org.apache.james.metrics.api.NoopMetricFactory;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -90,45 +93,32 @@ public class LSubProcessorTest {
     };
 
     LSubProcessor processor;
-
     ImapProcessor next;
-
     SubscriptionManager manager;
-
     ImapProcessor.Responder responder;
-
     MailboxMetaData result;
-
     ImapSession session;
-    
     MailboxSession mailboxSession;
-
     StatusResponseFactory serverResponseFactory;
-
     StatusResponse statusResponse;
-
     Collection<String> subscriptions;
-
     ImapCommand command;
-
     private ImapProcessor.Responder responderImpl;
 
-    private Mockery mockery = new JUnit4Mockery();
-    
     @Before
     public void setUp() throws Exception {
         subscriptions = new ArrayList<>();
-        serverResponseFactory = mockery.mock(StatusResponseFactory.class);
-        session = mockery.mock(ImapSession.class);
+        serverResponseFactory = mock(StatusResponseFactory.class);
+        session = mock(ImapSession.class);
         command = ImapCommand.anyStateCommand("Command");
-        next = mockery.mock(ImapProcessor.class);
-        responder = mockery.mock(ImapProcessor.Responder.class);
-        result = mockery.mock(MailboxMetaData.class);
-        statusResponse = mockery.mock(StatusResponse.class);
+        next = mock(ImapProcessor.class);
+        responder = mock(ImapProcessor.Responder.class);
+        result = mock(MailboxMetaData.class);
+        statusResponse = mock(StatusResponse.class);
         responderImpl = responder;
-        manager = mockery. mock(SubscriptionManager.class);
-        mailboxSession = mockery.mock(MailboxSession.class);
-        processor = new LSubProcessor(next, mockery.mock(MailboxManager.class), manager, serverResponseFactory, new NoopMetricFactory());
+        manager =  mock(SubscriptionManager.class);
+        mailboxSession = mock(MailboxSession.class);
+        processor = new LSubProcessor(next, mock(MailboxManager.class), manager, serverResponseFactory, new NoopMetricFactory());
     }
 
     @Test
@@ -140,23 +130,19 @@ public class LSubProcessorTest {
         subscriptions.add(CHILD_ONE);
         subscriptions.add(CHILD_TWO);
 
-        mockery.checking(new Expectations() {{
-                    oneOf(mailboxSession).getUser(); will(returnValue(USER));
-                    oneOf(responder).respond(with(
-                            equal(new LSubResponse(CHILD_ONE, false, HIERARCHY_DELIMITER))));
-                    oneOf(responder).respond(with(
-                            equal(new LSubResponse(CHILD_TWO, false, HIERARCHY_DELIMITER))));
-                }
-            }
-        );
-        
+        when(mailboxSession.getUser()).thenReturn(USER);
+
         expectSubscriptions();
-        expectOk();
+        when(serverResponseFactory.taggedOk(eq(TAG), same(command), eq(HumanReadableText.COMPLETED)))
+            .thenReturn(statusResponse);
 
         LsubRequest request = new LsubRequest(command, "", PARENT
                 + HIERARCHY_DELIMITER + "%", TAG);
         processor.doProcessRequest(request, session, TAG, command, responderImpl);
 
+        verify(responder).respond(new LSubResponse(CHILD_ONE, false, HIERARCHY_DELIMITER));
+        verify(responder).respond(new LSubResponse(CHILD_TWO, false, HIERARCHY_DELIMITER));
+        verify(responder).respond(statusResponse);
     }
 
     @Test
@@ -168,21 +154,18 @@ public class LSubProcessorTest {
         subscriptions.add(CHILD_ONE);
         subscriptions.add(CHILD_TWO);
 
-        mockery.checking(new Expectations() {{
-                    oneOf(mailboxSession).getUser(); will(returnValue(USER));
-                    oneOf(responder).respond(with(
-                            equal(new LSubResponse(PARENT, true, HIERARCHY_DELIMITER))));
-                }
-            }
-        );
+        when(mailboxSession.getUser()).thenReturn(USER);
 
         expectSubscriptions();
-        expectOk();
+        when(serverResponseFactory.taggedOk(eq(TAG), same(command), eq(HumanReadableText.COMPLETED)))
+            .thenReturn(statusResponse);
 
         LsubRequest request = new LsubRequest(command, "", ROOT
                 + HIERARCHY_DELIMITER + "%", TAG);
         processor.doProcessRequest(request, session, TAG, command, responderImpl);
 
+        verify(responder).respond(new LSubResponse(PARENT, true, HIERARCHY_DELIMITER));
+        verify(responder).respond(statusResponse);
     }
 
     @Test
@@ -195,70 +178,43 @@ public class LSubProcessorTest {
         subscriptions.add(CHILD_ONE);
         subscriptions.add(CHILD_TWO);
 
-        mockery.checking(new Expectations() {{
-                    oneOf(mailboxSession).getUser(); will(returnValue(USER));
-                    oneOf(responder).respond(with(
-                            equal(new LSubResponse(PARENT, false, HIERARCHY_DELIMITER))));
-                }
-            }
-        );
+        when(mailboxSession.getUser()).thenReturn(USER);
 
         expectSubscriptions();
-        expectOk();
+        when(serverResponseFactory.taggedOk(eq(TAG), same(command), eq(HumanReadableText.COMPLETED)))
+            .thenReturn(statusResponse);
 
         LsubRequest request = new LsubRequest(command, "", ROOT
                 + HIERARCHY_DELIMITER + "%", TAG);
         processor.doProcessRequest(request, session, TAG, command, responderImpl);
 
+        verify(responder).respond(new LSubResponse(PARENT, false, HIERARCHY_DELIMITER));
+        verify(responder).respond(statusResponse);
     }
 
     @Test
     public void testSelectAll() throws Exception {
-        mockery.checking(new Expectations() {{
-                    oneOf(mailboxSession).getUser(); will(returnValue(USER));
-                    oneOf(responder).respond(with(equal(
-                            new LSubResponse(MAILBOX_A, false, HIERARCHY_DELIMITER))));
-                    oneOf(responder).respond(with(equal(
-                            new LSubResponse(MAILBOX_B, false, HIERARCHY_DELIMITER))));
-                    oneOf(responder).respond(with(equal(
-                            new LSubResponse(MAILBOX_C, false, HIERARCHY_DELIMITER))));
-                }
-            }
-        );
         subscriptions.add(MAILBOX_A);
         subscriptions.add(MAILBOX_B);
         subscriptions.add(MAILBOX_C);
 
+        when(mailboxSession.getUser()).thenReturn(USER);
         expectSubscriptions();
-        expectOk();
+        when(serverResponseFactory.taggedOk(eq(TAG), same(command), eq(HumanReadableText.COMPLETED)))
+            .thenReturn(statusResponse);
 
         LsubRequest request = new LsubRequest(command, "", "*", TAG);
         processor.doProcessRequest(request, session, TAG, command, responderImpl);
 
-    }
-
-    
-    private void expectOk() {
-        mockery.checking(new Expectations() {{
-                    oneOf(serverResponseFactory).taggedOk(
-                            with(equal(TAG)),
-                            with(same(command)),
-                            with(equal(HumanReadableText.COMPLETED)));will(returnValue(statusResponse));
-                    oneOf(responder).respond(with(same(statusResponse)));          
-                }
-            }
-        );
+        verify(responder).respond(new LSubResponse(MAILBOX_A, false, HIERARCHY_DELIMITER));
+        verify(responder).respond(new LSubResponse(MAILBOX_B, false, HIERARCHY_DELIMITER));
+        verify(responder).respond(new LSubResponse(MAILBOX_C, false, HIERARCHY_DELIMITER));
+        verify(responder).respond(statusResponse);
     }
 
     private void expectSubscriptions() throws Exception {
-        mockery.checking(new Expectations() {{
-                    exactly(2).of(session).getAttribute(ImapSessionUtils.MAILBOX_SESSION_ATTRIBUTE_SESSION_KEY);
-                            will(returnValue(mailboxSession));
-                            allowing(mailboxSession).getPathDelimiter(); will(returnValue(HIERARCHY_DELIMITER));
-                    oneOf(mailboxSession).getUser(); will(returnValue(USER));
-                    oneOf(manager).subscriptions(with(same(mailboxSession)));will(returnValue(subscriptions));     
-                }
-            }
-        );
+        when(session.getAttribute(ImapSessionUtils.MAILBOX_SESSION_ATTRIBUTE_SESSION_KEY)).thenReturn(mailboxSession);
+        when(mailboxSession.getPathDelimiter()).thenReturn(HIERARCHY_DELIMITER);
+        when(manager.subscriptions(mailboxSession)).thenReturn(subscriptions);
     }
 }

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/processor/MoveProcessorTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/processor/MoveProcessorTest.java b/protocols/imap/src/test/java/org/apache/james/imap/processor/MoveProcessorTest.java
index 0a6d718..fd9785b 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/processor/MoveProcessorTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/processor/MoveProcessorTest.java
@@ -236,7 +236,7 @@ public class MoveProcessorTest {
     }
 
     @Test
-    public void processShouldNotHandleCopyRequests() throws Exception {
+    public void processShouldNotHandleCopyRequests() {
         CopyRequest copyRequest = new CopyRequest(ImapCommand.anyStateCommand("Name"), new IdRange[] {new IdRange(4, 6)}, ImapConstants.INBOX_NAME, true, TAG);
 
         testee.process(copyRequest, mockResponder, mockImapSession);

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/processor/NamespaceProcessorTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/processor/NamespaceProcessorTest.java b/protocols/imap/src/test/java/org/apache/james/imap/processor/NamespaceProcessorTest.java
index 5ba4461..b6162e6 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/processor/NamespaceProcessorTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/processor/NamespaceProcessorTest.java
@@ -18,6 +18,14 @@
  ****************************************************************/
 package org.apache.james.imap.processor;
 
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
@@ -28,7 +36,6 @@ import org.apache.james.imap.api.ImapSessionState;
 import org.apache.james.imap.api.ImapSessionUtils;
 import org.apache.james.imap.api.display.HumanReadableText;
 import org.apache.james.imap.api.message.response.StatusResponse;
-import org.apache.james.imap.api.message.response.StatusResponse.ResponseCode;
 import org.apache.james.imap.api.message.response.StatusResponseFactory;
 import org.apache.james.imap.api.process.ImapProcessor;
 import org.apache.james.imap.api.process.ImapProcessor.Responder;
@@ -39,9 +46,6 @@ import org.apache.james.mailbox.MailboxManager;
 import org.apache.james.mailbox.MailboxSession;
 import org.apache.james.mailbox.model.MailboxConstants;
 import org.apache.james.metrics.api.NoopMetricFactory;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -56,92 +60,74 @@ public class NamespaceProcessorTest {
     StatusResponseFactory statusResponseStub;
     ImapSession imapSessionStub;
     MailboxSession mailboxSessionStub;
-    String personalSpaceStub;
-    String usersSpaceStub;
-    String sharedSpaceStub;
     NamespaceRequest namespaceRequest;
     Collection<String> sharedSpaces;
     MailboxManager mailboxManagerStub;
-    Mockery mockery = new JUnit4Mockery();
-    
+
     @Before
     public void setUp() throws Exception {
         sharedSpaces = new ArrayList<>();
-        statusResponseStub = mockery.mock(StatusResponseFactory.class);
-        mailboxManagerStub = mockery.mock(MailboxManager.class);
-        subject = new NamespaceProcessor(mockery.mock(ImapProcessor.class), mailboxManagerStub, statusResponseStub, new NoopMetricFactory());
-        imapSessionStub = mockery.mock(ImapSession.class);
-        mailboxSessionStub = mockery.mock(MailboxSession.class);
+        statusResponseStub = mock(StatusResponseFactory.class);
+        mailboxManagerStub = mock(MailboxManager.class);
+        subject = new NamespaceProcessor(mock(ImapProcessor.class), mailboxManagerStub, statusResponseStub, new NoopMetricFactory());
+        imapSessionStub = mock(ImapSession.class);
+        mailboxSessionStub = mock(MailboxSession.class);
      
         namespaceRequest = new NamespaceRequest(ImapCommand.anyStateCommand("Name"), "TAG");
        
     }
-    
 
-    
     @Test
-    public void testNamespaceResponseShouldContainPersonalAndUserSpaces() throws Exception {
-        mockery.checking(new Expectations() {{
-                    allowing(imapSessionStub).supportMultipleNamespaces(); will(returnValue(true));
-                    allowing(imapSessionStub).getAttribute(ImapSessionUtils.MAILBOX_SESSION_ATTRIBUTE_SESSION_KEY); will(returnValue(mailboxSessionStub));
-                    allowing(imapSessionStub).getAttribute(EnableProcessor.ENABLED_CAPABILITIES); will(returnValue(null));
-                    allowing(any(ImapSession.class)).method("setAttribute");
-        
-                    allowing(mailboxSessionStub).getPersonalSpace(); will(returnValue(PERSONAL_PREFIX));
-                    allowing(mailboxSessionStub).getOtherUsersSpace(); will(returnValue(USERS_PREFIX));
-                    allowing(mailboxSessionStub).getSharedSpaces();will(returnValue(new ArrayList<String>()));
-                    allowing(mailboxSessionStub).getPathDelimiter();will(returnValue(MailboxConstants.DEFAULT_DELIMITER));
-                    allowing(imapSessionStub).getState();will(returnValue(ImapSessionState.AUTHENTICATED));
-                    allowing(statusResponseStub).taggedOk(
-                            with(any(String.class)), with(any(ImapCommand.class)), 
-                            with(any(HumanReadableText.class)), with(any(ResponseCode.class))); will(returnValue(mockery.mock(StatusResponse.class)));
-                    ignoring(imapSessionStub);
-                    ignoring(mailboxSessionStub);
-                    ignoring(mailboxManagerStub);
-                    ignoring(statusResponseStub);
-                }
-            }
-        );
-        
+    public void testNamespaceResponseShouldContainPersonalAndUserSpaces() {
+        when(imapSessionStub.supportMultipleNamespaces()).thenReturn(true);
+        when(imapSessionStub.getAttribute(ImapSessionUtils.MAILBOX_SESSION_ATTRIBUTE_SESSION_KEY)).thenReturn(mailboxSessionStub);
+        when(imapSessionStub.getAttribute(EnableProcessor.ENABLED_CAPABILITIES)).thenReturn(null);
+
+        when(mailboxSessionStub.getPersonalSpace()).thenReturn(PERSONAL_PREFIX);
+        when(mailboxSessionStub.getOtherUsersSpace()).thenReturn(USERS_PREFIX);
+        when(mailboxSessionStub.getSharedSpaces()).thenReturn(new ArrayList<>());
+        when(mailboxSessionStub.getPathDelimiter()).thenReturn(MailboxConstants.DEFAULT_DELIMITER);
+
+        when(imapSessionStub.getState()).thenReturn(ImapSessionState.AUTHENTICATED);
+        when(statusResponseStub.taggedOk(anyString(), any(ImapCommand.class), any(HumanReadableText.class)))
+            .thenReturn(mock(StatusResponse.class));
+
         final NamespaceResponse response = buildResponse(null);
-        
-        final Responder responderMock = expectResponse(response);
-        
+        final Responder responderMock = mock(Responder.class);
+
         subject.doProcess(namespaceRequest, responderMock, imapSessionStub);
+
+        verify(responderMock, times(1)).respond(response);
+        verify(responderMock, times(1)).respond(any(StatusResponse.class));
+        verifyNoMoreInteractions(responderMock);
     }
     
     @Test
-    public void testNamespaceResponseShouldContainSharedSpaces() throws Exception {
-        mockery.checking(new Expectations() {{
-                    allowing(imapSessionStub).supportMultipleNamespaces(); will(returnValue(true));
-                    allowing(imapSessionStub).getAttribute(ImapSessionUtils.MAILBOX_SESSION_ATTRIBUTE_SESSION_KEY); will(returnValue(mailboxSessionStub));
-                    allowing(imapSessionStub).getAttribute(EnableProcessor.ENABLED_CAPABILITIES); will(returnValue(null));
-                    allowing(any(ImapSession.class)).method("setAttribute");
-                    allowing(mailboxSessionStub).getPersonalSpace(); will(returnValue(PERSONAL_PREFIX));
-                    allowing(mailboxSessionStub).getOtherUsersSpace(); will(returnValue(USERS_PREFIX));
-                    allowing(mailboxSessionStub).getSharedSpaces();will(returnValue(Arrays.asList(SHARED_PREFIX)));
-                    allowing(mailboxSessionStub).getPathDelimiter();will(returnValue(MailboxConstants.DEFAULT_DELIMITER));
-                    allowing(imapSessionStub).getState();will(returnValue(ImapSessionState.AUTHENTICATED));
-                    allowing(statusResponseStub).taggedOk(
-                            with(any(String.class)), with(any(ImapCommand.class)), 
-                            with(any(HumanReadableText.class)), with(any(ResponseCode.class))); will(returnValue(mockery.mock(StatusResponse.class)));
-                    ignoring(imapSessionStub);
-                    ignoring(mailboxSessionStub);
-                    ignoring(mailboxManagerStub);
-                    ignoring(statusResponseStub);
-                }
-            }
-        );
-        this.sharedSpaces.add(sharedSpaceStub);
-        
+    public void testNamespaceResponseShouldContainSharedSpaces() {
+        when(imapSessionStub.supportMultipleNamespaces()).thenReturn(true);
+        when(imapSessionStub.getAttribute(ImapSessionUtils.MAILBOX_SESSION_ATTRIBUTE_SESSION_KEY)).thenReturn(mailboxSessionStub);
+        when(imapSessionStub.getAttribute(EnableProcessor.ENABLED_CAPABILITIES)).thenReturn(null);
+
+        when(mailboxSessionStub.getPersonalSpace()).thenReturn(PERSONAL_PREFIX);
+        when(mailboxSessionStub.getOtherUsersSpace()).thenReturn(USERS_PREFIX);
+        when(mailboxSessionStub.getSharedSpaces()).thenReturn(Arrays.asList(SHARED_PREFIX));
+        when(mailboxSessionStub.getPathDelimiter()).thenReturn(MailboxConstants.DEFAULT_DELIMITER);
+
+        when(imapSessionStub.getState()).thenReturn(ImapSessionState.AUTHENTICATED);
+        when(statusResponseStub.taggedOk(anyString(), any(ImapCommand.class), any(HumanReadableText.class)))
+            .thenReturn(mock(StatusResponse.class));
         
         final List<NamespaceResponse.Namespace> sharedSpaces = new ArrayList<>();
         sharedSpaces.add(new NamespaceResponse.Namespace(SHARED_PREFIX, MailboxConstants.DEFAULT_DELIMITER));
         final NamespaceResponse response = buildResponse(sharedSpaces);
         
-        final Responder responderMock = expectResponse(response);
-        
+        final Responder responderMock = mock(Responder.class);
+
         subject.doProcess(namespaceRequest, responderMock, imapSessionStub);
+
+        verify(responderMock, times(1)).respond(response);
+        verify(responderMock, times(1)).respond(any(StatusResponse.class));
+        verifyNoMoreInteractions(responderMock);
     }
 
     private NamespaceResponse buildResponse(List<NamespaceResponse.Namespace> sharedSpaces) {
@@ -153,16 +139,5 @@ public class NamespaceProcessorTest {
 
         return new NamespaceResponse(personalSpaces, otherUsersSpaces, sharedSpaces);
     }
-
-    private Responder expectResponse(final NamespaceResponse response) {
-        final Responder responderMock = mockery.mock(Responder.class);
-        mockery.checking(new Expectations() {{
-                    oneOf(responderMock).respond(with(equal(response)));
-                    oneOf(responderMock).respond(with(any(StatusResponse.class)));
-                }
-            }
-        );
-        return responderMock;
-    }
 }
 

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/processor/SearchProcessorTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/processor/SearchProcessorTest.java b/protocols/imap/src/test/java/org/apache/james/imap/processor/SearchProcessorTest.java
index 4e468a8..ccf2cb1 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/processor/SearchProcessorTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/processor/SearchProcessorTest.java
@@ -19,6 +19,12 @@
 
 package org.apache.james.imap.processor;
 
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.same;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
 import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.Collections;
@@ -27,6 +33,7 @@ import java.util.List;
 import java.util.Locale;
 import java.util.Optional;
 import java.util.TimeZone;
+
 import javax.mail.Flags;
 import javax.mail.Flags.Flag;
 
@@ -56,10 +63,7 @@ import org.apache.james.mailbox.model.SearchQuery.AddressType;
 import org.apache.james.mailbox.model.SearchQuery.Criterion;
 import org.apache.james.mailbox.model.SearchQuery.DateResolution;
 import org.apache.james.metrics.api.NoopMetricFactory;
-
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
+import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -97,55 +101,42 @@ public class SearchProcessorTest {
     private static final MailboxPath mailboxPath = new MailboxPath("namespace", "user", "name");
 
     SearchProcessor processor;
-
     ImapProcessor next;
-
     ImapProcessor.Responder responder;
-
     ImapSession session;
-
     ImapCommand command;
-
     StatusResponseFactory serverResponseFactory;
-
     StatusResponse statusResponse;
-
     MessageManager mailbox;
-    
     MailboxManager mailboxManager;
-    
     MailboxSession mailboxSession;
-
     SelectedMailbox selectedMailbox;
 
-    private Mockery mockery = new JUnit4Mockery();
-
     @Before
     public void setUp() throws Exception {
-        serverResponseFactory = mockery.mock(StatusResponseFactory.class);
-        session = mockery.mock(ImapSession.class);
+        serverResponseFactory = mock(StatusResponseFactory.class);
+        session = mock(ImapSession.class);
         command = ImapCommand.anyStateCommand("Command");
-        next = mockery.mock(ImapProcessor.class);
-        responder = mockery.mock(ImapProcessor.Responder.class);
-        statusResponse = mockery.mock(StatusResponse.class);
-        mailbox = mockery.mock(MessageManager.class);
-        mailboxManager = mockery.mock(MailboxManager.class);
-        mailboxSession = mockery.mock(MailboxSession.class);
-        selectedMailbox = mockery.mock(SelectedMailbox.class);
+        next = mock(ImapProcessor.class);
+        responder = mock(ImapProcessor.Responder.class);
+        statusResponse = mock(StatusResponse.class);
+        mailbox = mock(MessageManager.class);
+        mailboxManager = mock(MailboxManager.class);
+        mailboxSession = mock(MailboxSession.class);
+        selectedMailbox = mock(SelectedMailbox.class);
         
         processor = new SearchProcessor(next,  mailboxManager, serverResponseFactory, new NoopMetricFactory());
         expectOk();
     }
 
+    @After
+    public void afterEach() {
+        verifyCalls();
+    }
+
     private void allowUnsolicitedResponses() {
-        mockery.checking(new Expectations() {{
-                    atMost(1).of(session).getAttribute(
-                            with(equal(ImapSessionUtils.MAILBOX_USER_ATTRIBUTE_SESSION_KEY)));will(returnValue("user"));
-                    atMost(1).of(session).getAttribute(
-                            with(equal(ImapSessionUtils.MAILBOX_SESSION_ATTRIBUTE_SESSION_KEY)));will(returnValue(mailboxSession));
-                }
-            }
-        );
+        when(session.getAttribute(ImapSessionUtils.MAILBOX_USER_ATTRIBUTE_SESSION_KEY)).thenReturn("user");
+        when(session.getAttribute(ImapSessionUtils.MAILBOX_SESSION_ATTRIBUTE_SESSION_KEY)).thenReturn(mailboxSession);
     }
 
     @Test
@@ -153,14 +144,12 @@ public class SearchProcessorTest {
         expectsGetSelectedMailbox();
         final IdRange[] ids = { new IdRange(1, Long.MAX_VALUE) };
         final SearchQuery.UidRange[] ranges = { new SearchQuery.UidRange(MessageUid.of(42), MessageUid.of(100)) };
-        mockery.checking(new Expectations() {{
-                    allowing(selectedMailbox).existsCount();will(returnValue(100L));
-                    oneOf(selectedMailbox).uid(with(equal(1)));will(returnValue(Optional.of(MessageUid.of(42))));
-                    allowing(selectedMailbox).getFirstUid(); will(returnValue(Optional.of(MessageUid.of(1))));
-                    allowing(selectedMailbox).getLastUid(); will(returnValue(Optional.of(MessageUid.of(100))));
-                }
-            }
-        );
+
+        when(selectedMailbox.existsCount()).thenReturn(100L);
+        when(selectedMailbox.uid(1)).thenReturn(Optional.of(MessageUid.of(42L)));
+        when(selectedMailbox.getFirstUid()).thenReturn(Optional.of(MessageUid.of(1L)));
+        when(selectedMailbox.getLastUid()).thenReturn(Optional.of(MessageUid.of(100L)));
+
         allowUnsolicitedResponses();
         check(SearchKey.buildSequenceSet(ids), SearchQuery.uid(ranges));
     }
@@ -170,15 +159,13 @@ public class SearchProcessorTest {
         expectsGetSelectedMailbox();
         final IdRange[] ids = { new IdRange(1, 5) };
         final SearchQuery.UidRange[] ranges = { new SearchQuery.UidRange(MessageUid.of(42), MessageUid.of(1729)) };
-        mockery.checking(new Expectations() {{
-                    allowing(selectedMailbox).existsCount();will(returnValue(2L));
-                    oneOf(selectedMailbox).uid(with(equal(1)));will(returnValue(Optional.of(MessageUid.of(42L))));
-                    oneOf(selectedMailbox).uid(with(equal(5)));will(returnValue(Optional.of(MessageUid.of(1729L))));
-                    allowing(selectedMailbox).getFirstUid(); will(returnValue(Optional.of(MessageUid.of(1L))));
-                    allowing(selectedMailbox).getLastUid(); will(returnValue(Optional.of(MessageUid.MAX_VALUE)));
-                }
-            }
-        );
+
+        when(selectedMailbox.existsCount()).thenReturn(100L);
+        when(selectedMailbox.uid(1)).thenReturn(Optional.of(MessageUid.of(42L)));
+        when(selectedMailbox.uid(5)).thenReturn(Optional.of(MessageUid.of(1729L)));
+        when(selectedMailbox.getFirstUid()).thenReturn(Optional.of(MessageUid.of(1L)));
+        when(selectedMailbox.getLastUid()).thenReturn(Optional.of(MessageUid.MAX_VALUE));
+
         allowUnsolicitedResponses();
         check(SearchKey.buildSequenceSet(ids), SearchQuery.uid(ranges));
     }
@@ -188,12 +175,10 @@ public class SearchProcessorTest {
         expectsGetSelectedMailbox();
         final IdRange[] ids = { new IdRange(1) };
         final SearchQuery.UidRange[] ranges = { new SearchQuery.UidRange(MessageUid.of(42)) };
-        mockery.checking(new Expectations() {{
-                    allowing(selectedMailbox).existsCount();will(returnValue(1L));
-                    exactly(2).of(selectedMailbox).uid(with(equal(1)));will(returnValue(Optional.of(MessageUid.of(42L))));
-                }
-            }
-        );
+
+        when(selectedMailbox.existsCount()).thenReturn(1L);
+        when(selectedMailbox.uid(1)).thenReturn(Optional.of(MessageUid.of(42L)));
+
         allowUnsolicitedResponses();
         check(SearchKey.buildSequenceSet(ids), SearchQuery.uid(ranges));
     }
@@ -205,23 +190,15 @@ public class SearchProcessorTest {
     }
 
     private void expectsGetSelectedMailbox() throws Exception {
-        mockery.checking(new Expectations() {{
-                    atMost(1).of(mailboxManager).getMailbox(with(equal(mailboxPath)),  with(same(mailboxSession)));will(returnValue(mailbox));
-                    atMost(1).of(mailboxManager).getMailbox(with(equal(mailboxPath)), with(same(mailboxSession)));will(returnValue(mailbox));
-                    allowing(session).getSelected();will(returnValue(selectedMailbox));
-                    atMost(1).of(selectedMailbox).isRecentUidRemoved();will(returnValue(false));
-                    atLeast(1).of(selectedMailbox).isSizeChanged();will(returnValue(false));
-                    atLeast(1).of(selectedMailbox).getPath();will(returnValue(mailboxPath));
-                    atMost(1).of(selectedMailbox).flagUpdateUids();will(returnValue(Collections.EMPTY_LIST));
-                    atMost(1).of(selectedMailbox).resetEvents();
-                    
-                    oneOf(selectedMailbox).getRecent();will(returnValue(new ArrayList<MessageUid>()));
-                }
-            }
-        );
+        when(mailboxManager.getMailbox(mailboxPath, mailboxSession)).thenReturn(mailbox, mailbox);
+        when(session.getSelected()).thenReturn(selectedMailbox);
+        when(selectedMailbox.isRecentUidRemoved()).thenReturn(false);
+        when(selectedMailbox.isSizeChanged()).thenReturn(false);
+        when(selectedMailbox.getPath()).thenReturn(mailboxPath);
+        when(selectedMailbox.flagUpdateUids()).thenReturn(Collections.EMPTY_LIST);
+        when(selectedMailbox.getRecent()).thenReturn(new ArrayList<>());
     }
 
-
     private Calendar getGMT() {
         return Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.UK);
     }
@@ -428,14 +405,11 @@ public class SearchProcessorTest {
 
     @Test
     public void testUID() throws Exception {
-        mockery.checking(new Expectations() {{
-                    allowing(selectedMailbox).getFirstUid();will(returnValue(Optional.of(MessageUid.of(1))));
-                    allowing(selectedMailbox).getLastUid();will(returnValue(Optional.of(MessageUid.of(1048))));
-                    allowing(selectedMailbox).existsCount();will(returnValue(1L));
-                }
-            }
-        );
-        expectsGetSelectedMailbox();            
+        when(selectedMailbox.getFirstUid()).thenReturn(Optional.of(MessageUid.of(1)));
+        when(selectedMailbox.getLastUid()).thenReturn(Optional.of(MessageUid.of(1048)));
+        when(selectedMailbox.existsCount()).thenReturn(1L);
+
+        expectsGetSelectedMailbox();
 
         check(SearchKey.buildUidSet(IDS), SearchQuery.uid(RANGES));
     }
@@ -486,37 +460,29 @@ public class SearchProcessorTest {
         check(key, query);
     }
 
-    private void check(SearchKey key, final SearchQuery query) throws Exception {        
-        mockery.checking(new Expectations() {{
-                    allowing(session).getAttribute(
-                            with(equal(SearchProcessor.SEARCH_MODSEQ))); will(returnValue(null));
-                    allowing(session).setAttribute(SearchProcessor.SEARCH_MODSEQ, null);
-                    allowing(session).getAttribute(
-                            with(equal(ImapSessionUtils.MAILBOX_SESSION_ATTRIBUTE_SESSION_KEY))); will(returnValue((MailboxSession) mailboxSession));
-                    oneOf(mailbox).search(
-                            with(equal(query)),
-                            with(equal(mailboxSession)));will(
-                                    returnValue(new ArrayList<MessageUid>().iterator()));
-                    oneOf(responder).respond(with(equal(new SearchResponse(EMPTY, null))));
-                    allowing(selectedMailbox).getApplicableFlags(); will(returnValue(new Flags()));
-                    allowing(selectedMailbox).hasNewApplicableFlags(); will(returnValue(false));
-                  
-                }
-            }
-        );
+    private void check(SearchKey key, final SearchQuery query) throws Exception {
+        when(session.getAttribute(SearchProcessor.SEARCH_MODSEQ)).thenReturn(null);
+        when(session.getAttribute(ImapSessionUtils.MAILBOX_SESSION_ATTRIBUTE_SESSION_KEY)).thenReturn(mailboxSession);
+        when(mailbox.search(query, mailboxSession)).thenReturn(new ArrayList<MessageUid>().iterator());
+        when(selectedMailbox.getApplicableFlags()).thenReturn(new Flags());
+        when(selectedMailbox.hasNewApplicableFlags()).thenReturn(false);
+
         SearchRequest message = new SearchRequest(command, new SearchOperation(key, new ArrayList<>()), false, TAG);
         processor.doProcess(message, session, TAG, command, responder);
     }
 
     private void expectOk() {
-        mockery.checking(new Expectations() {{
-                    oneOf(serverResponseFactory).taggedOk(
-                            with(equal(TAG)),
-                            with(same(command)), 
-                            with(equal(HumanReadableText.COMPLETED)));will(returnValue(statusResponse));    
-                    oneOf(responder).respond(with(same(statusResponse)));
-                }
-            }
-        );
+        when(serverResponseFactory
+                .taggedOk(eq(TAG), same(command), eq(HumanReadableText.COMPLETED)))
+            .thenReturn(statusResponse);
+    }
+
+    private void verifyCalls() {
+        verify(selectedMailbox).resetEvents();
+
+        verify(session).setAttribute(SearchProcessor.SEARCH_MODSEQ, null);
+        verify(responder).respond(new SearchResponse(EMPTY, null));
+
+        verify(responder).respond(same(statusResponse));
     }
 }

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/processor/SetQuotaProcessorTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/processor/SetQuotaProcessorTest.java b/protocols/imap/src/test/java/org/apache/james/imap/processor/SetQuotaProcessorTest.java
index 91337c6..4f6340e 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/processor/SetQuotaProcessorTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/processor/SetQuotaProcessorTest.java
@@ -60,7 +60,7 @@ public class SetQuotaProcessorTest {
     }
 
     @Test
-    public void processorShouldWorkOnNoRights() throws Exception {
+    public void processorShouldWorkOnNoRights() {
         SetQuotaRequest setQuotaRequest = new SetQuotaRequest("A004", ImapCommand.anyStateCommand("Name"), "quotaRoot");
 
         when(mockedImapSession.getState()).thenReturn(ImapSessionState.AUTHENTICATED);

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/processor/base/MailboxEventAnalyserTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/processor/base/MailboxEventAnalyserTest.java b/protocols/imap/src/test/java/org/apache/james/imap/processor/base/MailboxEventAnalyserTest.java
index 0f797a7..87f7c76 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/processor/base/MailboxEventAnalyserTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/processor/base/MailboxEventAnalyserTest.java
@@ -119,7 +119,7 @@ public class MailboxEventAnalyserTest {
     }
 
     @Test
-    public void testShouldBeNoSizeChangeOnOtherEvent() throws Exception {
+    public void testShouldBeNoSizeChangeOnOtherEvent() {
         MailboxListener.MailboxEvent event = new MailboxListener.MailboxEvent(MAILBOX_SESSION, MAILBOX_PATH) {};
       
         testee.event(event);
@@ -128,13 +128,13 @@ public class MailboxEventAnalyserTest {
     }
 
     @Test
-    public void testShouldBeNoSizeChangeOnAdded() throws Exception {
+    public void testShouldBeNoSizeChangeOnAdded() {
         testee.event(new FakeMailboxListenerAdded(MAILBOX_SESSION, ImmutableList.of(MessageUid.of(11)), MAILBOX_PATH));
         assertThat(testee.isSizeChanged()).isTrue();
     }
 
     @Test
-    public void testShouldNoSizeChangeAfterReset() throws Exception {
+    public void testShouldNoSizeChangeAfterReset() {
         testee.event(new FakeMailboxListenerAdded(MAILBOX_SESSION, ImmutableList.of(MessageUid.of(11)), MAILBOX_PATH));
         testee.resetEvents();
 
@@ -142,7 +142,7 @@ public class MailboxEventAnalyserTest {
     }
 
     @Test
-    public void testShouldNotSetUidWhenNoSystemFlagChange() throws Exception {
+    public void testShouldNotSetUidWhenNoSystemFlagChange() {
         FakeMailboxListenerFlagsUpdate update = new FakeMailboxListenerFlagsUpdate(MAILBOX_SESSION,
             ImmutableList.of(MessageUid.of(90L)),
             ImmutableList.of(UpdatedFlags.builder()
@@ -158,7 +158,7 @@ public class MailboxEventAnalyserTest {
     }
 
     @Test
-    public void testShouldSetUidWhenSystemFlagChange() throws Exception {
+    public void testShouldSetUidWhenSystemFlagChange() {
         MessageUid uid = MessageUid.of(900);
         
         FakeMailboxListenerFlagsUpdate update = new FakeMailboxListenerFlagsUpdate(OTHER_MAILBOX_SESSION,
@@ -176,7 +176,7 @@ public class MailboxEventAnalyserTest {
     }
 
     @Test
-    public void testShouldClearFlagUidsUponReset() throws Exception {
+    public void testShouldClearFlagUidsUponReset() {
         MessageUid uid = MessageUid.of(900);
         SelectedMailboxImpl analyser = this.testee;
         
@@ -197,7 +197,7 @@ public class MailboxEventAnalyserTest {
     }
 
     @Test
-    public void testShouldSetUidWhenSystemFlagChangeDifferentSessionInSilentMode() throws Exception {
+    public void testShouldSetUidWhenSystemFlagChangeDifferentSessionInSilentMode() {
         MessageUid uid = MessageUid.of(900);
 
         FakeMailboxListenerFlagsUpdate update = new FakeMailboxListenerFlagsUpdate(OTHER_MAILBOX_SESSION,
@@ -217,7 +217,7 @@ public class MailboxEventAnalyserTest {
     }
 
     @Test
-    public void testShouldNotSetUidWhenSystemFlagChangeSameSessionInSilentMode() throws Exception {
+    public void testShouldNotSetUidWhenSystemFlagChangeSameSessionInSilentMode() {
         FakeMailboxListenerFlagsUpdate update = new FakeMailboxListenerFlagsUpdate(MAILBOX_SESSION,
             ImmutableList.of(MessageUid.of(345)),
             ImmutableList.of(UpdatedFlags.builder()
@@ -235,7 +235,7 @@ public class MailboxEventAnalyserTest {
     }
 
     @Test
-    public void testShouldNotSetUidWhenOnlyRecentFlagUpdated() throws Exception {
+    public void testShouldNotSetUidWhenOnlyRecentFlagUpdated() {
         FakeMailboxListenerFlagsUpdate update = new FakeMailboxListenerFlagsUpdate(MAILBOX_SESSION,
             ImmutableList.of(MessageUid.of(886)),
             ImmutableList.of(UpdatedFlags.builder()

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/processor/base/SelectedMailboxImplTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/processor/base/SelectedMailboxImplTest.java b/protocols/imap/src/test/java/org/apache/james/imap/processor/base/SelectedMailboxImplTest.java
index 2e881cb..b640cba 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/processor/base/SelectedMailboxImplTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/processor/base/SelectedMailboxImplTest.java
@@ -50,7 +50,6 @@ import org.apache.james.mailbox.store.SimpleMessageMetaData;
 import org.apache.james.mailbox.store.event.EventFactory;
 import org.apache.james.mailbox.store.mail.model.DefaultMessageId;
 import org.apache.james.mailbox.store.mail.model.Mailbox;
-import org.apache.james.mailbox.store.mail.model.MailboxMessage;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -161,6 +160,6 @@ public class SelectedMailboxImplTest {
     private void emitEvent(MailboxListener mailboxListener) {
         TreeMap<MessageUid, MessageMetaData> result = new TreeMap<>();
         result.put(EMITTED_EVENT_UID, new SimpleMessageMetaData(EMITTED_EVENT_UID, MOD_SEQ, new Flags(), SIZE, new Date(), new DefaultMessageId()));
-        mailboxListener.event(new EventFactory().added(mock(MailboxSession.class), result, mailbox, ImmutableMap.<MessageUid, MailboxMessage>of()));
+        mailboxListener.event(new EventFactory().added(mock(MailboxSession.class), result, mailbox, ImmutableMap.of()));
     }
 }

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/processor/fetch/MailboxMessageResultUtilsTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/processor/fetch/MailboxMessageResultUtilsTest.java b/protocols/imap/src/test/java/org/apache/james/imap/processor/fetch/MailboxMessageResultUtilsTest.java
index 182cd7e..54354b6 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/processor/fetch/MailboxMessageResultUtilsTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/processor/fetch/MailboxMessageResultUtilsTest.java
@@ -22,7 +22,6 @@ package org.apache.james.imap.processor.fetch;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNull;
 
-import java.io.IOException;
 import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.List;
@@ -71,7 +70,7 @@ public class MailboxMessageResultUtilsTest {
 
         
         @Override
-        public InputStream getInputStream() throws IOException {
+        public InputStream getInputStream() {
             return null;
         }
 
@@ -90,7 +89,7 @@ public class MailboxMessageResultUtilsTest {
     }
 
     @Test
-    public void testGetAllContent() throws Exception {
+    public void testGetAllContent() {
         List<MessageResult.Header> results = MessageResultUtils.getAll(headers.iterator());
         assertEquals(3, results.size());
         assertEquals(headerOne, results.get(0));

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/processor/fetch/PartialFetchBodyElementTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/processor/fetch/PartialFetchBodyElementTest.java b/protocols/imap/src/test/java/org/apache/james/imap/processor/fetch/PartialFetchBodyElementTest.java
index 2848b80..0015c8b 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/processor/fetch/PartialFetchBodyElementTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/processor/fetch/PartialFetchBodyElementTest.java
@@ -20,11 +20,10 @@
 package org.apache.james.imap.processor.fetch;
 
 import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 
 import org.apache.james.imap.message.response.FetchResponse.BodyElement;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -34,105 +33,75 @@ public class PartialFetchBodyElementTest {
 
     BodyElement mockBodyElement;
 
-    private Mockery mockery = new JUnit4Mockery();
-    
     @Before
     public void setUp() throws Exception {
-        mockBodyElement = mockery.mock(BodyElement.class);
-        mockery.checking(new Expectations() {{
-                    oneOf(mockBodyElement).getName();will(returnValue("Name"));
-                }
-            }
-        );
+        mockBodyElement = mock(BodyElement.class);
+        when(mockBodyElement.getName()).thenReturn("Name");
     }
 
     @Test
     public void testSizeShouldBeNumberOfOctetsWhenSizeMoreWhenStartIsZero()
             throws Exception {
         final long moreThanNumberOfOctets = NUMBER_OF_OCTETS + 1;
-        PartialFetchBodyElement element = new PartialFetchBodyElement(
-                mockBodyElement, 0, NUMBER_OF_OCTETS);
-        mockery.checking(new Expectations() {{
-                    oneOf(mockBodyElement).size();will(returnValue(new Long(moreThanNumberOfOctets)));
-                }
-            }
-        );
+        PartialFetchBodyElement element = new PartialFetchBodyElement(mockBodyElement, 0, NUMBER_OF_OCTETS);
+        when(mockBodyElement.size()).thenReturn(moreThanNumberOfOctets);
+
         assertEquals(
-                "Size is more than number of octets so should be number of octets",
-                NUMBER_OF_OCTETS, element.size());
+            "Size is more than number of octets so should be number of octets",
+            NUMBER_OF_OCTETS, element.size());
     }
 
     @Test
     public void testSizeShouldBeSizeWhenNumberOfOctetsMoreWhenStartIsZero()
             throws Exception {
         final long lessThanNumberOfOctets = NUMBER_OF_OCTETS - 1;
-        PartialFetchBodyElement element = new PartialFetchBodyElement(
-                mockBodyElement, 0, NUMBER_OF_OCTETS);
-        mockery.checking(new Expectations() {{
-                    oneOf(mockBodyElement).size();will(returnValue(new Long(lessThanNumberOfOctets)));
-                }
-            }
-        );
+        PartialFetchBodyElement element = new PartialFetchBodyElement(mockBodyElement, 0, NUMBER_OF_OCTETS);
+        when(mockBodyElement.size()).thenReturn(lessThanNumberOfOctets);
+
         assertEquals("Size is less than number of octets so should be size",
-                lessThanNumberOfOctets, element.size());
+            lessThanNumberOfOctets, element.size());
     }
 
     @Test
     public void testWhenStartPlusNumberOfOctetsIsMoreThanSizeSizeShouldBeSizeMinusStart()
             throws Exception {
         final long size = 60;
-        PartialFetchBodyElement element = new PartialFetchBodyElement(
-                mockBodyElement, 10, NUMBER_OF_OCTETS);
-        mockery.checking(new Expectations() {{
-                    oneOf(mockBodyElement).size();will(returnValue(new Long(size)));
-                }
-            }
-        );
+        PartialFetchBodyElement element = new PartialFetchBodyElement(mockBodyElement, 10, NUMBER_OF_OCTETS);
+        when(mockBodyElement.size()).thenReturn(size);
+
         assertEquals("Size is less than number of octets so should be size",
-                50, element.size());
+            50, element.size());
     }
 
     @Test
     public void testWhenStartPlusNumberOfOctetsIsLessThanSizeSizeShouldBeNumberOfOctetsMinusStart()
             throws Exception {
         final long size = 100;
-        PartialFetchBodyElement element = new PartialFetchBodyElement(
-                mockBodyElement, 10, NUMBER_OF_OCTETS);
-        mockery.checking(new Expectations() {{
-                    oneOf(mockBodyElement).size();will(returnValue(new Long(size)));
-                }
-            }
-        );
+        PartialFetchBodyElement element = new PartialFetchBodyElement(mockBodyElement, 10, NUMBER_OF_OCTETS);
+        when(mockBodyElement.size()).thenReturn(size);
+
         assertEquals("Size is less than number of octets so should be size",
-                90, element.size());
+            90, element.size());
     }
 
     @Test
     public void testSizeShouldBeZeroWhenStartIsMoreThanSize() throws Exception {
         final long size = 100;
-        PartialFetchBodyElement element = new PartialFetchBodyElement(
-                mockBodyElement, 1000, NUMBER_OF_OCTETS);
-        mockery.checking(new Expectations() {{
-                    oneOf(mockBodyElement).size();will(returnValue(new Long(size)));
-                }
-            }
-        );
+        PartialFetchBodyElement element = new PartialFetchBodyElement(mockBodyElement, 1000, NUMBER_OF_OCTETS);
+        when(mockBodyElement.size()).thenReturn(size);
+
         assertEquals("Size is less than number of octets so should be size", 0,
-                element.size());
+            element.size());
     }
 
     @Test
     public void testSizeShouldBeNumberOfOctetsWhenStartMoreThanOctets()
             throws Exception {
         final long size = 2000;
-        PartialFetchBodyElement element = new PartialFetchBodyElement(
-                mockBodyElement, 1000, NUMBER_OF_OCTETS);
-        mockery.checking(new Expectations() {{
-                    oneOf(mockBodyElement).size();will(returnValue(new Long(size)));
-                }
-            }
-        );
+        PartialFetchBodyElement element = new PartialFetchBodyElement(mockBodyElement, 1000, NUMBER_OF_OCTETS);
+        when(mockBodyElement.size()).thenReturn(size);
+
         assertEquals("Content size is less than start. Size should be zero.",
-                NUMBER_OF_OCTETS, element.size());
+            NUMBER_OF_OCTETS, element.size());
     }
 }

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/protocols/imap/utils/DecoderUtilsTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/protocols/imap/utils/DecoderUtilsTest.java b/protocols/imap/src/test/java/org/apache/james/protocols/imap/utils/DecoderUtilsTest.java
index 7693b32..108d9c0 100644
--- a/protocols/imap/src/test/java/org/apache/james/protocols/imap/utils/DecoderUtilsTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/protocols/imap/utils/DecoderUtilsTest.java
@@ -105,7 +105,7 @@ public class DecoderUtilsTest {
         checkDateTime("123456789012345678901234567");
     }
 
-    private void checkDateTime(String datetime) throws Exception {
+    private void checkDateTime(String datetime) {
         try {
             DecoderUtils.decodeDateTime(datetime);
             fail("Bad date-time" + datetime);
@@ -325,7 +325,7 @@ public class DecoderUtilsTest {
     }
 
     @Test
-    public void testRejectBogusMonths() throws Exception {
+    public void testRejectBogusMonths() {
         checkReject('N', 'O', 'C');
         checkReject('A', 'N', 'T');
         checkReject('Z', 'Z', 'Z');
@@ -357,7 +357,7 @@ public class DecoderUtilsTest {
     }
 
     @Test
-    public void testRejectBogusYear() throws Exception {
+    public void testRejectBogusYear() {
         checkRejectYear('D', '0', '2', '3');
         checkRejectYear('1', 'A', '2', '3');
         checkRejectYear('1', '5', 'B', '3');
@@ -432,7 +432,7 @@ public class DecoderUtilsTest {
     }
 
     @Test
-    public void testBogusZones() throws Exception {
+    public void testBogusZones() {
         checkRejectZone(" 0000");
         checkRejectZone(" GMT ");
         checkRejectZone("DANG!");
@@ -457,7 +457,7 @@ public class DecoderUtilsTest {
     }
 
     @Test
-    public void testIsSimpleDigit() throws Exception {
+    public void testIsSimpleDigit() {
         assertTrue(DecoderUtils.isSimpleDigit('0'));
         assertTrue(DecoderUtils.isSimpleDigit('1'));
         assertTrue(DecoderUtils.isSimpleDigit('2'));
@@ -507,7 +507,7 @@ public class DecoderUtilsTest {
     }
 
     @Test
-    public void testRejectNumber() throws Exception {
+    public void testRejectNumber() {
         checkRejectNumber("A1");
         checkRejectNumber("1A");
         checkRejectNumber("AA");


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


[19/20] james-project git commit: JAMES-2449 Release all tests about snapshot isolation

Posted by bt...@apache.org.
JAMES-2449 Release all tests about snapshot isolation

Keep some tests about exception upon concurrent actions


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

Branch: refs/heads/master
Commit: d3f6f1ada9a86d2f12b39cd5cff3bece64c56963
Parents: f101b0d
Author: Benoit Tellier <bt...@linagora.com>
Authored: Thu Aug 2 17:16:04 2018 +0700
Committer: Benoit Tellier <bt...@linagora.com>
Committed: Fri Aug 3 15:51:30 2018 +0700

----------------------------------------------------------------------
 .../queue/api/ManageableMailQueueContract.java  | 210 ++++++++++++++-----
 .../james/queue/file/FileMailQueueTest.java     |  63 ------
 2 files changed, 155 insertions(+), 118 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/d3f6f1ad/server/queue/queue-api/src/test/java/org/apache/james/queue/api/ManageableMailQueueContract.java
----------------------------------------------------------------------
diff --git a/server/queue/queue-api/src/test/java/org/apache/james/queue/api/ManageableMailQueueContract.java b/server/queue/queue-api/src/test/java/org/apache/james/queue/api/ManageableMailQueueContract.java
index 00bac8d..53c4a4e 100644
--- a/server/queue/queue-api/src/test/java/org/apache/james/queue/api/ManageableMailQueueContract.java
+++ b/server/queue/queue-api/src/test/java/org/apache/james/queue/api/ManageableMailQueueContract.java
@@ -27,11 +27,14 @@ import static org.apache.mailet.base.MailAddressFixture.RECIPIENT2;
 import static org.apache.mailet.base.MailAddressFixture.RECIPIENT3;
 import static org.apache.mailet.base.MailAddressFixture.SENDER;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
 
 import org.apache.mailet.Mail;
 import org.apache.mailet.base.MailAddressFixture;
 import org.junit.jupiter.api.Test;
 
+import com.google.common.collect.Iterators;
+
 public interface ManageableMailQueueContract extends MailQueueContract {
 
     ManageableMailQueue getManageableMailQueue();
@@ -136,7 +139,25 @@ public interface ManageableMailQueueContract extends MailQueueContract {
     }
 
     @Test
-    default void concurrentDequeueShouldNotAlterBrowsing() throws Exception {
+    default void dequeueShouldNotFailWhenBrowsing() throws Exception {
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name1")
+            .build());
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name2")
+            .build());
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name3")
+            .build());
+
+        ManageableMailQueue.MailQueueIterator items = getManageableMailQueue().browse();
+
+        assertThatCode(() -> getManageableMailQueue().deQueue()).doesNotThrowAnyException();
+
+    }
+
+    @Test
+    default void browseShouldNotFailWhenConcurrentDequeue() throws Exception {
         getManageableMailQueue().enQueue(defaultMail()
             .name("name1")
             .build());
@@ -151,14 +172,11 @@ public interface ManageableMailQueueContract extends MailQueueContract {
 
         getManageableMailQueue().deQueue();
 
-        assertThat(items)
-            .extracting(ManageableMailQueue.MailQueueItemView::getMail)
-            .extracting(Mail::getName)
-            .containsExactly("name1", "name2", "name3");
+        assertThatCode(() ->  Iterators.consumingIterator(items)).doesNotThrowAnyException();
     }
 
     @Test
-    default void concurrentDequeueShouldNotAlterBrowsingWhenDequeueWhileIterating() throws Exception {
+    default void dequeueShouldNotFailWhenBrowsingIterating() throws Exception {
         getManageableMailQueue().enQueue(defaultMail()
             .name("name1")
             .build());
@@ -170,20 +188,34 @@ public interface ManageableMailQueueContract extends MailQueueContract {
             .build());
 
         ManageableMailQueue.MailQueueIterator items = getManageableMailQueue().browse();
+        ManageableMailQueue.MailQueueItemView firstItem = items.next();
+
+        assertThatCode(() -> getManageableMailQueue().deQueue()).doesNotThrowAnyException();
+
+    }
 
+    @Test
+    default void browseShouldNotFailWhenConcurrentDequeueWhenIterating() throws Exception {
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name1")
+            .build());
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name2")
+            .build());
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name3")
+            .build());
+
+        ManageableMailQueue.MailQueueIterator items = getManageableMailQueue().browse();
         ManageableMailQueue.MailQueueItemView firstItem = items.next();
 
         getManageableMailQueue().deQueue();
 
-        assertThat(firstItem.getMail().getName()).isEqualTo("name1");
-        assertThat(items)
-            .extracting(ManageableMailQueue.MailQueueItemView::getMail)
-            .extracting(Mail::getName)
-            .containsExactly("name2", "name3");
+        assertThatCode(() ->  Iterators.consumingIterator(items)).doesNotThrowAnyException();
     }
 
     @Test
-    default void browsingShouldNotAffectDequeue() throws Exception {
+    default void enqueueShouldNotFailWhenBrowsing() throws Exception {
         getManageableMailQueue().enQueue(defaultMail()
             .name("name1")
             .build());
@@ -195,149 +227,217 @@ public interface ManageableMailQueueContract extends MailQueueContract {
             .build());
 
         ManageableMailQueue.MailQueueIterator items = getManageableMailQueue().browse();
-        items.next();
 
-        MailQueue.MailQueueItem mailQueueItem = getManageableMailQueue().deQueue();
+        assertThatCode(() -> getManageableMailQueue().enQueue(defaultMail()
+            .name("name4")
+            .build())).doesNotThrowAnyException();
 
-        assertThat(mailQueueItem.getMail().getName()).isEqualTo("name1");
     }
 
     @Test
-    default void concurrentEnqueueShouldNotAlterBrowsingWhenDequeueWhileIterating() throws Exception {
+    default void browseShouldNotFailWhenConcurrentEnqueue() throws Exception {
         getManageableMailQueue().enQueue(defaultMail()
             .name("name1")
             .build());
         getManageableMailQueue().enQueue(defaultMail()
             .name("name2")
             .build());
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name3")
+            .build());
 
         ManageableMailQueue.MailQueueIterator items = getManageableMailQueue().browse();
 
-        ManageableMailQueue.MailQueueItemView firstItem = items.next();
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name4")
+            .build());
 
+        assertThatCode(() ->  Iterators.consumingIterator(items)).doesNotThrowAnyException();
+    }
+
+    @Test
+    default void enqueueShouldNotFailWhenBrowsingIterating() throws Exception {
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name1")
+            .build());
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name2")
+            .build());
         getManageableMailQueue().enQueue(defaultMail()
             .name("name3")
             .build());
 
-        assertThat(firstItem.getMail().getName()).isEqualTo("name1");
-        assertThat(items).extracting(ManageableMailQueue.MailQueueItemView::getMail)
-            .extracting(Mail::getName)
-            .containsExactly("name2");
+        ManageableMailQueue.MailQueueIterator items = getManageableMailQueue().browse();
+        ManageableMailQueue.MailQueueItemView firstItem = items.next();
+
+        assertThatCode(() ->
+            getManageableMailQueue().enQueue(defaultMail()
+                .name("name4")
+                .build()))
+            .doesNotThrowAnyException();
+
     }
 
     @Test
-    default void concurrentFlushShouldNotAlterBrowsingWhenDequeueWhileIterating() throws Exception {
+    default void browseShouldNotFailWhenConcurrentEnqueueWhenIterating() throws Exception {
         getManageableMailQueue().enQueue(defaultMail()
             .name("name1")
             .build());
         getManageableMailQueue().enQueue(defaultMail()
             .name("name2")
             .build());
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name3")
+            .build());
 
         ManageableMailQueue.MailQueueIterator items = getManageableMailQueue().browse();
-
         ManageableMailQueue.MailQueueItemView firstItem = items.next();
 
-        getManageableMailQueue().flush();
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name2")
+            .build());
 
-        assertThat(firstItem.getMail().getName()).isEqualTo("name1");
-        assertThat(items).extracting(ManageableMailQueue.MailQueueItemView::getMail)
-            .extracting(Mail::getName)
-            .containsExactly("name2");
+        assertThatCode(() ->  Iterators.consumingIterator(items)).doesNotThrowAnyException();
     }
 
     @Test
-    default void concurrentFlushShouldNotAlterBrowsing() throws Exception {
+    default void clearShouldNotFailWhenBrowsingIterating() throws Exception {
         getManageableMailQueue().enQueue(defaultMail()
             .name("name1")
             .build());
         getManageableMailQueue().enQueue(defaultMail()
             .name("name2")
             .build());
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name3")
+            .build());
 
         ManageableMailQueue.MailQueueIterator items = getManageableMailQueue().browse();
+        ManageableMailQueue.MailQueueItemView firstItem = items.next();
 
-        getManageableMailQueue().flush();
+        assertThatCode(() -> getManageableMailQueue().clear())
+            .doesNotThrowAnyException();
 
-        assertThat(items).extracting(ManageableMailQueue.MailQueueItemView::getMail)
-            .extracting(Mail::getName)
-            .containsExactly("name1", "name2");
     }
 
     @Test
-    default void concurrentClearShouldNotAlterBrowsingWhenDequeue() throws Exception {
+    default void browseShouldNotFailWhenConcurrentClearWhenIterating() throws Exception {
         getManageableMailQueue().enQueue(defaultMail()
             .name("name1")
             .build());
         getManageableMailQueue().enQueue(defaultMail()
             .name("name2")
             .build());
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name3")
+            .build());
 
         ManageableMailQueue.MailQueueIterator items = getManageableMailQueue().browse();
+        ManageableMailQueue.MailQueueItemView firstItem = items.next();
 
         getManageableMailQueue().clear();
 
-        assertThat(items).extracting(ManageableMailQueue.MailQueueItemView::getMail)
-            .extracting(Mail::getName)
-            .containsExactly("name1", "name2");
+        assertThatCode(() ->  Iterators.consumingIterator(items)).doesNotThrowAnyException();
     }
 
     @Test
-    default void concurrentRemoveShouldNotAlterBrowsingWhenDequeue() throws Exception {
+    default void flushShouldNotFailWhenBrowsingIterating() throws Exception {
         getManageableMailQueue().enQueue(defaultMail()
             .name("name1")
             .build());
         getManageableMailQueue().enQueue(defaultMail()
             .name("name2")
             .build());
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name3")
+            .build());
 
         ManageableMailQueue.MailQueueIterator items = getManageableMailQueue().browse();
+        ManageableMailQueue.MailQueueItemView firstItem = items.next();
 
-        getManageableMailQueue().remove(ManageableMailQueue.Type.Name, "name2");
+        assertThatCode(() -> getManageableMailQueue().flush())
+            .doesNotThrowAnyException();
 
-        assertThat(items).extracting(ManageableMailQueue.MailQueueItemView::getMail)
-            .extracting(Mail::getName)
-            .containsExactly("name1", "name2");
     }
 
     @Test
-    default void concurrentClearShouldNotAlterBrowsingWhenDequeueWhileIterating() throws Exception {
+    default void browseShouldNotFailWhenConcurrentFlushWhenIterating() throws Exception {
         getManageableMailQueue().enQueue(defaultMail()
             .name("name1")
             .build());
         getManageableMailQueue().enQueue(defaultMail()
             .name("name2")
             .build());
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name3")
+            .build());
 
         ManageableMailQueue.MailQueueIterator items = getManageableMailQueue().browse();
-        ManageableMailQueue.MailQueueItemView next = items.next();
+        ManageableMailQueue.MailQueueItemView firstItem = items.next();
 
-        getManageableMailQueue().clear();
+        getManageableMailQueue().flush();
 
-        assertThat(next.getMail().getName()).isEqualTo("name1");
-        assertThat(items).extracting(ManageableMailQueue.MailQueueItemView::getMail)
-            .extracting(Mail::getName)
-            .containsExactly("name2");
+        assertThatCode(() ->  Iterators.consumingIterator(items)).doesNotThrowAnyException();
     }
 
     @Test
-    default void concurrentRemoveShouldNotAlterBrowsingWhenDequeueWhileIterating() throws Exception {
+    default void removeShouldNotFailWhenBrowsingIterating() throws Exception {
         getManageableMailQueue().enQueue(defaultMail()
             .name("name1")
             .build());
         getManageableMailQueue().enQueue(defaultMail()
             .name("name2")
             .build());
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name3")
+            .build());
 
         ManageableMailQueue.MailQueueIterator items = getManageableMailQueue().browse();
-        ManageableMailQueue.MailQueueItemView next = items.next();
+        ManageableMailQueue.MailQueueItemView firstItem = items.next();
+
+        assertThatCode(() -> getManageableMailQueue().flush())
+            .doesNotThrowAnyException();
+
+    }
+
+    @Test
+    default void browseShouldNotFailWhenConcurrentRemoveWhenIterating() throws Exception {
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name1")
+            .build());
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name2")
+            .build());
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name3")
+            .build());
+
+        ManageableMailQueue.MailQueueIterator items = getManageableMailQueue().browse();
+        ManageableMailQueue.MailQueueItemView firstItem = items.next();
 
         getManageableMailQueue().remove(ManageableMailQueue.Type.Name, "name2");
 
-        assertThat(next.getMail().getName()).isEqualTo("name1");
-        assertThat(items).extracting(ManageableMailQueue.MailQueueItemView::getMail)
-            .extracting(Mail::getName)
-            .containsExactly("name2");
+        assertThatCode(() ->  Iterators.consumingIterator(items)).doesNotThrowAnyException();
+    }
+
+    @Test
+    default void browsingShouldNotAffectDequeue() throws Exception {
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name1")
+            .build());
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name2")
+            .build());
+        getManageableMailQueue().enQueue(defaultMail()
+            .name("name3")
+            .build());
+
+        ManageableMailQueue.MailQueueIterator items = getManageableMailQueue().browse();
+        items.next();
+
+        MailQueue.MailQueueItem mailQueueItem = getManageableMailQueue().deQueue();
+
+        assertThat(mailQueueItem.getMail().getName()).isEqualTo("name1");
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/james-project/blob/d3f6f1ad/server/queue/queue-file/src/test/java/org/apache/james/queue/file/FileMailQueueTest.java
----------------------------------------------------------------------
diff --git a/server/queue/queue-file/src/test/java/org/apache/james/queue/file/FileMailQueueTest.java b/server/queue/queue-file/src/test/java/org/apache/james/queue/file/FileMailQueueTest.java
index d829200..f044d8c 100644
--- a/server/queue/queue-file/src/test/java/org/apache/james/queue/file/FileMailQueueTest.java
+++ b/server/queue/queue-file/src/test/java/org/apache/james/queue/file/FileMailQueueTest.java
@@ -58,69 +58,6 @@ public class FileMailQueueTest implements DelayedManageableMailQueueContract {
 
     @Test
     @Override
-    @Disabled("JAMES-2299 No snapshot isolation")
-    public void concurrentClearShouldNotAlterBrowsingWhenDequeueWhileIterating() {
-
-    }
-
-    @Test
-    @Override
-    @Disabled("JAMES-2299 No snapshot isolation")
-    public void concurrentClearShouldNotAlterBrowsingWhenDequeue() {
-
-    }
-
-    @Test
-    @Override
-    @Disabled("JAMES-2299 No snapshot isolation")
-    public void concurrentDequeueShouldNotAlterBrowsing() {
-
-    }
-
-    @Test
-    @Override
-    @Disabled("JAMES-2299 No snapshot isolation")
-    public void concurrentDequeueShouldNotAlterBrowsingWhenDequeueWhileIterating() {
-
-    }
-
-    @Test
-    @Override
-    @Disabled("JAMES-2299 No snapshot isolation")
-    public void concurrentEnqueueShouldNotAlterBrowsingWhenDequeueWhileIterating() {
-
-    }
-
-    @Test
-    @Override
-    @Disabled("JAMES-2299 No snapshot isolation")
-    public void concurrentRemoveShouldNotAlterBrowsingWhenDequeueWhileIterating() {
-
-    }
-
-    @Test
-    @Override
-    @Disabled("JAMES-2299 No snapshot isolation")
-    public void concurrentFlushShouldNotAlterBrowsingWhenDequeueWhileIterating() {
-
-    }
-
-    @Test
-    @Override
-    @Disabled("JAMES-2299 No snapshot isolation")
-    public void concurrentFlushShouldNotAlterBrowsing() {
-
-    }
-
-    @Test
-    @Override
-    @Disabled("JAMES-2299 No snapshot isolation")
-    public void concurrentRemoveShouldNotAlterBrowsingWhenDequeue() {
-
-    }
-
-    @Test
-    @Override
     @Disabled("JAMES-2298 Not supported yet")
     public void removeBySenderShouldRemoveSpecificEmail() {
 


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


[16/20] james-project git commit: JAMES-2513 Cassandra Domain List configuration should rely on POJO

Posted by bt...@apache.org.
JAMES-2513 Cassandra Domain List configuration should rely on POJO


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

Branch: refs/heads/master
Commit: 75097ea9ca35fdd71ced8184d2393f5e556a8317
Parents: 33c809a
Author: benwa <bt...@linagora.com>
Authored: Thu Aug 2 14:04:43 2018 +0700
Committer: Benoit Tellier <bt...@linagora.com>
Committed: Fri Aug 3 15:51:29 2018 +0700

----------------------------------------------------------------------
 .../modules/data/CassandraDomainListModule.java | 20 ++++++++++++++++----
 1 file changed, 16 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/75097ea9/server/container/guice/cassandra-guice/src/main/java/org/apache/james/modules/data/CassandraDomainListModule.java
----------------------------------------------------------------------
diff --git a/server/container/guice/cassandra-guice/src/main/java/org/apache/james/modules/data/CassandraDomainListModule.java b/server/container/guice/cassandra-guice/src/main/java/org/apache/james/modules/data/CassandraDomainListModule.java
index 4d253af..482a65c 100644
--- a/server/container/guice/cassandra-guice/src/main/java/org/apache/james/modules/data/CassandraDomainListModule.java
+++ b/server/container/guice/cassandra-guice/src/main/java/org/apache/james/modules/data/CassandraDomainListModule.java
@@ -24,6 +24,7 @@ import org.apache.commons.configuration.ConfigurationException;
 import org.apache.james.backends.cassandra.components.CassandraModule;
 import org.apache.james.domainlist.api.DomainList;
 import org.apache.james.domainlist.cassandra.CassandraDomainList;
+import org.apache.james.domainlist.lib.DomainListConfiguration;
 import org.apache.james.lifecycle.api.Configurable;
 import org.apache.james.server.core.configuration.ConfigurationProvider;
 import org.apache.james.utils.ConfigurationPerformer;
@@ -31,6 +32,7 @@ import org.apache.james.utils.ConfigurationPerformer;
 import com.google.common.collect.ImmutableList;
 import com.google.inject.AbstractModule;
 import com.google.inject.Inject;
+import com.google.inject.Provides;
 import com.google.inject.Scopes;
 import com.google.inject.Singleton;
 import com.google.inject.multibindings.Multibinder;
@@ -44,23 +46,33 @@ public class CassandraDomainListModule extends AbstractModule {
         Multibinder.newSetBinder(binder(), CassandraModule.class).addBinding().toInstance(org.apache.james.domainlist.cassandra.CassandraDomainListModule.MODULE);
         Multibinder.newSetBinder(binder(), ConfigurationPerformer.class).addBinding().to(CassandraDomainListConfigurationPerformer.class);
     }
+
+    @Provides
+    @Singleton
+    public DomainListConfiguration provideDomainListConfiguration(ConfigurationProvider configurationProvider) {
+        try {
+            return DomainListConfiguration.from(configurationProvider.getConfiguration("domainlist"));
+        } catch (ConfigurationException e) {
+            throw new RuntimeException(e);
+        }
+    }
     
     @Singleton
     public static class CassandraDomainListConfigurationPerformer implements ConfigurationPerformer {
 
-        private final ConfigurationProvider configurationProvider;
+        private final DomainListConfiguration configuration;
         private final CassandraDomainList cassandraDomainList;
 
         @Inject
-        public CassandraDomainListConfigurationPerformer(ConfigurationProvider configurationProvider, CassandraDomainList cassandraDomainList) {
-            this.configurationProvider = configurationProvider;
+        public CassandraDomainListConfigurationPerformer(DomainListConfiguration configuration, CassandraDomainList cassandraDomainList) {
+            this.configuration = configuration;
             this.cassandraDomainList = cassandraDomainList;
         }
 
         @Override
         public void initModule() {
             try {
-                cassandraDomainList.configure(configurationProvider.getConfiguration("domainlist"));
+                cassandraDomainList.configure(configuration);
             } catch (ConfigurationException e) {
                 throw new RuntimeException(e);
             }


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


[10/20] james-project git commit: JAMES-2506 Remove jmock from mpt

Posted by bt...@apache.org.
JAMES-2506 Remove jmock from mpt


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

Branch: refs/heads/master
Commit: 37829b367a4e3ee6df42b3a0b92130a1f4f2dbd1
Parents: dffc54e
Author: duc <dt...@linagora.com>
Authored: Mon Jul 30 17:36:33 2018 +0700
Committer: Benoit Tellier <bt...@linagora.com>
Committed: Fri Aug 3 15:51:21 2018 +0700

----------------------------------------------------------------------
 mpt/all/pom.xml                                 |  5 --
 mpt/antlib/pom.xml                              |  5 --
 mpt/app/pom.xml                                 |  5 --
 mpt/core/pom.xml                                | 10 +--
 .../james/mpt/TestExternalHostSystem.java       | 47 +++++++-------
 .../mpt/TestFileProtocolSessionBuilder.java     | 67 +++++++++++---------
 mpt/impl/imap-mailbox/core/pom.xml              |  8 ---
 mpt/impl/imap-mailbox/external-james/pom.xml    |  4 --
 mpt/pom.xml                                     |  1 -
 9 files changed, 66 insertions(+), 86 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/37829b36/mpt/all/pom.xml
----------------------------------------------------------------------
diff --git a/mpt/all/pom.xml b/mpt/all/pom.xml
index 9b7fa22..615f41a 100644
--- a/mpt/all/pom.xml
+++ b/mpt/all/pom.xml
@@ -40,11 +40,6 @@ MPT is a functional test framework specialised for the ASCII line-base protocols
             <artifactId>commons-logging</artifactId>
         </dependency>
         <dependency>
-            <groupId>jmock</groupId>
-            <artifactId>jmock</artifactId>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
         </dependency>

http://git-wip-us.apache.org/repos/asf/james-project/blob/37829b36/mpt/antlib/pom.xml
----------------------------------------------------------------------
diff --git a/mpt/antlib/pom.xml b/mpt/antlib/pom.xml
index d2d1ebc..352fba5 100644
--- a/mpt/antlib/pom.xml
+++ b/mpt/antlib/pom.xml
@@ -51,11 +51,6 @@ to the library requiring no extra coding.</description>
             <artifactId>commons-logging</artifactId>
         </dependency>
         <dependency>
-            <groupId>jmock</groupId>
-            <artifactId>jmock</artifactId>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
         </dependency>

http://git-wip-us.apache.org/repos/asf/james-project/blob/37829b36/mpt/app/pom.xml
----------------------------------------------------------------------
diff --git a/mpt/app/pom.xml b/mpt/app/pom.xml
index 28239ac..993f1da 100644
--- a/mpt/app/pom.xml
+++ b/mpt/app/pom.xml
@@ -56,11 +56,6 @@ interfaces to the MPT library.</description>
             <artifactId>commons-logging</artifactId>
         </dependency>
         <dependency>
-            <groupId>jmock</groupId>
-            <artifactId>jmock</artifactId>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
         </dependency>

http://git-wip-us.apache.org/repos/asf/james-project/blob/37829b36/mpt/core/pom.xml
----------------------------------------------------------------------
diff --git a/mpt/core/pom.xml b/mpt/core/pom.xml
index 1ebad5a..a946cc5 100644
--- a/mpt/core/pom.xml
+++ b/mpt/core/pom.xml
@@ -44,11 +44,6 @@
             <artifactId>commons-io</artifactId>
         </dependency>
         <dependency>
-            <groupId>jmock</groupId>
-            <artifactId>jmock</artifactId>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
             <scope>compile</scope>
@@ -67,6 +62,11 @@
             <artifactId>awaitility</artifactId>
         </dependency>
         <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-core</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
             <groupId>org.slf4j</groupId>
             <artifactId>slf4j-api</artifactId>
         </dependency>

http://git-wip-us.apache.org/repos/asf/james-project/blob/37829b36/mpt/core/src/test/java/org/apache/james/mpt/TestExternalHostSystem.java
----------------------------------------------------------------------
diff --git a/mpt/core/src/test/java/org/apache/james/mpt/TestExternalHostSystem.java b/mpt/core/src/test/java/org/apache/james/mpt/TestExternalHostSystem.java
index d914af2..8705a6b 100644
--- a/mpt/core/src/test/java/org/apache/james/mpt/TestExternalHostSystem.java
+++ b/mpt/core/src/test/java/org/apache/james/mpt/TestExternalHostSystem.java
@@ -19,6 +19,12 @@
 
 package org.apache.james.mpt;
 
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+
 import org.apache.james.mpt.api.Continuation;
 import org.apache.james.mpt.api.ImapFeatures;
 import org.apache.james.mpt.api.ImapFeatures.Feature;
@@ -27,11 +33,11 @@ import org.apache.james.mpt.api.UserAdder;
 import org.apache.james.mpt.host.ExternalHostSystem;
 import org.apache.james.mpt.monitor.NullMonitor;
 import org.apache.james.mpt.session.ExternalSessionFactory;
-import org.jmock.Mock;
-import org.jmock.MockObjectTestCase;
-
-public class TestExternalHostSystem extends MockObjectTestCase {
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
 
+public class TestExternalHostSystem {
     
     private static final String USER = "USER NAME";
 
@@ -41,46 +47,41 @@ public class TestExternalHostSystem extends MockObjectTestCase {
 
     private static final ImapFeatures SUPPORTED_FEATURES = ImapFeatures.of(Feature.NAMESPACE_SUPPORT);
 
-    
     private DiscardProtocol protocol;
-    
     private DiscardProtocol.Record record;
-
     private Continuation continuation;
-
     private UserAdder userAdder;
 
-    private Mock mockUserAdder;
-    
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
+    @Before
+    public void setUp() throws Exception {
         protocol = new DiscardProtocol();
         protocol.start();
         record = protocol.recordNext();
-        continuation = (Continuation) mock(Continuation.class).proxy();
-        mockUserAdder = mock(UserAdder.class);
-        userAdder = (UserAdder) mockUserAdder.proxy();
+        continuation = mock(Continuation.class);
+        userAdder = mock(UserAdder.class);
     }
 
-    @Override
-    protected void tearDown() throws Exception {
+    @After
+    public void tearDown() {
         protocol.stop();
-        super.tearDown();
     }
-    
+
+    @Test
     public void testWrite() throws Exception {
         Session session = newSession(SHABANG);
         final String in = "Hello, World";
         session.writeLine(in);
         session.stop();
-        assertEquals(in + "\r\n", record.complete());
+
+        assertThat(record.complete()).isEqualTo(in + "\r\n");
     }
-    
+
+    @Test
     public void testAddUser() throws Exception {
-        mockUserAdder.expects(once()).method("addUser").with(eq(USER), eq(PASSWORD));
         ExternalHostSystem system = buildSystem(SHABANG);
         system.addUser(USER, PASSWORD);
+        verify(userAdder, times(1)).addUser(USER, PASSWORD);
+        verifyNoMoreInteractions(userAdder);
     }
 
     private Session newSession(String shabang) throws Exception {

http://git-wip-us.apache.org/repos/asf/james-project/blob/37829b36/mpt/core/src/test/java/org/apache/james/mpt/TestFileProtocolSessionBuilder.java
----------------------------------------------------------------------
diff --git a/mpt/core/src/test/java/org/apache/james/mpt/TestFileProtocolSessionBuilder.java b/mpt/core/src/test/java/org/apache/james/mpt/TestFileProtocolSessionBuilder.java
index 4d6edcd..bacb76c 100644
--- a/mpt/core/src/test/java/org/apache/james/mpt/TestFileProtocolSessionBuilder.java
+++ b/mpt/core/src/test/java/org/apache/james/mpt/TestFileProtocolSessionBuilder.java
@@ -19,14 +19,19 @@
 
 package org.apache.james.mpt;
 
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+
 import java.io.StringReader;
 
 import org.apache.james.mpt.api.ProtocolInteractor;
 import org.apache.james.mpt.protocol.ProtocolSessionBuilder;
-import org.jmock.Mock;
-import org.jmock.MockObjectTestCase;
+import org.junit.Before;
+import org.junit.Test;
 
-public class TestFileProtocolSessionBuilder extends MockObjectTestCase {
+public class TestFileProtocolSessionBuilder {
 
     private static final String SCRIPT_WITH_VARIABLES = "HELLO ${not} ${foo} WORLD ${bar}";
     private static final String SCRIPT_WITH_FOO_REPLACED_BY_WHATEVER = "HELLO ${not} whatever WORLD ${bar}";
@@ -35,54 +40,56 @@ public class TestFileProtocolSessionBuilder extends MockObjectTestCase {
     ProtocolSessionBuilder builder;
     ProtocolInteractor session;
 
-    private Mock mockSession;
-    
-    @Override
-    protected void setUp() throws Exception {
-        super.setUp();
+    @Before
+    public void setUp() throws Exception {
         builder = new ProtocolSessionBuilder();
-        mockSession = mock(ProtocolInteractor.class);
-        session = (ProtocolInteractor) mockSession.proxy();
-    }
-
-    @Override
-    protected void tearDown() throws Exception {
-        super.tearDown();
+        session = mock(ProtocolInteractor.class);
     }
 
-    private void addLines() throws Exception {
-        builder.addProtocolLines("A Script", new StringReader(ProtocolSessionBuilder.CLIENT_TAG + " " + SCRIPT_WITH_VARIABLES), session);
-    }
-    
+    @Test
     public void testShouldPreserveContentsWhenNoVariablesSet() throws Exception {
-        mockSession.expects(once()).method("cl").with(eq(-1), eq(SCRIPT_WITH_VARIABLES));
-        addLines();
+        builder.addProtocolLines("A Script", new StringReader(ProtocolSessionBuilder.CLIENT_TAG + " " + SCRIPT_WITH_VARIABLES), session);
+
+        verify(session, times(1)).cl(-1, SCRIPT_WITH_VARIABLES);
+        verifyNoMoreInteractions(session);
     }
 
+    @Test
     public void testShouldReplaceVariableWhenSet() throws Exception {
-        mockSession.expects(once()).method("cl").with(eq(-1), eq(SCRIPT_WITH_FOO_REPLACED_BY_WHATEVER));
         builder.setVariable("foo", "whatever");
-        addLines();
+        builder.addProtocolLines("A Script", new StringReader(ProtocolSessionBuilder.CLIENT_TAG + " " + SCRIPT_WITH_VARIABLES), session);
+
+        verify(session, times(1)).cl(-1, SCRIPT_WITH_FOO_REPLACED_BY_WHATEVER);
+        verifyNoMoreInteractions(session);
     }
-    
+
+    @Test
     public void testShouldReplaceAllVariablesWhenSet() throws Exception {
-        mockSession.expects(once()).method("cl").with(eq(-1), eq(SCRIPT_WITH_VARIABLES_INLINED));
         builder.setVariable("bar", "bar");
         builder.setVariable("foo", "foo");
         builder.setVariable("not", "not");
-        addLines();
+        builder.addProtocolLines("A Script", new StringReader(ProtocolSessionBuilder.CLIENT_TAG + " " + SCRIPT_WITH_VARIABLES), session);
+
+        verify(session, times(1)).cl(-1, SCRIPT_WITH_VARIABLES_INLINED);
+        verifyNoMoreInteractions(session);
     }
-    
+
+    @Test
     public void testShouldReplaceVariableAtBeginningAndEnd() throws Exception {
-        mockSession.expects(once()).method("cl").with(eq(-1), eq("whatever Some Other Scriptwhateverwhatever"));
         builder.setVariable("foo", "whatever");
         builder.addProtocolLines("A Script", new StringReader(ProtocolSessionBuilder.CLIENT_TAG + " " + "${foo} Some Other Script${foo}${foo}"), session);
+
+        verify(session, times(1)).cl(-1, "whatever Some Other Scriptwhateverwhatever");
+        verifyNoMoreInteractions(session);
     }
-    
+
+    @Test
     public void testShouldIgnoreNotQuiteVariables() throws Exception {
         final String NEARLY = "{foo}${}${foo Some Other Script${foo}";
-        mockSession.expects(once()).method("cl").with(eq(-1), eq(NEARLY));
         builder.setVariable("foo", "whatever");
         builder.addProtocolLines("A Script", new StringReader(ProtocolSessionBuilder.CLIENT_TAG + " " + NEARLY), session);
+
+        verify(session, times(1)).cl(-1, NEARLY);
+        verifyNoMoreInteractions(session);
     }
 }

http://git-wip-us.apache.org/repos/asf/james-project/blob/37829b36/mpt/impl/imap-mailbox/core/pom.xml
----------------------------------------------------------------------
diff --git a/mpt/impl/imap-mailbox/core/pom.xml b/mpt/impl/imap-mailbox/core/pom.xml
index b8075ff..a99084c 100644
--- a/mpt/impl/imap-mailbox/core/pom.xml
+++ b/mpt/impl/imap-mailbox/core/pom.xml
@@ -84,14 +84,6 @@
             <groupId>${james.protocols.groupId}</groupId>
             <artifactId>protocols-imap</artifactId>
         </dependency>
-        <dependency>
-            <groupId>org.jmock</groupId>
-            <artifactId>jmock</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.jmock</groupId>
-            <artifactId>jmock-junit4</artifactId>
-        </dependency>
         <!-- As mime4j use commons-logging we need to specify the binding here -->
         <dependency>
             <groupId>org.slf4j</groupId>

http://git-wip-us.apache.org/repos/asf/james-project/blob/37829b36/mpt/impl/imap-mailbox/external-james/pom.xml
----------------------------------------------------------------------
diff --git a/mpt/impl/imap-mailbox/external-james/pom.xml b/mpt/impl/imap-mailbox/external-james/pom.xml
index 95132ec..2077d22 100644
--- a/mpt/impl/imap-mailbox/external-james/pom.xml
+++ b/mpt/impl/imap-mailbox/external-james/pom.xml
@@ -67,9 +67,5 @@
             <groupId>org.apache.commons</groupId>
             <artifactId>commons-lang3</artifactId>
         </dependency>
-        <dependency>
-            <groupId>org.jmock</groupId>
-            <artifactId>jmock</artifactId>
-        </dependency>
     </dependencies>
 </project>

http://git-wip-us.apache.org/repos/asf/james-project/blob/37829b36/mpt/pom.xml
----------------------------------------------------------------------
diff --git a/mpt/pom.xml b/mpt/pom.xml
index c2f6595..12b341c 100644
--- a/mpt/pom.xml
+++ b/mpt/pom.xml
@@ -57,7 +57,6 @@
         <guice.version>4.0</guice.version>
         <hadoop.version>1.0.1</hadoop.version>
         <hbase.version>0.94.27</hbase.version>
-        <jmock.version>2.6.0</jmock.version>
         <junit.version>4.11</junit.version>
         <lucene-core.version>3.6.0</lucene-core.version>
         <slf4j.version>1.7.25</slf4j.version>


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


[02/20] james-project git commit: JAMES-2495 Lucene MPT tests can be run with InMemory mailbox impl

Posted by bt...@apache.org.
JAMES-2495 Lucene MPT tests can be run with InMemory mailbox impl


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

Branch: refs/heads/master
Commit: a58e7ddc193d500e684e77eb5afe7302fc27c0c7
Parents: 47968ea
Author: Matthieu Baechler <ma...@apache.org>
Authored: Wed Aug 1 17:04:16 2018 +0200
Committer: Benoit Tellier <bt...@linagora.com>
Committed: Fri Aug 3 15:51:21 2018 +0700

----------------------------------------------------------------------
 .../lucenesearch/LuceneSearchTest.java          | 50 --------------
 .../lucenesearch/LuceneUidSearchTest.java       | 50 --------------
 .../host/LuceneSearchHostSystem.java            | 71 ++++++++------------
 3 files changed, 28 insertions(+), 143 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/a58e7ddc/mpt/impl/imap-mailbox/lucenesearch/src/test/java/org/apache/james/mpt/imapmailbox/lucenesearch/LuceneSearchTest.java
----------------------------------------------------------------------
diff --git a/mpt/impl/imap-mailbox/lucenesearch/src/test/java/org/apache/james/mpt/imapmailbox/lucenesearch/LuceneSearchTest.java b/mpt/impl/imap-mailbox/lucenesearch/src/test/java/org/apache/james/mpt/imapmailbox/lucenesearch/LuceneSearchTest.java
deleted file mode 100644
index b5fe9ed..0000000
--- a/mpt/impl/imap-mailbox/lucenesearch/src/test/java/org/apache/james/mpt/imapmailbox/lucenesearch/LuceneSearchTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one   *
- * or more contributor license agreements.  See the NOTICE file *
- * distributed with this work for additional information        *
- * regarding copyright ownership.  The ASF licenses this file   *
- * to you under the Apache License, Version 2.0 (the            *
- * "License"); you may not use this file except in compliance   *
- * with the License.  You may obtain a copy of the License at   *
- *                                                              *
- *   http://www.apache.org/licenses/LICENSE-2.0                 *
- *                                                              *
- * Unless required by applicable law or agreed to in writing,   *
- * software distributed under the License is distributed on an  *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
- * KIND, either express or implied.  See the License for the    *
- * specific language governing permissions and limitations      *
- * under the License.                                           *
- ****************************************************************/
-
-package org.apache.james.mpt.imapmailbox.lucenesearch;
-
-import org.apache.james.mpt.api.ImapHostSystem;
-import org.apache.james.mpt.imapmailbox.lucenesearch.host.LuceneSearchHostSystem;
-import org.apache.james.mpt.imapmailbox.suite.Search;
-import org.junit.After;
-import org.junit.Before;
-
-public class LuceneSearchTest extends Search {
-
-    private ImapHostSystem system;
-
-    @Override
-    @Before
-    public void setUp() throws Exception {
-        system = new LuceneSearchHostSystem();
-        system.beforeTest();
-        super.setUp();
-    }
-    
-    @Override
-    protected ImapHostSystem createImapHostSystem() {
-        return system;
-    }
-
-    @After
-    public void tearDown() throws Exception {
-        system.afterTest();
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/james-project/blob/a58e7ddc/mpt/impl/imap-mailbox/lucenesearch/src/test/java/org/apache/james/mpt/imapmailbox/lucenesearch/LuceneUidSearchTest.java
----------------------------------------------------------------------
diff --git a/mpt/impl/imap-mailbox/lucenesearch/src/test/java/org/apache/james/mpt/imapmailbox/lucenesearch/LuceneUidSearchTest.java b/mpt/impl/imap-mailbox/lucenesearch/src/test/java/org/apache/james/mpt/imapmailbox/lucenesearch/LuceneUidSearchTest.java
deleted file mode 100644
index 942b73e..0000000
--- a/mpt/impl/imap-mailbox/lucenesearch/src/test/java/org/apache/james/mpt/imapmailbox/lucenesearch/LuceneUidSearchTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one   *
- * or more contributor license agreements.  See the NOTICE file *
- * distributed with this work for additional information        *
- * regarding copyright ownership.  The ASF licenses this file   *
- * to you under the Apache License, Version 2.0 (the            *
- * "License"); you may not use this file except in compliance   *
- * with the License.  You may obtain a copy of the License at   *
- *                                                              *
- *   http://www.apache.org/licenses/LICENSE-2.0                 *
- *                                                              *
- * Unless required by applicable law or agreed to in writing,   *
- * software distributed under the License is distributed on an  *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
- * KIND, either express or implied.  See the License for the    *
- * specific language governing permissions and limitations      *
- * under the License.                                           *
- ****************************************************************/
-
-package org.apache.james.mpt.imapmailbox.lucenesearch;
-
-import org.apache.james.mpt.api.ImapHostSystem;
-import org.apache.james.mpt.imapmailbox.lucenesearch.host.LuceneSearchHostSystem;
-import org.apache.james.mpt.imapmailbox.suite.UidSearch;
-import org.junit.After;
-import org.junit.Before;
-
-public class LuceneUidSearchTest extends UidSearch {
-
-    private ImapHostSystem system;
-
-    @Override
-    @Before
-    public void setUp() throws Exception {
-        system = new LuceneSearchHostSystem();
-        system.beforeTest();
-        super.setUp();
-    }
-    
-    @Override
-    protected ImapHostSystem createImapHostSystem() {
-        return system;
-    }
-
-    @After
-    public void tearDown() throws Exception {
-        system.afterTest();
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/james-project/blob/a58e7ddc/mpt/impl/imap-mailbox/lucenesearch/src/test/java/org/apache/james/mpt/imapmailbox/lucenesearch/host/LuceneSearchHostSystem.java
----------------------------------------------------------------------
diff --git a/mpt/impl/imap-mailbox/lucenesearch/src/test/java/org/apache/james/mpt/imapmailbox/lucenesearch/host/LuceneSearchHostSystem.java b/mpt/impl/imap-mailbox/lucenesearch/src/test/java/org/apache/james/mpt/imapmailbox/lucenesearch/host/LuceneSearchHostSystem.java
index b5f5742..a085f9e 100644
--- a/mpt/impl/imap-mailbox/lucenesearch/src/test/java/org/apache/james/mpt/imapmailbox/lucenesearch/host/LuceneSearchHostSystem.java
+++ b/mpt/impl/imap-mailbox/lucenesearch/src/test/java/org/apache/james/mpt/imapmailbox/lucenesearch/host/LuceneSearchHostSystem.java
@@ -22,11 +22,8 @@ package org.apache.james.mpt.imapmailbox.lucenesearch.host;
 import java.io.File;
 import java.io.IOException;
 
-import javax.persistence.EntityManagerFactory;
-
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.lang.NotImplementedException;
-import org.apache.james.backends.jpa.JpaTestCluster;
 import org.apache.james.core.quota.QuotaCount;
 import org.apache.james.core.quota.QuotaSize;
 import org.apache.james.imap.api.process.ImapProcessor;
@@ -36,27 +33,20 @@ import org.apache.james.imap.processor.main.DefaultImapProcessorFactory;
 import org.apache.james.mailbox.MailboxManager;
 import org.apache.james.mailbox.MailboxSession;
 import org.apache.james.mailbox.SubscriptionManager;
-import org.apache.james.mailbox.acl.GroupMembershipResolver;
-import org.apache.james.mailbox.acl.MailboxACLResolver;
 import org.apache.james.mailbox.acl.SimpleGroupMembershipResolver;
 import org.apache.james.mailbox.acl.UnionMailboxACLResolver;
 import org.apache.james.mailbox.exception.MailboxException;
-import org.apache.james.mailbox.jpa.JPAId;
-import org.apache.james.mailbox.jpa.JPAId.Factory;
-import org.apache.james.mailbox.jpa.JPAMailboxFixture;
-import org.apache.james.mailbox.jpa.JPAMailboxSessionMapperFactory;
-import org.apache.james.mailbox.jpa.JPASubscriptionManager;
-import org.apache.james.mailbox.jpa.mail.JPAModSeqProvider;
-import org.apache.james.mailbox.jpa.mail.JPAUidProvider;
-import org.apache.james.mailbox.jpa.openjpa.OpenJPAMailboxManager;
+import org.apache.james.mailbox.inmemory.InMemoryId;
+import org.apache.james.mailbox.inmemory.InMemoryMailboxManager;
+import org.apache.james.mailbox.inmemory.InMemoryMailboxSessionMapperFactory;
+import org.apache.james.mailbox.inmemory.InMemoryMessageId;
 import org.apache.james.mailbox.lucene.search.LuceneMessageSearchIndex;
-import org.apache.james.mailbox.model.MessageId;
 import org.apache.james.mailbox.store.JVMMailboxPathLocker;
 import org.apache.james.mailbox.store.StoreMailboxAnnotationManager;
 import org.apache.james.mailbox.store.StoreRightManager;
+import org.apache.james.mailbox.store.StoreSubscriptionManager;
 import org.apache.james.mailbox.store.event.DefaultDelegatingMailboxListener;
 import org.apache.james.mailbox.store.event.MailboxEventDispatcher;
-import org.apache.james.mailbox.store.mail.model.DefaultMessageId;
 import org.apache.james.mailbox.store.mail.model.impl.MessageParser;
 import org.apache.james.mailbox.store.quota.DefaultUserQuotaRootResolver;
 import org.apache.james.mailbox.store.quota.NoQuotaManager;
@@ -72,11 +62,10 @@ public class LuceneSearchHostSystem extends JamesImapHostSystem {
     public static final String META_DATA_DIRECTORY = "target/user-meta-data";
     private static final ImapFeatures SUPPORTED_FEATURES = ImapFeatures.of(Feature.NAMESPACE_SUPPORT,
         Feature.MOD_SEQ_SEARCH);
-    private static final JpaTestCluster JPA_TEST_CLUSTER = JpaTestCluster.create(JPAMailboxFixture.MAILBOX_PERSISTANCE_CLASSES);
 
 
     private File tempFile;
-    private OpenJPAMailboxManager mailboxManager;
+    private InMemoryMailboxManager mailboxManager;
 
     @Override
     public void beforeTest() throws Exception {
@@ -92,7 +81,6 @@ public class LuceneSearchHostSystem extends JamesImapHostSystem {
         resetUserMetaData();
         MailboxSession session = mailboxManager.createSystemSession("test");
         mailboxManager.startProcessingRequest(session);
-        mailboxManager.deleteEverything(session);
         mailboxManager.endProcessingRequest(session);
         mailboxManager.logout(session, false);
     }
@@ -106,44 +94,41 @@ public class LuceneSearchHostSystem extends JamesImapHostSystem {
     }
 
     private void initFields() {
-        EntityManagerFactory entityManagerFactory = JPA_TEST_CLUSTER.getEntityManagerFactory();
-        JVMMailboxPathLocker locker = new JVMMailboxPathLocker();
-        JPAUidProvider uidProvider = new JPAUidProvider(locker, entityManagerFactory);
-        JPAModSeqProvider modSeqProvider = new JPAModSeqProvider(locker, entityManagerFactory);
-        JPAMailboxSessionMapperFactory factory = new JPAMailboxSessionMapperFactory(entityManagerFactory, uidProvider, modSeqProvider);
-
+       
         try {
-            JPAId.Factory mailboxIdFactory = new Factory();
-            FSDirectory fsDirectory = FSDirectory.open(tempFile);
-            MessageId.Factory messageIdFactory = new DefaultMessageId.Factory();
-
-            MailboxACLResolver aclResolver = new UnionMailboxACLResolver();
-            GroupMembershipResolver groupMembershipResolver = new SimpleGroupMembershipResolver();
-            MessageParser messageParser = new MessageParser();
+            DefaultDelegatingMailboxListener delegatingMailboxListener = new DefaultDelegatingMailboxListener();
+            MailboxEventDispatcher dispatcher = new MailboxEventDispatcher(delegatingMailboxListener);
+            
+            InMemoryMailboxSessionMapperFactory mapperFactory = new InMemoryMailboxSessionMapperFactory();
+            StoreRightManager rightManager = new StoreRightManager(mapperFactory, new UnionMailboxACLResolver(), new SimpleGroupMembershipResolver(), dispatcher);
+            JVMMailboxPathLocker locker = new JVMMailboxPathLocker();
+            InMemoryMessageId.Factory messageIdFactory = new InMemoryMessageId.Factory();
+            mailboxManager = new InMemoryMailboxManager(mapperFactory,
+                authenticator,
+                authorizator,
+                locker,
+                new MessageParser(),
+                messageIdFactory,
+                dispatcher,
+                delegatingMailboxListener,
+                new StoreMailboxAnnotationManager(mapperFactory, rightManager),
+                rightManager);
 
-            DefaultDelegatingMailboxListener delegatingListener = new DefaultDelegatingMailboxListener();
-            MailboxEventDispatcher mailboxEventDispatcher = new MailboxEventDispatcher(delegatingListener);
-            StoreRightManager storeRightManager = new StoreRightManager(factory, aclResolver, groupMembershipResolver, mailboxEventDispatcher);
-
-            StoreMailboxAnnotationManager annotationManager = new StoreMailboxAnnotationManager(factory, storeRightManager);
-            mailboxManager = new OpenJPAMailboxManager(factory, authenticator, authorizator,
-                messageParser, new DefaultMessageId.Factory(), delegatingListener,
-                mailboxEventDispatcher, annotationManager, storeRightManager);
-
-            LuceneMessageSearchIndex searchIndex = new LuceneMessageSearchIndex(factory, mailboxIdFactory, fsDirectory, messageIdFactory);
+            FSDirectory fsDirectory = FSDirectory.open(tempFile);
+            LuceneMessageSearchIndex searchIndex = new LuceneMessageSearchIndex(mapperFactory, new InMemoryId.Factory(), fsDirectory, messageIdFactory);
             searchIndex.setEnableSuffixMatch(true);
             mailboxManager.setMessageSearchIndex(searchIndex);
 
             mailboxManager.init();
 
-            SubscriptionManager subscriptionManager = new JPASubscriptionManager(factory);
+            SubscriptionManager subscriptionManager = new StoreSubscriptionManager(mapperFactory);
 
             final ImapProcessor defaultImapProcessorFactory =
                 DefaultImapProcessorFactory.createDefaultProcessor(
                     mailboxManager,
                     subscriptionManager,
                     new NoQuotaManager(),
-                    new DefaultUserQuotaRootResolver(factory),
+                    new DefaultUserQuotaRootResolver(mapperFactory),
                     new DefaultMetricFactory());
 
             configure(new DefaultImapDecoderFactory().buildImapDecoder(),


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


[13/20] james-project git commit: JAMES-2513 MemoryDomainList don't need to override 'configure'

Posted by bt...@apache.org.
JAMES-2513 MemoryDomainList don't need to override 'configure'


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

Branch: refs/heads/master
Commit: 26b4081eaa4d47251cc04b10fd97f3483d8d7110
Parents: 7063734
Author: benwa <bt...@linagora.com>
Authored: Thu Aug 2 10:57:02 2018 +0700
Committer: Benoit Tellier <bt...@linagora.com>
Committed: Fri Aug 3 15:51:29 2018 +0700

----------------------------------------------------------------------
 .../james/domainlist/memory/MemoryDomainList.java       | 12 ++----------
 1 file changed, 2 insertions(+), 10 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/26b4081e/server/data/data-memory/src/main/java/org/apache/james/domainlist/memory/MemoryDomainList.java
----------------------------------------------------------------------
diff --git a/server/data/data-memory/src/main/java/org/apache/james/domainlist/memory/MemoryDomainList.java b/server/data/data-memory/src/main/java/org/apache/james/domainlist/memory/MemoryDomainList.java
index 39d5835..c6d89c3 100644
--- a/server/data/data-memory/src/main/java/org/apache/james/domainlist/memory/MemoryDomainList.java
+++ b/server/data/data-memory/src/main/java/org/apache/james/domainlist/memory/MemoryDomainList.java
@@ -24,8 +24,6 @@ import java.util.List;
 
 import javax.inject.Inject;
 
-import org.apache.commons.configuration.ConfigurationException;
-import org.apache.commons.configuration.HierarchicalConfiguration;
 import org.apache.james.core.Domain;
 import org.apache.james.dnsservice.api.DNSService;
 import org.apache.james.domainlist.api.DomainListException;
@@ -44,18 +42,12 @@ public class MemoryDomainList extends AbstractDomainList {
     }
 
     @Override
-    protected List<Domain> getDomainListInternal() throws DomainListException {
+    protected List<Domain> getDomainListInternal() {
         return ImmutableList.copyOf(domains);
     }
 
-
-    @Override
-    public void configure(HierarchicalConfiguration config) throws ConfigurationException {
-        super.configure(config);
-    }
-
     @Override
-    protected boolean containsDomainInternal(Domain domain) throws DomainListException {
+    protected boolean containsDomainInternal(Domain domain) {
         return domains.contains(domain);
     }
 


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


[05/20] james-project git commit: JAMES-2506 Remove jmock from protocols-imap

Posted by bt...@apache.org.
JAMES-2506 Remove jmock from protocols-imap


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

Branch: refs/heads/master
Commit: 6373f39a82f1ed5c90e9fdc7772b872a8dffd1eb
Parents: 37829b3
Author: duc <dt...@linagora.com>
Authored: Mon Jul 30 23:53:07 2018 +0700
Committer: Benoit Tellier <bt...@linagora.com>
Committed: Fri Aug 3 15:51:21 2018 +0700

----------------------------------------------------------------------
 protocols/imap/pom.xml                          |  16 --
 .../decode/ImapRequestStreamLineReader.java     |   2 +-
 .../james/imap/api/ImapConfigurationTest.java   |  28 +--
 .../james/imap/api/message/UidRangeTest.java    |   2 +-
 .../message/response/StatusResponseTest.java    |   4 +-
 .../imap/decode/FetchPartPathDecoderTest.java   |   6 +-
 .../decode/parser/CreateCommandParserTest.java  |   4 +-
 .../FetchCommandParserPartialFetchTest.java     |  30 +---
 .../SearchCommandParserAndParenthesesTest.java  |   9 -
 .../parser/SearchCommandParserCharsetTest.java  |  41 ++---
 .../parser/SearchCommandParserNotTest.java      |   9 -
 .../parser/SearchCommandParserOrTest.java       |  10 +-
 .../SearchCommandParserQuotedCharsetTest.java   |  36 ++--
 ...chCommandParserSearchKeySequenceSetTest.java |  10 --
 .../SearchCommandParserSearchKeyTest.java       |   9 -
 .../SearchCommandParserTopLevelAndTest.java     |   9 -
 .../decode/parser/StoreCommandParserTest.java   |  14 +-
 .../encode/AnnotationResponseEncoderTest.java   |   4 +-
 .../encode/EncoderUtilsDateTimeLocaleTest.java  |  20 +--
 .../FetchResponseEncoderEnvelopeTest.java       |  50 +++---
 .../FetchResponseEncoderNoExtensionsTest.java   |  47 ++---
 .../imap/encode/FetchResponseEncoderTest.java   |  13 +-
 .../imap/encode/LSubResponseEncoderTest.java    |   9 +-
 .../imap/encode/ListResponseEncoderTest.java    |  11 +-
 .../MailboxStatusResponseEncoderTest.java       |  14 +-
 .../encode/NamespaceResponseEncoderTest.java    | 155 +++++++---------
 .../imap/encode/SearchResponseEncoderTest.java  |   9 +-
 .../imap/encode/XListResponseEncoderTest.java   |  11 +-
 ...ImapRequestHandlerAdandonConnectionTest.java |  34 +---
 .../james/imap/processor/CopyProcessorTest.java |   2 +-
 .../processor/GetQuotaRootProcessorTest.java    | 141 ++++++---------
 .../james/imap/processor/LSubProcessorTest.java | 128 +++++--------
 .../james/imap/processor/MoveProcessorTest.java |   2 +-
 .../imap/processor/NamespaceProcessorTest.java  | 131 ++++++--------
 .../imap/processor/SearchProcessorTest.java     | 178 ++++++++-----------
 .../imap/processor/SetQuotaProcessorTest.java   |   2 +-
 .../base/MailboxEventAnalyserTest.java          |  18 +-
 .../processor/base/SelectedMailboxImplTest.java |   3 +-
 .../fetch/MailboxMessageResultUtilsTest.java    |   5 +-
 .../fetch/PartialFetchBodyElementTest.java      |  89 +++-------
 .../protocols/imap/utils/DecoderUtilsTest.java  |  12 +-
 41 files changed, 489 insertions(+), 838 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/pom.xml
----------------------------------------------------------------------
diff --git a/protocols/imap/pom.xml b/protocols/imap/pom.xml
index 484cfe4..d328e6d 100644
--- a/protocols/imap/pom.xml
+++ b/protocols/imap/pom.xml
@@ -110,22 +110,6 @@
             <scope>test</scope>
         </dependency>
         <dependency>
-            <groupId>org.jmock</groupId>
-            <artifactId>jmock</artifactId>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.jmock</groupId>
-            <artifactId>jmock-junit4</artifactId>
-            <scope>test</scope>
-            <exclusions>
-                <exclusion>
-                    <groupId>junit</groupId>
-                    <artifactId>junit-dep</artifactId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-        <dependency>
             <groupId>org.mockito</groupId>
             <artifactId>mockito-core</artifactId>
             <scope>test</scope>

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/main/java/org/apache/james/imap/decode/ImapRequestStreamLineReader.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/main/java/org/apache/james/imap/decode/ImapRequestStreamLineReader.java b/protocols/imap/src/main/java/org/apache/james/imap/decode/ImapRequestStreamLineReader.java
index 4fedc02..c00aae1 100644
--- a/protocols/imap/src/main/java/org/apache/james/imap/decode/ImapRequestStreamLineReader.java
+++ b/protocols/imap/src/main/java/org/apache/james/imap/decode/ImapRequestStreamLineReader.java
@@ -73,7 +73,7 @@ public class ImapRequestStreamLineReader extends ImapRequestLineReader {
     }
 
     @Override
-    public InputStream read(int size, boolean extraCRLF) throws DecodingException {
+    public InputStream read(int size, boolean extraCRLF) {
 
         // Unset the next char.
         nextSeen = false;

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/api/ImapConfigurationTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/api/ImapConfigurationTest.java b/protocols/imap/src/test/java/org/apache/james/imap/api/ImapConfigurationTest.java
index e169e84..b8697d7 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/api/ImapConfigurationTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/api/ImapConfigurationTest.java
@@ -41,14 +41,14 @@ public class ImapConfigurationTest {
     }
 
     @Test
-    public void idleKeepAliveShouldBeDefaultValueWhenNoSetting() throws Exception {
+    public void idleKeepAliveShouldBeDefaultValueWhenNoSetting() {
         ImapConfiguration imapConfiguration = ImapConfiguration.builder().build();
 
         assertThat(imapConfiguration.getIdleTimeInterval()).isEqualTo(ImapConfiguration.DEFAULT_HEARTBEAT_INTERVAL_IN_SECONDS);
     }
 
     @Test
-    public void idleKeepAliveShouldReturnSetValue() throws Exception {
+    public void idleKeepAliveShouldReturnSetValue() {
         long idleValue  = 1;
         ImapConfiguration imapConfiguration = ImapConfiguration.builder()
                 .idleTimeInterval(idleValue)
@@ -58,7 +58,7 @@ public class ImapConfigurationTest {
     }
 
     @Test
-    public void idleKeepAliveShouldThrowWhenRezo() throws Exception {
+    public void idleKeepAliveShouldThrowWhenRezo() {
         expectedException.expect(IllegalArgumentException.class);
 
         ImapConfiguration.builder()
@@ -67,7 +67,7 @@ public class ImapConfigurationTest {
     }
 
     @Test
-    public void idleKeepAliveShouldThrowWhenNegative() throws Exception {
+    public void idleKeepAliveShouldThrowWhenNegative() {
         expectedException.expect(IllegalArgumentException.class);
 
         ImapConfiguration.builder()
@@ -76,14 +76,14 @@ public class ImapConfigurationTest {
     }
 
     @Test
-    public void millisecondsShouldBeDefaultValueWhenNoSetting() throws Exception {
+    public void millisecondsShouldBeDefaultValueWhenNoSetting() {
         ImapConfiguration imapConfiguration = ImapConfiguration.builder().build();
 
         assertThat(imapConfiguration.getIdleTimeIntervalUnit()).isEqualTo(ImapConfiguration.DEFAULT_HEARTBEAT_INTERVAL_UNIT);
     }
 
     @Test
-    public void millisecondsShouldReturnSetValue() throws Exception {
+    public void millisecondsShouldReturnSetValue() {
         ImapConfiguration imapConfiguration = ImapConfiguration.builder()
                 .idleTimeIntervalUnit(TimeUnit.MINUTES)
                 .build();
@@ -92,7 +92,7 @@ public class ImapConfigurationTest {
     }
 
     @Test
-    public void disabledCapsShouldBeEmptyAsDefault() throws Exception {
+    public void disabledCapsShouldBeEmptyAsDefault() {
         ImapConfiguration imapConfiguration = ImapConfiguration.builder()
                 .build();
 
@@ -100,7 +100,7 @@ public class ImapConfigurationTest {
     }
 
     @Test
-    public void disabledCapsShouldReturnSetValue() throws Exception {
+    public void disabledCapsShouldReturnSetValue() {
         ImapConfiguration imapConfiguration = ImapConfiguration.builder()
                 .disabledCaps(ImmutableSet.of("AnyValue"))
                 .build();
@@ -109,7 +109,7 @@ public class ImapConfigurationTest {
     }
 
     @Test
-    public void disabledCapsShouldReturnMultipleSetValues() throws Exception {
+    public void disabledCapsShouldReturnMultipleSetValues() {
         ImapConfiguration imapConfiguration = ImapConfiguration.builder()
                 .disabledCaps(ImmutableSet.of("AnyValue", "OtherValue"))
                 .build();
@@ -118,7 +118,7 @@ public class ImapConfigurationTest {
     }
 
     @Test
-    public void disabledCapsShouldReturnMultipleSetValuesWithNormalizeValue() throws Exception {
+    public void disabledCapsShouldReturnMultipleSetValuesWithNormalizeValue() {
         ImapConfiguration imapConfiguration = ImapConfiguration.builder()
                 .disabledCaps(ImmutableSet.of("   AnyValue   ", "  OtherValue   "))
                 .build();
@@ -127,7 +127,7 @@ public class ImapConfigurationTest {
     }
 
     @Test
-    public void disabledCapsFromStringArrayShouldReturnMultipleSetValuesWithNormalizeValue() throws Exception {
+    public void disabledCapsFromStringArrayShouldReturnMultipleSetValuesWithNormalizeValue() {
         ImapConfiguration imapConfiguration = ImapConfiguration.builder()
                 .disabledCaps("   AnyValue   ", "  OtherValue   ")
                 .build();
@@ -136,7 +136,7 @@ public class ImapConfigurationTest {
     }
 
     @Test
-    public void disabledCapShouldReturnMultipleStringWithNormalizeValue() throws Exception {
+    public void disabledCapShouldReturnMultipleStringWithNormalizeValue() {
         ImapConfiguration imapConfiguration = ImapConfiguration.builder()
                 .disabledCap("   AnyValue   ")
                 .build();
@@ -145,7 +145,7 @@ public class ImapConfigurationTest {
     }
 
     @Test
-    public void idleShouldEnableByDefault() throws Exception {
+    public void idleShouldEnableByDefault() {
         ImapConfiguration imapConfiguration = ImapConfiguration.builder()
                 .build();
 
@@ -153,7 +153,7 @@ public class ImapConfigurationTest {
     }
 
     @Test
-    public void idleShouldBeDisable() throws Exception {
+    public void idleShouldBeDisable() {
         ImapConfiguration imapConfiguration = ImapConfiguration.builder()
                 .enableIdle(false)
                 .build();

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/api/message/UidRangeTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/api/message/UidRangeTest.java b/protocols/imap/src/test/java/org/apache/james/imap/api/message/UidRangeTest.java
index 06d400d..96aae02 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/api/message/UidRangeTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/api/message/UidRangeTest.java
@@ -117,7 +117,7 @@ public class UidRangeTest {
     
     @Test
     public void mergeZeroRangeShouldOutputZeroRange() {
-        assertThat(UidRange.mergeRanges(ImmutableList.<UidRange>of())).isEmpty();
+        assertThat(UidRange.mergeRanges(ImmutableList.of())).isEmpty();
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/api/message/response/StatusResponseTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/api/message/response/StatusResponseTest.java b/protocols/imap/src/test/java/org/apache/james/imap/api/message/response/StatusResponseTest.java
index 81ee9f9..99d709a 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/api/message/response/StatusResponseTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/api/message/response/StatusResponseTest.java
@@ -28,7 +28,7 @@ import org.junit.Test;
 public class StatusResponseTest  {
 
     @Test
-    public void testResponseCodeExtension() throws Exception {
+    public void testResponseCodeExtension() {
         assertEquals("Preserve names beginning with X", "XEXTENSION",
                 StatusResponse.ResponseCode.createExtension("XEXTENSION")
                         .getCode());
@@ -38,7 +38,7 @@ public class StatusResponseTest  {
     }
 
     @Test
-    public void responseCodeShouldBuildTheLongestEntryForMetadata() throws Exception {
+    public void responseCodeShouldBuildTheLongestEntryForMetadata() {
         assertThat(StatusResponse.ResponseCode.longestMetadataEntry(1024).getCode()).isEqualTo("METADATA LONGENTRIES");
         assertThat(StatusResponse.ResponseCode.longestMetadataEntry(1024).getNumber()).isEqualTo(1024);
     }

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/decode/FetchPartPathDecoderTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/decode/FetchPartPathDecoderTest.java b/protocols/imap/src/test/java/org/apache/james/imap/decode/FetchPartPathDecoderTest.java
index 98d4072..8ffdce1 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/decode/FetchPartPathDecoderTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/decode/FetchPartPathDecoderTest.java
@@ -128,8 +128,7 @@ public class FetchPartPathDecoderTest {
     }
 
     @Test
-    public void testShouldThrowProtocolExceptionWhenSpecifierBogus()
-            throws Exception {
+    public void testShouldThrowProtocolExceptionWhenSpecifierBogus() {
         try {
             decoder.decode("1.34.BOGUS");
             fail("Expected protocol exception to be thrown");
@@ -139,8 +138,7 @@ public class FetchPartPathDecoderTest {
     }
 
     @Test
-    public void testShouldThrowProtocolExceptionWhenPathBogus()
-            throws Exception {
+    public void testShouldThrowProtocolExceptionWhenPathBogus() {
         try {
             decoder.decode("1.34.BOGUS.44.34234.324");
             fail("Expected protocol exception to be thrown");

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/CreateCommandParserTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/CreateCommandParserTest.java b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/CreateCommandParserTest.java
index ae1c813..bbba010 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/CreateCommandParserTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/CreateCommandParserTest.java
@@ -60,7 +60,7 @@ public class CreateCommandParserTest {
     }
 
     @Test
-    public void decodeShouldThrowWhenCommandHasEmptyMailbox() throws DecodingException {
+    public void decodeShouldThrowWhenCommandHasEmptyMailbox() {
         InputStream inputStream = new ByteArrayInputStream(" \n".getBytes(StandardCharsets.US_ASCII));
         ImapRequestStreamLineReader lineReader = new ImapRequestStreamLineReader(inputStream, outputStream);
 
@@ -69,7 +69,7 @@ public class CreateCommandParserTest {
     }
 
     @Test
-    public void decodeShouldThrowWhenCommandHasOnlySeparatorMailbox() throws DecodingException {
+    public void decodeShouldThrowWhenCommandHasOnlySeparatorMailbox() {
         InputStream inputStream = new ByteArrayInputStream("..\n".getBytes(StandardCharsets.US_ASCII));
         ImapRequestStreamLineReader lineReader = new ImapRequestStreamLineReader(inputStream, outputStream);
 

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/FetchCommandParserPartialFetchTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/FetchCommandParserPartialFetchTest.java b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/FetchCommandParserPartialFetchTest.java
index 3993c54..ce73caf 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/FetchCommandParserPartialFetchTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/FetchCommandParserPartialFetchTest.java
@@ -19,11 +19,13 @@
 
 package org.apache.james.imap.decode.parser;
 
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 
 import org.apache.james.imap.api.ImapCommand;
-import org.apache.james.imap.api.ImapMessage;
 import org.apache.james.imap.api.message.BodyFetchElement;
 import org.apache.james.imap.api.message.FetchData;
 import org.apache.james.imap.api.message.IdRange;
@@ -31,32 +33,22 @@ import org.apache.james.imap.api.process.ImapSession;
 import org.apache.james.imap.decode.ImapRequestLineReader;
 import org.apache.james.imap.decode.ImapRequestStreamLineReader;
 import org.apache.james.protocols.imap.DecodingException;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
 public class FetchCommandParserPartialFetchTest  {
 
-    Mockery context = new JUnit4Mockery();
-    
     FetchCommandParser parser;
-
     ImapCommand command;
-
-    ImapMessage message;
     ImapSession session;
 
     @Before
     public void setUp() throws Exception {
         parser = new FetchCommandParser();
         command = ImapCommand.anyStateCommand("Command");
-        message = context.mock(ImapMessage.class);
-        session = context.mock(ImapSession.class);
-        
+        session = mock(ImapSession.class);
     }
 
-
     @Test
     public void testShouldParseZeroAndLength() throws Exception {
         IdRange[] ranges = { new IdRange(1) };
@@ -77,16 +69,12 @@ public class FetchCommandParserPartialFetchTest  {
 
     @Test
     public void testShouldNotParseZeroLength() throws Exception {
-        try {
-            ImapRequestLineReader reader = new ImapRequestStreamLineReader(
-                    new ByteArrayInputStream("1 (BODY[]<20.0>)\r\n"
-                            .getBytes("US-ASCII")), new ByteArrayOutputStream());
-            parser.decode(command, reader, "A01", false, session);                
-            throw new Exception("Number of octets must be non-zero");
+        ImapRequestLineReader reader = new ImapRequestStreamLineReader(
+                new ByteArrayInputStream("1 (BODY[]<20.0>)\r\n"
+                        .getBytes("US-ASCII")), new ByteArrayOutputStream());
 
-        } catch (DecodingException e) {
-            // expected
-        }
+        assertThatThrownBy(() -> parser.decode(command, reader, "A01", false, session))
+            .isInstanceOf(DecodingException.class);
     }
 
     private void check(String input, IdRange[] idSet,

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserAndParenthesesTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserAndParenthesesTest.java b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserAndParenthesesTest.java
index 9d08096..2842228 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserAndParenthesesTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserAndParenthesesTest.java
@@ -29,7 +29,6 @@ import java.util.Arrays;
 import java.util.List;
 
 import org.apache.james.imap.api.ImapCommand;
-import org.apache.james.imap.api.ImapMessage;
 import org.apache.james.imap.api.message.IdRange;
 import org.apache.james.imap.api.message.UidRange;
 import org.apache.james.imap.api.message.request.DayMonthYear;
@@ -38,14 +37,11 @@ import org.apache.james.imap.decode.ImapRequestLineReader;
 import org.apache.james.imap.decode.ImapRequestStreamLineReader;
 import org.apache.james.mailbox.MessageUid;
 import org.apache.james.protocols.imap.DecodingException;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
 public class SearchCommandParserAndParenthesesTest {
 
-    private Mockery context = new JUnit4Mockery();
     Input[] variety = { sequence(), uid(), fromHeader(), since(),
             stringQuoted(), stringUnquoted(), draft(), mailingListHeader(),
             on(), unanswered() };
@@ -151,17 +147,12 @@ public class SearchCommandParserAndParenthesesTest {
     }
 
     SearchCommandParser parser;
-
-
     ImapCommand command;
 
-    ImapMessage message;
-
     @Before
     public void setUp() throws Exception {
         parser = new SearchCommandParser();
         command = ImapCommand.anyStateCommand("Command");
-        message = context.mock(ImapMessage.class);
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserCharsetTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserCharsetTest.java b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserCharsetTest.java
index d30279b..250721a 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserCharsetTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserCharsetTest.java
@@ -20,6 +20,12 @@
 package org.apache.james.imap.decode.parser;
 
 import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.same;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
@@ -35,9 +41,6 @@ import org.apache.james.imap.api.message.response.StatusResponseFactory;
 import org.apache.james.imap.api.process.ImapSession;
 import org.apache.james.imap.decode.ImapRequestLineReader;
 import org.apache.james.imap.decode.ImapRequestStreamLineReader;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -64,14 +67,8 @@ public class SearchCommandParserCharsetTest {
             ASCII);
 
     SearchCommandParser parser;
-
     StatusResponseFactory mockStatusResponseFactory;
-
-    private Mockery context = new JUnit4Mockery();
-
-    
     ImapCommand command;
-
     ImapMessage message;
 
     private ImapSession session;
@@ -80,29 +77,27 @@ public class SearchCommandParserCharsetTest {
     public void setUp() throws Exception {
         parser = new SearchCommandParser();
         command = ImapCommand.anyStateCommand("Command");
-        message = context.mock(ImapMessage.class);
-        session = context.mock(ImapSession.class);
+        message = mock(ImapMessage.class);
+        session = mock(ImapSession.class);
 
-        mockStatusResponseFactory = context.mock(StatusResponseFactory.class);
+        mockStatusResponseFactory = mock(StatusResponseFactory.class);
         parser.setStatusResponseFactory(mockStatusResponseFactory);
     }
 
-
     @Test
-    public void testBadCharset() throws Exception {
-        context.checking(new Expectations() {{
-                oneOf(mockStatusResponseFactory).taggedNo(
-                        with(equal(TAG)), 
-                        with(same(command)), 
-                        with(equal(HumanReadableText.BAD_CHARSET)),
-                        with(equal(StatusResponse.ResponseCode.badCharset(CharsetUtil.getAvailableCharsetNames()))));
-                }
-            }
-        );
+    public void testBadCharsetMockito() throws Exception {
         ImapRequestLineReader reader = new ImapRequestStreamLineReader(
                 new ByteArrayInputStream("CHARSET BOGUS ".getBytes("US-ASCII")),
                 new ByteArrayOutputStream());
         parser.decode(command, reader, TAG, false, session);
+
+        verify(mockStatusResponseFactory, times(1)).taggedNo(
+            eq(TAG),
+            same(command),
+            eq(HumanReadableText.BAD_CHARSET),
+            eq(StatusResponse.ResponseCode.badCharset(CharsetUtil.getAvailableCharsetNames())));
+
+        verifyNoMoreInteractions(mockStatusResponseFactory);
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserNotTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserNotTest.java b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserNotTest.java
index bd6e859..bf9a2e3 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserNotTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserNotTest.java
@@ -27,7 +27,6 @@ import java.util.Arrays;
 import java.util.List;
 
 import org.apache.james.imap.api.ImapCommand;
-import org.apache.james.imap.api.ImapMessage;
 import org.apache.james.imap.api.message.IdRange;
 import org.apache.james.imap.api.message.UidRange;
 import org.apache.james.imap.api.message.request.DayMonthYear;
@@ -35,26 +34,18 @@ import org.apache.james.imap.api.message.request.SearchKey;
 import org.apache.james.imap.decode.ImapRequestLineReader;
 import org.apache.james.imap.decode.ImapRequestStreamLineReader;
 import org.apache.james.mailbox.MessageUid;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
 public class SearchCommandParserNotTest {
 
     SearchCommandParser parser;
-
     ImapCommand command;
-
-    ImapMessage message;
-
-    private Mockery context = new JUnit4Mockery();
     
     @Before
     public void setUp() throws Exception {
         parser = new SearchCommandParser();
         command = ImapCommand.anyStateCommand("Command");
-        message = context.mock(ImapMessage.class);
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserOrTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserOrTest.java b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserOrTest.java
index f87c5ad..ddd93ea 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserOrTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserOrTest.java
@@ -26,7 +26,6 @@ import java.io.ByteArrayOutputStream;
 import java.util.Arrays;
 
 import org.apache.james.imap.api.ImapCommand;
-import org.apache.james.imap.api.ImapMessage;
 import org.apache.james.imap.api.message.IdRange;
 import org.apache.james.imap.api.message.UidRange;
 import org.apache.james.imap.api.message.request.DayMonthYear;
@@ -34,25 +33,18 @@ import org.apache.james.imap.api.message.request.SearchKey;
 import org.apache.james.imap.decode.ImapRequestLineReader;
 import org.apache.james.imap.decode.ImapRequestStreamLineReader;
 import org.apache.james.mailbox.MessageUid;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
 public class SearchCommandParserOrTest {
-    SearchCommandParser parser;
 
+    SearchCommandParser parser;
     ImapCommand command;
 
-    ImapMessage message;
-
-    private Mockery context = new JUnit4Mockery();
-    
     @Before
     public void setUp() throws Exception {
         parser = new SearchCommandParser();
         command = ImapCommand.anyStateCommand("Command");
-        message = context.mock(ImapMessage.class);
     }
     
     public Input sequence() {

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserQuotedCharsetTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserQuotedCharsetTest.java b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserQuotedCharsetTest.java
index 97a4ec2..c3a8da3 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserQuotedCharsetTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserQuotedCharsetTest.java
@@ -21,6 +21,12 @@ package org.apache.james.imap.decode.parser;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.fail;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.same;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
@@ -37,9 +43,6 @@ import org.apache.james.imap.api.process.ImapSession;
 import org.apache.james.imap.decode.ImapRequestLineReader;
 import org.apache.james.imap.decode.ImapRequestStreamLineReader;
 import org.apache.james.protocols.imap.DecodingException;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -129,24 +132,19 @@ public class SearchCommandParserQuotedCharsetTest {
     }
 
     SearchCommandParser parser;
-
     StatusResponseFactory mockStatusResponseFactory;
-
     ImapCommand command;
-
     ImapMessage message;
 
-    private Mockery mockery = new JUnit4Mockery();
-
     private ImapSession session;
     
     @Before
     public void setUp() throws Exception {
         parser = new SearchCommandParser();
         command = ImapCommand.anyStateCommand("Command");
-        message = mockery.mock(ImapMessage.class);
-        mockStatusResponseFactory = mockery.mock(StatusResponseFactory.class);
-        session = mockery.mock(ImapSession.class);
+        message = mock(ImapMessage.class);
+        mockStatusResponseFactory = mock(StatusResponseFactory.class);
+        session = mock(ImapSession.class);
 
         parser.setStatusResponseFactory(mockStatusResponseFactory);
     }
@@ -177,19 +175,17 @@ public class SearchCommandParserQuotedCharsetTest {
 
     @Test
     public void testBadCharset() throws Exception {      
-        mockery.checking(new Expectations() {{
-                oneOf(mockStatusResponseFactory).taggedNo(
-                        with(equal(TAG)), 
-                        with(same(command)), 
-                        with(equal(HumanReadableText.BAD_CHARSET)),
-                        with(equal(StatusResponse.ResponseCode.badCharset(CharsetUtil.getAvailableCharsetNames()))));
-                }
-            }
-        );
         ImapRequestLineReader reader = new ImapRequestStreamLineReader(
                 new ByteArrayInputStream("CHARSET BOGUS ".getBytes("US-ASCII")),
                 new ByteArrayOutputStream());
         parser.decode(command, reader, TAG, false, session);
+
+        verify(mockStatusResponseFactory, times(1)).taggedNo(
+            eq(TAG),
+            same(command),
+            eq(HumanReadableText.BAD_CHARSET),
+            eq(StatusResponse.ResponseCode.badCharset(CharsetUtil.getAvailableCharsetNames())));
+        verifyNoMoreInteractions(mockStatusResponseFactory);
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserSearchKeySequenceSetTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserSearchKeySequenceSetTest.java b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserSearchKeySequenceSetTest.java
index 095b718..e41293e 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserSearchKeySequenceSetTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserSearchKeySequenceSetTest.java
@@ -26,34 +26,24 @@ import java.io.ByteArrayOutputStream;
 import java.util.Arrays;
 
 import org.apache.james.imap.api.ImapCommand;
-import org.apache.james.imap.api.ImapMessage;
 import org.apache.james.imap.api.message.IdRange;
 import org.apache.james.imap.api.message.UidRange;
 import org.apache.james.imap.api.message.request.SearchKey;
 import org.apache.james.imap.decode.ImapRequestLineReader;
 import org.apache.james.imap.decode.ImapRequestStreamLineReader;
 import org.apache.james.mailbox.MessageUid;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
 public class SearchCommandParserSearchKeySequenceSetTest {
 
     SearchCommandParser parser;
-
-
     ImapCommand command;
 
-    ImapMessage message;
-
-    private Mockery mockery = new JUnit4Mockery();
-    
     @Before
     public void setUp() throws Exception {
         parser = new SearchCommandParser();
         command = ImapCommand.anyStateCommand("Command");
-        message = mockery.mock(ImapMessage.class);
     }
     
     @Test

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserSearchKeyTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserSearchKeyTest.java b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserSearchKeyTest.java
index f7513f2..aed0a81 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserSearchKeyTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserSearchKeyTest.java
@@ -35,8 +35,6 @@ import org.apache.james.imap.decode.ImapRequestLineReader;
 import org.apache.james.imap.decode.ImapRequestStreamLineReader;
 import org.apache.james.mailbox.MessageUid;
 import org.apache.james.protocols.imap.DecodingException;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -45,22 +43,15 @@ public class SearchCommandParserSearchKeyTest {
     private static final DayMonthYear DATE = new DayMonthYear(1, 1, 2000);
 
     SearchCommandParser parser;
-    
     ImapCommand command;
-
     ImapMessage message;
 
-    private Mockery mockery = new JUnit4Mockery();
-
     @Before
     public void setUp() throws Exception {
         parser = new SearchCommandParser();
         command = ImapCommand.anyStateCommand("Command");
-        message = mockery.mock(ImapMessage.class);
     }
 
-    
-
     @Test
     public void testShouldParseAll() throws Exception {
         SearchKey key = SearchKey.buildAll();

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserTopLevelAndTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserTopLevelAndTest.java b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserTopLevelAndTest.java
index febe499..a31643b 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserTopLevelAndTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/SearchCommandParserTopLevelAndTest.java
@@ -29,7 +29,6 @@ import java.util.Arrays;
 import java.util.List;
 
 import org.apache.james.imap.api.ImapCommand;
-import org.apache.james.imap.api.ImapMessage;
 import org.apache.james.imap.api.message.IdRange;
 import org.apache.james.imap.api.message.UidRange;
 import org.apache.james.imap.api.message.request.DayMonthYear;
@@ -38,8 +37,6 @@ import org.apache.james.imap.decode.ImapRequestLineReader;
 import org.apache.james.imap.decode.ImapRequestStreamLineReader;
 import org.apache.james.mailbox.MessageUid;
 import org.apache.james.protocols.imap.DecodingException;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -136,18 +133,12 @@ public class SearchCommandParserTopLevelAndTest {
     }
 
     SearchCommandParser parser;
-
     ImapCommand command;
 
-    ImapMessage message;
-
-    private Mockery mockery = new JUnit4Mockery();
-    
     @Before
     public void setUp() throws Exception {
         parser = new SearchCommandParser();
         command = ImapCommand.anyStateCommand("Command");
-        message = mockery.mock(ImapMessage.class);
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/StoreCommandParserTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/StoreCommandParserTest.java b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/StoreCommandParserTest.java
index 470ff88..865a2bc 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/StoreCommandParserTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/decode/parser/StoreCommandParserTest.java
@@ -19,6 +19,8 @@
 
 package org.apache.james.imap.decode.parser;
 
+import static org.mockito.Mockito.mock;
+
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 
@@ -30,32 +32,22 @@ import org.apache.james.imap.api.message.IdRange;
 import org.apache.james.imap.api.process.ImapSession;
 import org.apache.james.imap.decode.ImapRequestLineReader;
 import org.apache.james.imap.decode.ImapRequestStreamLineReader;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
 public class StoreCommandParserTest {
 
     StoreCommandParser parser;
-
-
     ImapCommand command;
-
     ImapMessage message;
 
-    private Mockery mockery = new JUnit4Mockery();
-
-
     private ImapSession session;
 
     @Before
     public void setUp() throws Exception {
         parser = new StoreCommandParser();
         command = ImapCommand.anyStateCommand("Command");
-        message = mockery.mock(ImapMessage.class);
-        session = mockery.mock(ImapSession.class);
-
+        session = mock(ImapSession.class);
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/encode/AnnotationResponseEncoderTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/encode/AnnotationResponseEncoderTest.java b/protocols/imap/src/test/java/org/apache/james/imap/encode/AnnotationResponseEncoderTest.java
index 66ea607..3f7b4c8 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/encode/AnnotationResponseEncoderTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/encode/AnnotationResponseEncoderTest.java
@@ -58,7 +58,7 @@ public class AnnotationResponseEncoderTest {
 
     @Test
     public void encodingShouldWellFormEmptyRequest() throws Exception {
-        AnnotationResponse response = new AnnotationResponse(null, ImmutableList.<MailboxAnnotation>of());
+        AnnotationResponse response = new AnnotationResponse(null, ImmutableList.of());
 
         encoder.encode(response, composer, imapSession);
 
@@ -67,7 +67,7 @@ public class AnnotationResponseEncoderTest {
 
     @Test
     public void encodingShouldWellFormWhenEmptyReturnedAnnotation() throws Exception {
-        AnnotationResponse response = new AnnotationResponse("INBOX", ImmutableList.<MailboxAnnotation>of());
+        AnnotationResponse response = new AnnotationResponse("INBOX", ImmutableList.of());
 
         encoder.encode(response, composer, imapSession);
 

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/encode/EncoderUtilsDateTimeLocaleTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/encode/EncoderUtilsDateTimeLocaleTest.java b/protocols/imap/src/test/java/org/apache/james/imap/encode/EncoderUtilsDateTimeLocaleTest.java
index 4fad41a..cf25839 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/encode/EncoderUtilsDateTimeLocaleTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/encode/EncoderUtilsDateTimeLocaleTest.java
@@ -37,52 +37,52 @@ public class EncoderUtilsDateTimeLocaleTest  {
     }
 
     @Test
-    public void testUS() throws Exception {
+    public void testUS() {
         runTests(Locale.US);
     }
     
     @Test
-    public void testUK() throws Exception {
+    public void testUK() {
         runTests(Locale.UK);
     }
 
     @Test
-    public void testITALY() throws Exception {
+    public void testITALY() {
         runTests(Locale.ITALY);
     }
 
     @Test
-    public void testGERMANY() throws Exception {
+    public void testGERMANY() {
         runTests(Locale.GERMANY);
     }
 
     @Test
-    public void testFRANCE() throws Exception {
+    public void testFRANCE() {
         runTests(Locale.FRANCE);
     }
 
     @Test
-    public void testCANADA() throws Exception {
+    public void testCANADA() {
         runTests(Locale.CANADA);
     }
 
     @Test
-    public void testCHINA() throws Exception {
+    public void testCHINA() {
         runTests(Locale.CHINA);
     }
 
     @Test
-    public void testJAPAN() throws Exception {
+    public void testJAPAN() {
         runTests(Locale.JAPAN);
     }
 
     @Test
-    public void testKOREA() throws Exception {
+    public void testKOREA() {
         runTests(Locale.KOREA);
     }
 
     @Test
-    public void testTAIWAN() throws Exception {
+    public void testTAIWAN() {
         runTests(Locale.TAIWAN);
     }
 

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderEnvelopeTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderEnvelopeTest.java b/protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderEnvelopeTest.java
index dcb6dee..f3d7397 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderEnvelopeTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderEnvelopeTest.java
@@ -20,14 +20,13 @@
 package org.apache.james.imap.encode;
 
 import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 
 import org.apache.james.imap.encode.base.ByteImapResponseWriter;
 import org.apache.james.imap.encode.base.ImapResponseComposerImpl;
 import org.apache.james.imap.message.response.FetchResponse;
 import org.apache.james.imap.message.response.FetchResponse.Envelope.Address;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -52,8 +51,6 @@ public class FetchResponseEncoderEnvelopeTest {
 
     private static final int MSN = 100;
 
-    private Mockery context = new JUnit4Mockery();
-    
 
     private ImapEncoder mockNextEncoder;
 
@@ -89,7 +86,7 @@ public class FetchResponseEncoderEnvelopeTest {
     
     @Before
     public void setUp() throws Exception {
-        envelope = context.mock(FetchResponse.Envelope.class);
+        envelope = mock(FetchResponse.Envelope.class);
 
         bcc = null;
         cc = null;
@@ -103,7 +100,7 @@ public class FetchResponseEncoderEnvelopeTest {
         to = null;
 
         message = new FetchResponse(MSN, null, null, null, null, null, envelope, null, null, null);
-        mockNextEncoder = context.mock(ImapEncoder.class);
+        mockNextEncoder = mock(ImapEncoder.class);
         encoder = new FetchResponseEncoder(mockNextEncoder, false);
     }
 
@@ -122,33 +119,26 @@ public class FetchResponseEncoderEnvelopeTest {
 
     private Address mockAddress(final String name, final String domainList,
             final String mailbox, final String host) {
-        final Address address = context.mock(Address.class, name + host);
-        context.checking(new Expectations() {{
-                    oneOf(address).getPersonalName();will(returnValue(name));
-                    oneOf(address).getAtDomainList();will(returnValue(domainList));
-                    oneOf(address).getMailboxName();will(returnValue(mailbox));
-                    oneOf(address).getHostName();will(returnValue(host));
-                }
-            }
-        );
+        Address address = mock(Address.class);
+
+        when(address.getPersonalName()).thenReturn(name);
+        when(address.getAtDomainList()).thenReturn(domainList);
+        when(address.getMailboxName()).thenReturn(mailbox);
+        when(address.getHostName()).thenReturn(host);
         return address;
     }
 
     private void envelopExpects() {
-        context.checking(new Expectations() {{
-                oneOf(envelope).getBcc();will(returnValue(bcc));
-                oneOf(envelope).getCc();will(returnValue(cc));
-                oneOf(envelope).getDate();will(returnValue(date));
-                oneOf(envelope).getFrom();will(returnValue(from));
-                oneOf(envelope).getInReplyTo();will(returnValue(inReplyTo));
-                oneOf(envelope).getMessageId();will(returnValue(messageId));
-                oneOf(envelope).getReplyTo();will(returnValue(replyTo));
-                oneOf(envelope).getSender();will(returnValue(sender));
-                oneOf(envelope).getSubject();will(returnValue(subject));
-                oneOf(envelope).getTo();will(returnValue(to));
-                }
-            }
-        );
+        when(envelope.getBcc()).thenReturn(bcc);
+        when(envelope.getCc()).thenReturn(cc);
+        when(envelope.getDate()).thenReturn(date);
+        when(envelope.getFrom()).thenReturn(from);
+        when(envelope.getInReplyTo()).thenReturn(inReplyTo);
+        when(envelope.getMessageId()).thenReturn(messageId);
+        when(envelope.getReplyTo()).thenReturn(replyTo);
+        when(envelope.getSender()).thenReturn(sender);
+        when(envelope.getSubject()).thenReturn(subject);
+        when(envelope.getTo()).thenReturn(to);
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderNoExtensionsTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderNoExtensionsTest.java b/protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderNoExtensionsTest.java
index f129b03..b4b135c 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderNoExtensionsTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderNoExtensionsTest.java
@@ -22,6 +22,8 @@ package org.apache.james.imap.encode;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -35,41 +37,34 @@ import org.apache.james.imap.encode.base.ByteImapResponseWriter;
 import org.apache.james.imap.encode.base.ImapResponseComposerImpl;
 import org.apache.james.imap.message.response.FetchResponse;
 import org.apache.james.mailbox.MessageUid;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
-public class FetchResponseEncoderNoExtensionsTest  {
+public class FetchResponseEncoderNoExtensionsTest {
     private ByteImapResponseWriter writer = new ByteImapResponseWriter();
     private ImapResponseComposer composer = new ImapResponseComposerImpl(writer);
     private Flags flags;
 
     private FetchResponse.Structure stubStructure;
-
     private ImapEncoder mockNextEncoder;
-
     private FetchResponseEncoder encoder;
 
-    private Mockery context = new JUnit4Mockery();
-    
     @Before
     public void setUp() throws Exception {
-        mockNextEncoder = context.mock(ImapEncoder.class);
+        mockNextEncoder = mock(ImapEncoder.class);
         encoder = new FetchResponseEncoder(mockNextEncoder, true);
         flags = new Flags(Flags.Flag.DELETED);
-        stubStructure = context.mock(FetchResponse.Structure.class);
+        stubStructure = mock(FetchResponse.Structure.class);
     }
 
 
     @Test
-    public void testShouldNotAcceptUnknownResponse() throws Exception {
-        assertFalse(encoder.isAcceptable(context.mock(ImapMessage.class)));
+    public void testShouldNotAcceptUnknownResponse() {
+        assertFalse(encoder.isAcceptable(mock(ImapMessage.class)));
     }
 
     @Test
-    public void testShouldAcceptFetchResponse() throws Exception {
+    public void testShouldAcceptFetchResponse() {
         assertTrue(encoder.isAcceptable(new FetchResponse(11, null, null, null, null,
                 null, null, null, null, null)));
     }
@@ -99,7 +94,7 @@ public class FetchResponseEncoderNoExtensionsTest  {
         assertEquals("* 100 FETCH (FLAGS (\\Deleted) UID 72)\r\n",writer.getString());
 
     }
-    
+
     @Test
     public void testShouldNotAddExtensionsWithEncodingBodyStructure() throws Exception {
         FetchResponse message = new FetchResponse(100, flags, MessageUid.of(72), null,
@@ -109,20 +104,16 @@ public class FetchResponseEncoderNoExtensionsTest  {
         final List<String> parameterList = new ArrayList<>();
         parameterList.add("CHARSET");
         parameterList.add("US-ASCII");
-        
-        context.checking(new Expectations() {{
-                    final long octets = 2279L;
-                    final long lines = 48L;
-                    allowing(stubStructure).getMediaType(); will(returnValue("TEXT"));
-                    allowing(stubStructure).getSubType(); will(returnValue("HTML"));
-                    allowing(stubStructure).getOctets();will(returnValue(octets));
-                    allowing(stubStructure).getLines();will(returnValue(lines));
-                    allowing(stubStructure).getParameters(); will(returnValue(parameterList));
-                    allowing(stubStructure).getEncoding(); will(returnValue("7BIT"));
-                    ignoring(stubStructure);
-                }
-            }
-        );
+
+        when(stubStructure.getMediaType()).thenReturn("TEXT");
+        when(stubStructure.getSubType()).thenReturn("HTML");
+        when(stubStructure.getOctets()).thenReturn(2279L);
+        when(stubStructure.getLines()).thenReturn(48L);
+        when(stubStructure.getParameters()).thenReturn(parameterList);
+        when(stubStructure.getEncoding()).thenReturn("7BIT");
+        when(stubStructure.getId()).thenReturn("");
+        when(stubStructure.getDescription()).thenReturn("");
+
         final FakeImapSession fakeImapSession = new FakeImapSession();
         encoder.doEncode(message, composer, fakeImapSession);
         assertEquals("* 100 FETCH (FLAGS (\\Deleted) BODYSTRUCTURE (\"TEXT\" \"HTML\" (\"CHARSET\" \"US-ASCII\") \"\" \"\" \"7BIT\" 2279 48) UID 72)\r\n", writer.getString());

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderTest.java b/protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderTest.java
index 9f1470c..b5fb7d6 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/encode/FetchResponseEncoderTest.java
@@ -22,6 +22,7 @@ package org.apache.james.imap.encode;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
 
 import javax.mail.Flags;
 
@@ -30,8 +31,6 @@ import org.apache.james.imap.encode.base.ByteImapResponseWriter;
 import org.apache.james.imap.encode.base.ImapResponseComposerImpl;
 import org.apache.james.imap.message.response.FetchResponse;
 import org.apache.james.mailbox.MessageUid;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -45,22 +44,20 @@ public class FetchResponseEncoderTest  {
 
     private FetchResponseEncoder encoder;
 
-    private Mockery context = new JUnit4Mockery();
-
     @Before
     public void setUp() throws Exception {
-        mockNextEncoder = context.mock(ImapEncoder.class);
+        mockNextEncoder = mock(ImapEncoder.class);
         encoder = new FetchResponseEncoder(mockNextEncoder, false);
         flags = new Flags(Flags.Flag.DELETED);
     }
 
     @Test
-    public void testShouldNotAcceptUnknownResponse() throws Exception {
-        assertFalse(encoder.isAcceptable(context.mock(ImapMessage.class)));
+    public void testShouldNotAcceptUnknownResponse() {
+        assertFalse(encoder.isAcceptable(mock(ImapMessage.class)));
     }
 
     @Test
-    public void testShouldAcceptFetchResponse() throws Exception {
+    public void testShouldAcceptFetchResponse() {
         assertTrue(encoder.isAcceptable(new FetchResponse(11, null, null, null, null,
                 null, null, null, null, null)));
     }

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/encode/LSubResponseEncoderTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/encode/LSubResponseEncoderTest.java b/protocols/imap/src/test/java/org/apache/james/imap/encode/LSubResponseEncoderTest.java
index 91690bc..b1a15aa 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/encode/LSubResponseEncoderTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/encode/LSubResponseEncoderTest.java
@@ -20,6 +20,7 @@
 package org.apache.james.imap.encode;
 
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
 
 import org.apache.james.imap.api.ImapMessage;
 import org.apache.james.imap.encode.base.ByteImapResponseWriter;
@@ -27,8 +28,6 @@ import org.apache.james.imap.encode.base.ImapResponseComposerImpl;
 import org.apache.james.imap.message.response.LSubResponse;
 import org.apache.james.imap.message.response.ListResponse;
 import org.apache.james.mailbox.model.MailboxMetaData;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -38,11 +37,9 @@ public class LSubResponseEncoderTest  {
     private ByteImapResponseWriter writer = new ByteImapResponseWriter();
     private ImapResponseComposer composer = new ImapResponseComposerImpl(writer);
 
-    private Mockery context = new JUnit4Mockery();
-
     @Before
     public void setUp() throws Exception {
-        encoder = new LSubResponseEncoder(context.mock(ImapEncoder.class));
+        encoder = new LSubResponseEncoder(mock(ImapEncoder.class));
     }
 
     @Test
@@ -58,7 +55,7 @@ public class LSubResponseEncoderTest  {
 
     @Test
     public void encoderShouldNotAcceptImapMessage() {
-        assertThat(encoder.isAcceptable(context.mock(ImapMessage.class))).isFalse();
+        assertThat(encoder.isAcceptable(mock(ImapMessage.class))).isFalse();
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/encode/ListResponseEncoderTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/encode/ListResponseEncoderTest.java b/protocols/imap/src/test/java/org/apache/james/imap/encode/ListResponseEncoderTest.java
index 5ab80be..50a8fea 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/encode/ListResponseEncoderTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/encode/ListResponseEncoderTest.java
@@ -21,6 +21,7 @@ package org.apache.james.imap.encode;
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.Assert.assertFalse;
+import static org.mockito.Mockito.mock;
 
 import org.apache.james.imap.api.ImapMessage;
 import org.apache.james.imap.encode.base.ByteImapResponseWriter;
@@ -28,8 +29,6 @@ import org.apache.james.imap.encode.base.ImapResponseComposerImpl;
 import org.apache.james.imap.message.response.LSubResponse;
 import org.apache.james.imap.message.response.ListResponse;
 import org.apache.james.mailbox.model.MailboxMetaData;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -40,11 +39,9 @@ public class ListResponseEncoderTest {
     private ByteImapResponseWriter writer = new ByteImapResponseWriter();
     private ImapResponseComposer composer = new ImapResponseComposerImpl(writer);
 
-    private Mockery context = new JUnit4Mockery();
-    
     @Before
     public void setUp() throws Exception {
-        encoder = new ListResponseEncoder(context.mock(ImapEncoder.class));
+        encoder = new ListResponseEncoder(mock(ImapEncoder.class));
     }
 
     @Test
@@ -56,13 +53,13 @@ public class ListResponseEncoderTest {
     @Test
     public void encoderShouldNotAcceptLsubResponse() {
         assertThat(encoder.isAcceptable(new LSubResponse("name", true, '.'))).isFalse();
-        assertFalse(encoder.isAcceptable(context.mock(ImapMessage.class)));
+        assertFalse(encoder.isAcceptable(mock(ImapMessage.class)));
         assertFalse(encoder.isAcceptable(null));
     }
 
     @Test
     public void encoderShouldNotAcceptImapMessage() {
-        assertThat(encoder.isAcceptable(context.mock(ImapMessage.class))).isFalse();
+        assertThat(encoder.isAcceptable(mock(ImapMessage.class))).isFalse();
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/encode/MailboxStatusResponseEncoderTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/encode/MailboxStatusResponseEncoderTest.java b/protocols/imap/src/test/java/org/apache/james/imap/encode/MailboxStatusResponseEncoderTest.java
index bf57192..0ad5f2b 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/encode/MailboxStatusResponseEncoderTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/encode/MailboxStatusResponseEncoderTest.java
@@ -22,14 +22,13 @@ package org.apache.james.imap.encode;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
 
 import org.apache.james.imap.api.ImapMessage;
 import org.apache.james.imap.encode.base.ByteImapResponseWriter;
 import org.apache.james.imap.encode.base.ImapResponseComposerImpl;
 import org.apache.james.imap.message.response.MailboxStatusResponse;
 import org.apache.james.mailbox.MessageUid;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -41,21 +40,18 @@ public class MailboxStatusResponseEncoderTest  {
 
     ByteImapResponseWriter writer = new ByteImapResponseWriter();
     ImapResponseComposer composer = new ImapResponseComposerImpl(writer);
-    
-    private Mockery context = new JUnit4Mockery();
-    
+
     @Before
     public void setUp() throws Exception {
-        mockNextEncoder = context.mock(ImapEncoder.class);
+        mockNextEncoder = mock(ImapEncoder.class);
         encoder = new MailboxStatusResponseEncoder(mockNextEncoder);
     }
-    
 
     @Test
-    public void testIsAcceptable() throws Exception {
+    public void testIsAcceptable() {
         assertTrue(encoder.isAcceptable(new MailboxStatusResponse(null, null, null,
                 null, null, null, "mailbox")));
-        assertFalse(encoder.isAcceptable(context.mock(ImapMessage.class)));
+        assertFalse(encoder.isAcceptable(mock(ImapMessage.class)));
         assertFalse(encoder.isAcceptable(null));
     }
 

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/encode/NamespaceResponseEncoderTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/encode/NamespaceResponseEncoderTest.java b/protocols/imap/src/test/java/org/apache/james/imap/encode/NamespaceResponseEncoderTest.java
index 9ac81af..0fceca4 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/encode/NamespaceResponseEncoderTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/encode/NamespaceResponseEncoderTest.java
@@ -20,6 +20,8 @@ package org.apache.james.imap.encode;
 
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -28,12 +30,10 @@ import org.apache.james.imap.api.ImapConstants;
 import org.apache.james.imap.api.ImapMessage;
 import org.apache.james.imap.api.process.ImapSession;
 import org.apache.james.imap.message.response.NamespaceResponse;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.Sequence;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
+import org.mockito.InOrder;
+import org.mockito.Mockito;
 
 public class NamespaceResponseEncoderTest {
 
@@ -43,14 +43,12 @@ public class NamespaceResponseEncoderTest {
 
     NamespaceResponseEncoder subject;
 
-    private Mockery context = new JUnit4Mockery();
-    
     @Before
     public void setUp() throws Exception {
-        dummySession = context.mock(ImapSession.class);
-        final ImapEncoder stubNextEncoderInChain = context.mock(ImapEncoder.class);
+        dummySession = mock(ImapSession.class);
+        final ImapEncoder stubNextEncoderInChain = mock(ImapEncoder.class);
         subject = new NamespaceResponseEncoder(stubNextEncoderInChain);
-        mockComposer = context.mock(ImapResponseComposer.class);
+        mockComposer = mock(ImapResponseComposer.class);
     }
 
     @Test
@@ -58,27 +56,22 @@ public class NamespaceResponseEncoderTest {
             throws Exception {
         final String aPrefix = "A Prefix";
         final String aDeliminator = "@";
-        context.checking(new Expectations() {
-            {
-                final Sequence sequence = context.sequence("Composition order");
-                oneOf(mockComposer).untagged(); inSequence(sequence);
-                oneOf(mockComposer).commandName(ImapConstants.NAMESPACE_COMMAND_NAME);
-                oneOf(mockComposer).nil(); inSequence(sequence);
-                oneOf(mockComposer).nil(); inSequence(sequence);
-                oneOf(mockComposer).openParen();  inSequence(sequence);
-                oneOf(mockComposer).openParen(); inSequence(sequence);
-                oneOf(mockComposer).quote(aPrefix + aDeliminator); inSequence(sequence);
-                oneOf(mockComposer).quote(aDeliminator); inSequence(sequence);
-                oneOf(mockComposer).closeParen(); inSequence(sequence);
-                oneOf(mockComposer).closeParen(); inSequence(sequence);
-                oneOf(mockComposer).end(); inSequence(sequence);
-            }
-        });
+
         List<NamespaceResponse.Namespace> namespaces = new ArrayList<>();
         namespaces.add(new NamespaceResponse.Namespace(aPrefix, aDeliminator
                 .charAt(0)));
         subject.doEncode(new NamespaceResponse(null, null, namespaces),
                 mockComposer, dummySession);
+
+        InOrder inOrder = Mockito.inOrder(mockComposer);
+        inOrder.verify(mockComposer, times(1)).untagged();
+        inOrder.verify(mockComposer, times(1)).commandName(ImapConstants.NAMESPACE_COMMAND_NAME);
+        inOrder.verify(mockComposer, times(2)).nil();
+        inOrder.verify(mockComposer, times(2)).openParen();
+        inOrder.verify(mockComposer, times(1)).quote(aPrefix + aDeliminator);
+        inOrder.verify(mockComposer, times(1)).quote(aDeliminator);
+        inOrder.verify(mockComposer, times(2)).closeParen();
+        inOrder.verify(mockComposer, times(1)).end();
     }
 
     @Test
@@ -86,27 +79,23 @@ public class NamespaceResponseEncoderTest {
             throws Exception {
         final String aPrefix = "A Prefix";
         final String aDeliminator = "@";
-        context.checking(new Expectations() {
-            {
-                final Sequence sequence = context.sequence("Composition order");
-                oneOf(mockComposer).untagged(); inSequence(sequence);
-                oneOf(mockComposer).commandName(ImapConstants.NAMESPACE_COMMAND_NAME);
-                oneOf(mockComposer).nil(); inSequence(sequence);
-                oneOf(mockComposer).openParen(); inSequence(sequence);
-                oneOf(mockComposer).openParen(); inSequence(sequence);
-                oneOf(mockComposer).quote(aPrefix + aDeliminator); inSequence(sequence);
-                oneOf(mockComposer).quote(aDeliminator); inSequence(sequence);
-                oneOf(mockComposer).closeParen(); inSequence(sequence);
-                oneOf(mockComposer).closeParen(); inSequence(sequence);
-                oneOf(mockComposer).nil(); inSequence(sequence);
-                oneOf(mockComposer).end(); inSequence(sequence);
-            }
-        });
+
         List<NamespaceResponse.Namespace> namespaces = new ArrayList<>();
         namespaces.add(new NamespaceResponse.Namespace(aPrefix, aDeliminator
                 .charAt(0)));
         subject.doEncode(new NamespaceResponse(null, namespaces, null),
                 mockComposer, dummySession);
+
+        InOrder inOrder = Mockito.inOrder(mockComposer);
+        inOrder.verify(mockComposer, times(1)).untagged();
+        inOrder.verify(mockComposer, times(1)).commandName(ImapConstants.NAMESPACE_COMMAND_NAME);
+        inOrder.verify(mockComposer, times(1)).nil();
+        inOrder.verify(mockComposer, times(2)).openParen();
+        inOrder.verify(mockComposer, times(1)).quote(aPrefix + aDeliminator);
+        inOrder.verify(mockComposer, times(1)).quote(aDeliminator);
+        inOrder.verify(mockComposer, times(2)).closeParen();
+        inOrder.verify(mockComposer, times(1)).nil();
+        inOrder.verify(mockComposer, times(1)).end();
     }
 
     @Test
@@ -114,27 +103,22 @@ public class NamespaceResponseEncoderTest {
             throws Exception {
         final String aPrefix = "A Prefix";
         final String aDeliminator = "@";
-        context.checking(new Expectations() {
-            {
-                final Sequence sequence = context.sequence("Composition order");
-                oneOf(mockComposer).untagged(); inSequence(sequence);
-                oneOf(mockComposer).commandName(ImapConstants.NAMESPACE_COMMAND_NAME);
-                oneOf(mockComposer).openParen(); inSequence(sequence);
-                oneOf(mockComposer).openParen(); inSequence(sequence);
-                oneOf(mockComposer).quote(aPrefix + aDeliminator); inSequence(sequence);
-                oneOf(mockComposer).quote(aDeliminator); inSequence(sequence);
-                oneOf(mockComposer).closeParen(); inSequence(sequence);
-                oneOf(mockComposer).closeParen(); inSequence(sequence);
-                oneOf(mockComposer).nil(); inSequence(sequence);
-                oneOf(mockComposer).nil(); inSequence(sequence);
-                oneOf(mockComposer).end(); inSequence(sequence);
-            }
-        });
+
         List<NamespaceResponse.Namespace> namespaces = new ArrayList<>();
         namespaces.add(new NamespaceResponse.Namespace(aPrefix, aDeliminator
                 .charAt(0)));
         subject.doEncode(new NamespaceResponse(namespaces, null, null),
                 mockComposer, dummySession);
+
+        InOrder inOrder = Mockito.inOrder(mockComposer);
+        inOrder.verify(mockComposer, times(1)).untagged();
+        inOrder.verify(mockComposer, times(1)).commandName(ImapConstants.NAMESPACE_COMMAND_NAME);
+        inOrder.verify(mockComposer, times(2)).openParen();
+        inOrder.verify(mockComposer, times(1)).quote(aPrefix + aDeliminator);
+        inOrder.verify(mockComposer, times(1)).quote(aDeliminator);
+        inOrder.verify(mockComposer, times(2)).closeParen();
+        inOrder.verify(mockComposer, times(2)).nil();
+        inOrder.verify(mockComposer, times(1)).end();
     }
 
     @Test
@@ -144,26 +128,7 @@ public class NamespaceResponseEncoderTest {
         final String aDeliminator = "@";
         final String anotherPrefix = "Another Prefix";
         final String anotherDeliminator = "^";
-        context.checking(new Expectations() {
-            {
-                final Sequence sequence = context.sequence("Composition order");
-                oneOf(mockComposer).untagged(); inSequence(sequence);
-                oneOf(mockComposer).commandName(ImapConstants.NAMESPACE_COMMAND_NAME);
-                oneOf(mockComposer).openParen(); inSequence(sequence);
-                oneOf(mockComposer).openParen(); inSequence(sequence);
-                oneOf(mockComposer).quote(aPrefix + aDeliminator); inSequence(sequence);
-                oneOf(mockComposer).quote(aDeliminator); inSequence(sequence);
-                oneOf(mockComposer).closeParen(); inSequence(sequence);
-                oneOf(mockComposer).openParen(); inSequence(sequence);
-                oneOf(mockComposer).quote(anotherPrefix + anotherDeliminator); inSequence(sequence);
-                oneOf(mockComposer).quote(anotherDeliminator); inSequence(sequence);
-                oneOf(mockComposer).closeParen(); inSequence(sequence);
-                oneOf(mockComposer).closeParen(); inSequence(sequence);
-                oneOf(mockComposer).nil(); inSequence(sequence);
-                oneOf(mockComposer).nil(); inSequence(sequence);
-                oneOf(mockComposer).end(); inSequence(sequence);
-            }
-        });
+
         List<NamespaceResponse.Namespace> namespaces = new ArrayList<>();
         namespaces.add(new NamespaceResponse.Namespace(aPrefix, aDeliminator
                 .charAt(0)));
@@ -171,28 +136,38 @@ public class NamespaceResponseEncoderTest {
                 anotherDeliminator.charAt(0)));
         subject.doEncode(new NamespaceResponse(namespaces, null, null),
                 mockComposer, dummySession);
+
+        InOrder inOrder = Mockito.inOrder(mockComposer);
+        inOrder.verify(mockComposer, times(1)).untagged();
+        inOrder.verify(mockComposer, times(1)).commandName(ImapConstants.NAMESPACE_COMMAND_NAME);
+        inOrder.verify(mockComposer, times(2)).openParen();
+        inOrder.verify(mockComposer, times(1)).quote(aPrefix + aDeliminator);
+        inOrder.verify(mockComposer, times(1)).quote(aDeliminator);
+        inOrder.verify(mockComposer, times(1)).closeParen();
+        inOrder.verify(mockComposer, times(1)).openParen();
+        inOrder.verify(mockComposer, times(1)).quote(anotherPrefix + anotherDeliminator);
+        inOrder.verify(mockComposer, times(1)).quote(anotherDeliminator);
+        inOrder.verify(mockComposer, times(2)).closeParen();
+        inOrder.verify(mockComposer, times(2)).nil();
+        inOrder.verify(mockComposer, times(1)).end();
     }
 
     @Test
     public void testAllNullShouldWriteAllNIL() throws Exception {
-        context.checking(new Expectations() {
-            {
-                final Sequence sequence = context.sequence("Composition order");
-                oneOf(mockComposer).untagged(); inSequence(sequence);
-                oneOf(mockComposer).commandName(ImapConstants.NAMESPACE_COMMAND_NAME);
-                oneOf(mockComposer).nil(); inSequence(sequence);
-                oneOf(mockComposer).nil(); inSequence(sequence);
-                oneOf(mockComposer).nil(); inSequence(sequence);
-                oneOf(mockComposer).end(); inSequence(sequence);
-            }
-        });
+
         subject.doEncode(new NamespaceResponse(null, null, null), mockComposer,
                 dummySession);
+
+        InOrder inOrder = Mockito.inOrder(mockComposer);
+        inOrder.verify(mockComposer, times(1)).untagged();
+        inOrder.verify(mockComposer, times(1)).commandName(ImapConstants.NAMESPACE_COMMAND_NAME);
+        inOrder.verify(mockComposer, times(3)).nil();
+        inOrder.verify(mockComposer, times(1)).end();
     }
 
     @Test
-    public void testNamespaceResponseIsAcceptable() throws Exception {
-        assertFalse(subject.isAcceptable(context.mock(ImapMessage.class)));
+    public void testNamespaceResponseIsAcceptable() {
+        assertFalse(subject.isAcceptable(mock(ImapMessage.class)));
         assertTrue(subject
                 .isAcceptable(new NamespaceResponse(null, null, null)));
     }

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/encode/SearchResponseEncoderTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/encode/SearchResponseEncoderTest.java b/protocols/imap/src/test/java/org/apache/james/imap/encode/SearchResponseEncoderTest.java
index 4f4d18c..72b13f8 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/encode/SearchResponseEncoderTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/encode/SearchResponseEncoderTest.java
@@ -22,14 +22,13 @@ package org.apache.james.imap.encode;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
 
 import org.apache.james.imap.api.ImapMessage;
 import org.apache.james.imap.encode.base.ByteImapResponseWriter;
 import org.apache.james.imap.encode.base.ImapResponseComposerImpl;
 import org.apache.james.imap.message.response.LSubResponse;
 import org.apache.james.imap.message.response.SearchResponse;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -46,11 +45,9 @@ public class SearchResponseEncoderTest {
     private ByteImapResponseWriter writer = new ByteImapResponseWriter();
     private ImapResponseComposer composer = new ImapResponseComposerImpl(writer);
 
-    private Mockery context = new JUnit4Mockery();
-    
     @Before
     public void setUp() throws Exception {
-        mockNextEncoder = context.mock(ImapEncoder.class);
+        mockNextEncoder = mock(ImapEncoder.class);
         response = new SearchResponse(IDS, null);
         encoder = new SearchResponseEncoder(mockNextEncoder);
     }
@@ -59,7 +56,7 @@ public class SearchResponseEncoderTest {
     public void testIsAcceptable() {
         assertTrue(encoder.isAcceptable(response));
         assertFalse(encoder.isAcceptable(new LSubResponse("name", true, '.')));
-        assertFalse(encoder.isAcceptable(context.mock(ImapMessage.class)));
+        assertFalse(encoder.isAcceptable(mock(ImapMessage.class)));
         assertFalse(encoder.isAcceptable(null));
     }
 

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/encode/XListResponseEncoderTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/encode/XListResponseEncoderTest.java b/protocols/imap/src/test/java/org/apache/james/imap/encode/XListResponseEncoderTest.java
index 04181bf..a3e212f 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/encode/XListResponseEncoderTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/encode/XListResponseEncoderTest.java
@@ -21,6 +21,7 @@ package org.apache.james.imap.encode;
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.Assert.assertFalse;
+import static org.mockito.Mockito.mock;
 
 import org.apache.james.imap.api.ImapMessage;
 import org.apache.james.imap.api.process.MailboxType;
@@ -29,8 +30,6 @@ import org.apache.james.imap.encode.base.ImapResponseComposerImpl;
 import org.apache.james.imap.message.response.LSubResponse;
 import org.apache.james.imap.message.response.XListResponse;
 import org.apache.james.mailbox.model.MailboxMetaData;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -41,11 +40,9 @@ public class XListResponseEncoderTest {
     private ByteImapResponseWriter writer = new ByteImapResponseWriter();
     private ImapResponseComposer composer = new ImapResponseComposerImpl(writer);
 
-    private Mockery context = new JUnit4Mockery();
-    
     @Before
     public void setUp() throws Exception {
-        encoder = new XListResponseEncoder(context.mock(ImapEncoder.class));
+        encoder = new XListResponseEncoder(mock(ImapEncoder.class));
     }
 
     @Test
@@ -63,13 +60,13 @@ public class XListResponseEncoderTest {
     @Test
     public void encoderShouldNotAcceptLsubResponse() {
         assertThat(encoder.isAcceptable(new LSubResponse("name", true, '.'))).isFalse();
-        assertFalse(encoder.isAcceptable(context.mock(ImapMessage.class)));
+        assertFalse(encoder.isAcceptable(mock(ImapMessage.class)));
         assertFalse(encoder.isAcceptable(null));
     }
 
     @Test
     public void encoderShouldNotAcceptImapMessage() {
-        assertThat(encoder.isAcceptable(context.mock(ImapMessage.class))).isFalse();
+        assertThat(encoder.isAcceptable(mock(ImapMessage.class))).isFalse();
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/main/ImapRequestHandlerAdandonConnectionTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/main/ImapRequestHandlerAdandonConnectionTest.java b/protocols/imap/src/test/java/org/apache/james/imap/main/ImapRequestHandlerAdandonConnectionTest.java
index 0b3cb7a..dcd2818 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/main/ImapRequestHandlerAdandonConnectionTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/main/ImapRequestHandlerAdandonConnectionTest.java
@@ -19,6 +19,7 @@
 package org.apache.james.imap.main;
 
 import static org.junit.Assert.assertFalse;
+import static org.mockito.Mockito.mock;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
@@ -28,9 +29,6 @@ import org.apache.james.imap.api.process.ImapSession;
 import org.apache.james.imap.decode.ImapDecoder;
 import org.apache.james.imap.decode.main.ImapRequestStreamHandler;
 import org.apache.james.imap.encode.ImapEncoder;
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.integration.junit4.JUnit4Mockery;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -47,45 +45,27 @@ public class ImapRequestHandlerAdandonConnectionTest {
     ImapDecoder decoderStub;
     ImapProcessor processorStub;
     ImapEncoder encoderStub;
-    ImapSession sessionStub;    
-
-    private Mockery mockery = new JUnit4Mockery();
-    
+    ImapSession sessionStub;
     
     @Before
     public void setUp() throws Exception {
         // Fakes
         fakeOutput = new ByteArrayOutputStream();
         // Stubs
-        decoderStub = mockery.mock(ImapDecoder.class);
-        processorStub = mockery.mock(ImapProcessor.class);
-        encoderStub = mockery.mock(ImapEncoder.class);
-        sessionStub = mockery.mock(ImapSession.class);
+        decoderStub = mock(ImapDecoder.class);
+        processorStub = mock(ImapProcessor.class);
+        encoderStub = mock(ImapEncoder.class);
+        sessionStub = mock(ImapSession.class);
         // System under test
         subject = new ImapRequestStreamHandler(decoderStub, processorStub, encoderStub);
     }
     
     @Test
-    public void testWhenConsumeLineFailsShouldAbandonConnection() throws Exception {        
-        //
-        // Setup
-        //
-        
-        // Setup stubs
-        mockery.checking(new Expectations() {{
-                    ignoring(decoderStub);
-                    ignoring(processorStub);
-                    ignoring(encoderStub);
-                    ignoring(sessionStub);
-                }
-            }
-        );
-        
+    public void testWhenConsumeLineFailsShouldAbandonConnection() {
         // Create input stream that will throw IOException after first read
         byte[] endOfStreamAfterOneCharacter = {'0'};
         ByteArrayInputStream fakeInput = new ByteArrayInputStream(endOfStreamAfterOneCharacter);
         
-        
         // 
         // Exercise
         //

http://git-wip-us.apache.org/repos/asf/james-project/blob/6373f39a/protocols/imap/src/test/java/org/apache/james/imap/processor/CopyProcessorTest.java
----------------------------------------------------------------------
diff --git a/protocols/imap/src/test/java/org/apache/james/imap/processor/CopyProcessorTest.java b/protocols/imap/src/test/java/org/apache/james/imap/processor/CopyProcessorTest.java
index 76323ba..db5e8c4 100644
--- a/protocols/imap/src/test/java/org/apache/james/imap/processor/CopyProcessorTest.java
+++ b/protocols/imap/src/test/java/org/apache/james/imap/processor/CopyProcessorTest.java
@@ -216,7 +216,7 @@ public class CopyProcessorTest {
     }
 
     @Test
-    public void processShouldNotHandleMoveRequests() throws Exception {
+    public void processShouldNotHandleMoveRequests() {
         MoveRequest moveRequest = new MoveRequest(ImapCommand.anyStateCommand("Name"), new IdRange[] {new IdRange(4, 6)}, ImapConstants.INBOX_NAME, true, TAG);
 
         testee.process(moveRequest, mockResponder, mockImapSession);


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


[20/20] james-project git commit: JAMES-2513 Memory Domain List configuration should rely on POJO

Posted by bt...@apache.org.
JAMES-2513 Memory Domain List configuration should rely on POJO


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

Branch: refs/heads/master
Commit: f101b0dae18bd911ca513b327a97fdfb522b7a9e
Parents: 8d33e65
Author: benwa <bt...@linagora.com>
Authored: Thu Aug 2 14:07:21 2018 +0700
Committer: Benoit Tellier <bt...@linagora.com>
Committed: Fri Aug 3 15:51:30 2018 +0700

----------------------------------------------------------------------
 .../james/modules/data/MemoryDataModule.java      | 18 ++++++++++++++++--
 1 file changed, 16 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/f101b0da/server/container/guice/memory-guice/src/main/java/org/apache/james/modules/data/MemoryDataModule.java
----------------------------------------------------------------------
diff --git a/server/container/guice/memory-guice/src/main/java/org/apache/james/modules/data/MemoryDataModule.java b/server/container/guice/memory-guice/src/main/java/org/apache/james/modules/data/MemoryDataModule.java
index 44e7496..573c504 100644
--- a/server/container/guice/memory-guice/src/main/java/org/apache/james/modules/data/MemoryDataModule.java
+++ b/server/container/guice/memory-guice/src/main/java/org/apache/james/modules/data/MemoryDataModule.java
@@ -25,6 +25,7 @@ import org.apache.commons.configuration.ConfigurationException;
 import org.apache.james.dlp.api.DLPConfigurationStore;
 import org.apache.james.dlp.eventsourcing.EventSourcingDLPConfigurationStore;
 import org.apache.james.domainlist.api.DomainList;
+import org.apache.james.domainlist.lib.DomainListConfiguration;
 import org.apache.james.domainlist.memory.MemoryDomainList;
 import org.apache.james.lifecycle.api.Configurable;
 import org.apache.james.mailrepository.api.MailRepositoryUrlStore;
@@ -39,6 +40,7 @@ import org.apache.james.utils.ConfigurationPerformer;
 import com.google.common.collect.ImmutableList;
 import com.google.inject.AbstractModule;
 import com.google.inject.Inject;
+import com.google.inject.Provides;
 import com.google.inject.Scopes;
 import com.google.inject.Singleton;
 import com.google.inject.multibindings.Multibinder;
@@ -70,16 +72,28 @@ public class MemoryDataModule extends AbstractModule {
         Multibinder.newSetBinder(binder(), ConfigurationPerformer.class).addBinding().to(MemoryDataConfigurationPerformer.class);
     }
 
+    @Provides
+    @Singleton
+    public DomainListConfiguration provideDomainListConfiguration(ConfigurationProvider configurationProvider) {
+        try {
+            return DomainListConfiguration.from(configurationProvider.getConfiguration("domainlist"));
+        } catch (ConfigurationException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
     @Singleton
     public static class MemoryDataConfigurationPerformer implements ConfigurationPerformer {
 
         private final ConfigurationProvider configurationProvider;
+        private final DomainListConfiguration domainListConfiguration;
         private final MemoryDomainList memoryDomainList;
         private final MemoryRecipientRewriteTable memoryRecipientRewriteTable;
 
         @Inject
-        public MemoryDataConfigurationPerformer(ConfigurationProvider configurationProvider, MemoryDomainList memoryDomainList, MemoryRecipientRewriteTable memoryRecipientRewriteTable) {
+        public MemoryDataConfigurationPerformer(ConfigurationProvider configurationProvider, DomainListConfiguration domainListConfiguration, MemoryDomainList memoryDomainList, MemoryRecipientRewriteTable memoryRecipientRewriteTable) {
             this.configurationProvider = configurationProvider;
+            this.domainListConfiguration = domainListConfiguration;
             this.memoryDomainList = memoryDomainList;
             this.memoryRecipientRewriteTable = memoryRecipientRewriteTable;
         }
@@ -87,7 +101,7 @@ public class MemoryDataModule extends AbstractModule {
         @Override
         public void initModule() {
             try {
-                memoryDomainList.configure(configurationProvider.getConfiguration("domainlist"));
+                memoryDomainList.configure(domainListConfiguration);
                 memoryRecipientRewriteTable.configure(configurationProvider.getConfiguration("recipientrewritetable"));
             } catch (ConfigurationException e) {
                 throw new RuntimeException(e);


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


[08/20] james-project git commit: JAMES-2517 Use try-with-resource in more places

Posted by bt...@apache.org.
http://git-wip-us.apache.org/repos/asf/james-project/blob/3c275fe6/mailbox/lucene/src/main/java/org/apache/james/mailbox/lucene/search/LuceneMessageSearchIndex.java
----------------------------------------------------------------------
diff --git a/mailbox/lucene/src/main/java/org/apache/james/mailbox/lucene/search/LuceneMessageSearchIndex.java b/mailbox/lucene/src/main/java/org/apache/james/mailbox/lucene/search/LuceneMessageSearchIndex.java
index 887b05a..13a402d 100644
--- a/mailbox/lucene/src/main/java/org/apache/james/mailbox/lucene/search/LuceneMessageSearchIndex.java
+++ b/mailbox/lucene/src/main/java/org/apache/james/mailbox/lucene/search/LuceneMessageSearchIndex.java
@@ -1,1383 +1,1351 @@
-/****************************************************************
- * 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.mailbox.lucene.search;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.StringReader;
-import java.nio.charset.Charset;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Collection;
-import java.util.Date;
-import java.util.EnumSet;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Optional;
-import java.util.Set;
-import java.util.TimeZone;
-
-import javax.inject.Inject;
-import javax.mail.Flags;
-import javax.mail.Flags.Flag;
-
-import org.apache.james.mailbox.MailboxManager;
-import org.apache.james.mailbox.MailboxManager.SearchCapabilities;
-import org.apache.james.mailbox.MailboxSession;
-import org.apache.james.mailbox.MessageUid;
-import org.apache.james.mailbox.exception.MailboxException;
-import org.apache.james.mailbox.exception.UnsupportedSearchException;
-import org.apache.james.mailbox.model.MailboxId;
-import org.apache.james.mailbox.model.MessageId;
-import org.apache.james.mailbox.model.MessageRange;
-import org.apache.james.mailbox.model.SearchQuery;
-import org.apache.james.mailbox.model.SearchQuery.AllCriterion;
-import org.apache.james.mailbox.model.SearchQuery.AttachmentCriterion;
-import org.apache.james.mailbox.model.SearchQuery.ContainsOperator;
-import org.apache.james.mailbox.model.SearchQuery.Criterion;
-import org.apache.james.mailbox.model.SearchQuery.CustomFlagCriterion;
-import org.apache.james.mailbox.model.SearchQuery.DateOperator;
-import org.apache.james.mailbox.model.SearchQuery.DateResolution;
-import org.apache.james.mailbox.model.SearchQuery.FlagCriterion;
-import org.apache.james.mailbox.model.SearchQuery.HeaderCriterion;
-import org.apache.james.mailbox.model.SearchQuery.HeaderOperator;
-import org.apache.james.mailbox.model.SearchQuery.NumericOperator;
-import org.apache.james.mailbox.model.SearchQuery.UidCriterion;
-import org.apache.james.mailbox.model.SearchQuery.UidRange;
-import org.apache.james.mailbox.model.UpdatedFlags;
-import org.apache.james.mailbox.store.mail.MessageMapperFactory;
-import org.apache.james.mailbox.store.mail.model.Mailbox;
-import org.apache.james.mailbox.store.mail.model.MailboxMessage;
-import org.apache.james.mailbox.store.mail.model.impl.PropertyBuilder;
-import org.apache.james.mailbox.store.search.ListeningMessageSearchIndex;
-import org.apache.james.mailbox.store.search.SearchUtil;
-import org.apache.james.mime4j.MimeException;
-import org.apache.james.mime4j.dom.Header;
-import org.apache.james.mime4j.dom.address.Address;
-import org.apache.james.mime4j.dom.address.AddressList;
-import org.apache.james.mime4j.dom.address.Group;
-import org.apache.james.mime4j.dom.address.MailboxList;
-import org.apache.james.mime4j.dom.datetime.DateTime;
-import org.apache.james.mime4j.dom.field.DateTimeField;
-import org.apache.james.mime4j.field.address.AddressFormatter;
-import org.apache.james.mime4j.field.address.LenientAddressParser;
-import org.apache.james.mime4j.field.datetime.parser.DateTimeParser;
-import org.apache.james.mime4j.message.SimpleContentHandler;
-import org.apache.james.mime4j.parser.MimeStreamParser;
-import org.apache.james.mime4j.stream.BodyDescriptor;
-import org.apache.james.mime4j.stream.MimeConfig;
-import org.apache.james.mime4j.util.MimeUtil;
-import org.apache.lucene.analysis.Analyzer;
-import org.apache.lucene.document.DateTools;
-import org.apache.lucene.document.Document;
-import org.apache.lucene.document.Field;
-import org.apache.lucene.document.Field.Index;
-import org.apache.lucene.document.Field.Store;
-import org.apache.lucene.document.NumericField;
-import org.apache.lucene.index.IndexReader;
-import org.apache.lucene.index.IndexWriter;
-import org.apache.lucene.index.IndexWriterConfig;
-import org.apache.lucene.index.IndexWriterConfig.OpenMode;
-import org.apache.lucene.index.Term;
-import org.apache.lucene.search.BooleanClause;
-import org.apache.lucene.search.BooleanQuery;
-import org.apache.lucene.search.IndexSearcher;
-import org.apache.lucene.search.NumericRangeQuery;
-import org.apache.lucene.search.PrefixQuery;
-import org.apache.lucene.search.Query;
-import org.apache.lucene.search.ScoreDoc;
-import org.apache.lucene.search.Sort;
-import org.apache.lucene.search.SortField;
-import org.apache.lucene.search.TermQuery;
-import org.apache.lucene.search.TermRangeQuery;
-import org.apache.lucene.search.TopDocs;
-import org.apache.lucene.search.WildcardQuery;
-import org.apache.lucene.store.Directory;
-import org.apache.lucene.util.IOUtils;
-import org.apache.lucene.util.Version;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.github.steveash.guavate.Guavate;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableList;
-
-/**
- * Lucene based {@link ListeningMessageSearchIndex} which offers message searching via a Lucene index
- * 
- * 
-
- * @param 
- */
-public class LuceneMessageSearchIndex extends ListeningMessageSearchIndex {
-    private static final Logger LOGGER = LoggerFactory.getLogger(LuceneMessageSearchIndex.class);
-    private static final Date MAX_DATE;
-    private static final Date MIN_DATE;
-    
-    static {
-        Calendar cal = Calendar.getInstance();
-        cal.set(9999, 11, 31);
-        MAX_DATE = cal.getTime();
-        
-        cal.set(0000, 0, 1);
-        MIN_DATE = cal.getTime();
-    }
-    
-    /**
-     * Default max query results
-     */
-    private static final int DEFAULT_MAX_QUERY_RESULTS = 100000;
-    
-    /**
-     * {@link Field} which will contain the unique index of the {@link Document}
-     */
-    private static final String ID_FIELD = "id";
-    
-    
-    /**
-     * {@link Field} which will contain uid of the {@link MailboxMessage}
-     */
-    private static final String UID_FIELD = "uid";
-    
-    /**
-     * {@link Field} boolean field that say if the message as an attachment or not
-     */
-    private static final String HAS_ATTACHMENT_FIELD = "hasAttachment";
-
-    /**
-     * {@link Field} which will contain the {@link Flags} of the {@link MailboxMessage}
-     */
-    private static final String FLAGS_FIELD = "flags";
-  
-    /**
-     * {@link Field} which will contain the size of the {@link MailboxMessage}
-     */
-    private static final String SIZE_FIELD = "size";
-
-    /**
-     * {@link Field} which will contain the body of the {@link MailboxMessage}
-     */
-    private static final String BODY_FIELD = "body";
-    
-    
-    /**
-     * Prefix which will be used for each message header to store it also in a seperate {@link Field}
-     */
-    private static final String PREFIX_HEADER_FIELD = "header_";
-    
-    /**
-     * {@link Field} which will contain the whole message header of the {@link MailboxMessage}
-     */
-    private static final String HEADERS_FIELD = "headers";
-
-    /**
-     * {@link Field} which will contain the mod-sequence of the message
-     */
-    private static final String MODSEQ_FIELD = "modSeq";
-
-    /**
-     * {@link Field} which will contain the TO-Address of the message
-     */
-    private static final String TO_FIELD = "to";
-    
-    private static final String FIRST_TO_MAILBOX_NAME_FIELD = "firstToMailboxName";
-    private static final String FIRST_TO_MAILBOX_DISPLAY_FIELD = "firstToMailboxDisplay";
-
-    /**
-     * {@link Field} which will contain the CC-Address of the message
-     */
-    private static final String CC_FIELD = "cc";
-
-    private static final String FIRST_CC_MAILBOX_NAME_FIELD = "firstCcMailboxName";
-    
-
-    /**
-     * {@link Field} which will contain the FROM-Address of the message
-     */
-    private static final String FROM_FIELD = "from";
-    
-    private static final String FIRST_FROM_MAILBOX_NAME_FIELD = "firstFromMailboxName";
-    private static final String FIRST_FROM_MAILBOX_DISPLAY_FIELD = "firstFromMailboxDisplay";
-
-    /**
-     * {@link Field} which will contain the BCC-Address of the message
-     */
-    private static final String BCC_FIELD = "bcc";
-    
-    
-    private static final String BASE_SUBJECT_FIELD = "baseSubject";
-    
-    /**
-     * {@link Field} which contain the internalDate of the message with YEAR-Resolution
-     */
-    private static final String INTERNAL_DATE_FIELD_YEAR_RESOLUTION = "internaldateYearResolution";
-    
-    
-    /**
-     * {@link Field} which contain the internalDate of the message with MONTH-Resolution
-     */
-    private static final String INTERNAL_DATE_FIELD_MONTH_RESOLUTION = "internaldateMonthResolution";
-    
-    /**
-     * {@link Field} which contain the internalDate of the message with DAY-Resolution
-     */
-    private static final String INTERNAL_DATE_FIELD_DAY_RESOLUTION = "internaldateDayResolution";
-    
-    /**
-     * {@link Field} which contain the internalDate of the message with HOUR-Resolution
-     */
-    private static final String INTERNAL_DATE_FIELD_HOUR_RESOLUTION = "internaldateHourResolution";
-    
-    /**
-     * {@link Field} which contain the internalDate of the message with MINUTE-Resolution
-     */
-    private static final String INTERNAL_DATE_FIELD_MINUTE_RESOLUTION = "internaldateMinuteResolution";
-    
-    /**
-     * {@link Field} which contain the internalDate of the message with SECOND-Resolution
-     */
-    private static final String INTERNAL_DATE_FIELD_SECOND_RESOLUTION = "internaldateSecondResolution";
-    
-    
-    /**
-     * {@link Field} which contain the internalDate of the message with MILLISECOND-Resolution
-     */
-    private static final String INTERNAL_DATE_FIELD_MILLISECOND_RESOLUTION = "internaldateMillisecondResolution";
-
-    /**
-     * {@link Field} which will contain the id of the {@link Mailbox}
-     */
-    private static final String MAILBOX_ID_FIELD = "mailboxid";
-
-    /**
-     * {@link Field} which will contain the user of the {@link MailboxSession}
-     */
-    private static final String USERS = "userSession";
-    /**
-     * {@link Field} which will contain the id of the {@link MessageId}
-     */
-    private static final String MESSAGE_ID_FIELD = "messageid";
-
-    /**
-     * {@link Field} which contain the Date header of the message with YEAR-Resolution
-     */
-    private static final String SENT_DATE_FIELD_YEAR_RESOLUTION = "sentdateYearResolution";
-    
-    
-    /**
-     * {@link Field} which contain the Date header of the message with MONTH-Resolution
-     */
-    private static final String SENT_DATE_FIELD_MONTH_RESOLUTION = "sentdateMonthResolution";
-    
-    /**
-     * {@link Field} which contain the Date header of the message with DAY-Resolution
-     */
-    private static final String SENT_DATE_FIELD_DAY_RESOLUTION = "sentdateDayResolution";
-    
-    /**
-     * {@link Field} which contain the Date header of the message with HOUR-Resolution
-     */
-    private static final String SENT_DATE_FIELD_HOUR_RESOLUTION = "sentdateHourResolution";
-    
-    /**
-     * {@link Field} which contain the Date header of the message with MINUTE-Resolution
-     */
-    private static final String SENT_DATE_FIELD_MINUTE_RESOLUTION = "sentdateMinuteResolution";
-    
-    /**
-     * {@link Field} which contain the Date header of the message with SECOND-Resolution
-     */
-    private static final String SENT_DATE_FIELD_SECOND_RESOLUTION = "sentdateSecondResolution";
-    
-    
-    /**
-     * {@link Field} which contain the Date header of the message with MILLISECOND-Resolution
-     */
-    private static final String SENT_DATE_FIELD_MILLISECOND_RESOLUTION = "sentdateMillisecondResolution";
-
-    private static final String SENT_DATE_SORT_FIELD_MILLISECOND_RESOLUTION = "sentdateSort";
-
-    private static final String MEDIA_TYPE_TEXT = "text";
-    private static final String MEDIA_TYPE_MESSAGE = "message";
-    private static final String DEFAULT_ENCODING = "US-ASCII";
-    
-    private static final SortField UID_SORT = new SortField(UID_FIELD, SortField.LONG);
-    private static final SortField UID_SORT_REVERSE = new SortField(UID_FIELD, SortField.LONG, true);
-
-    private static final SortField SIZE_SORT = new SortField(SIZE_FIELD, SortField.LONG);
-    private static final SortField SIZE_SORT_REVERSE = new SortField(SIZE_FIELD, SortField.LONG, true);
-
-    private static final SortField FIRST_CC_MAILBOX_SORT = new SortField(FIRST_CC_MAILBOX_NAME_FIELD, SortField.STRING);
-    private static final SortField FIRST_CC_MAILBOX_SORT_REVERSE = new SortField(FIRST_CC_MAILBOX_NAME_FIELD, SortField.STRING, true);
-
-    private static final SortField FIRST_TO_MAILBOX_SORT = new SortField(FIRST_TO_MAILBOX_NAME_FIELD, SortField.STRING);
-    private static final SortField FIRST_TO_MAILBOX_SORT_REVERSE = new SortField(FIRST_TO_MAILBOX_NAME_FIELD, SortField.STRING, true);
-
-    private static final SortField FIRST_FROM_MAILBOX_SORT = new SortField(FIRST_FROM_MAILBOX_NAME_FIELD, SortField.STRING);
-    private static final SortField FIRST_FROM_MAILBOX_SORT_REVERSE = new SortField(FIRST_FROM_MAILBOX_NAME_FIELD, SortField.STRING, true);
-
-    
-    private static final SortField ARRIVAL_MAILBOX_SORT = new SortField(INTERNAL_DATE_FIELD_MILLISECOND_RESOLUTION, SortField.LONG);
-    private static final SortField ARRIVAL_MAILBOX_SORT_REVERSE = new SortField(INTERNAL_DATE_FIELD_MILLISECOND_RESOLUTION, SortField.LONG, true);
-
-    private static final SortField BASE_SUBJECT_SORT = new SortField(BASE_SUBJECT_FIELD, SortField.STRING);
-    private static final SortField BASE_SUBJECT_SORT_REVERSE = new SortField(BASE_SUBJECT_FIELD, SortField.STRING, true);
-    
-    private static final SortField SENT_DATE_SORT = new SortField(SENT_DATE_SORT_FIELD_MILLISECOND_RESOLUTION, SortField.LONG);
-    private static final SortField SENT_DATE_SORT_REVERSE = new SortField(SENT_DATE_SORT_FIELD_MILLISECOND_RESOLUTION, SortField.LONG, true);
-    
-    private static final SortField FIRST_TO_MAILBOX_DISPLAY_SORT = new SortField(FIRST_TO_MAILBOX_DISPLAY_FIELD, SortField.STRING);
-    private static final SortField FIRST_TO_MAILBOX_DISPLAY_SORT_REVERSE = new SortField(FIRST_TO_MAILBOX_DISPLAY_FIELD, SortField.STRING, true);
-
-    private static final SortField FIRST_FROM_MAILBOX_DISPLAY_SORT = new SortField(FIRST_FROM_MAILBOX_DISPLAY_FIELD, SortField.STRING);
-    private static final SortField FIRST_FROM_MAILBOX_DISPLAY_SORT_REVERSE = new SortField(FIRST_FROM_MAILBOX_DISPLAY_FIELD, SortField.STRING, true);
-    
-    private final MailboxId.Factory mailboxIdFactory;
-    private final MessageId.Factory messageIdFactory;
-    private final IndexWriter writer;
-
-    private int maxQueryResults = DEFAULT_MAX_QUERY_RESULTS;
-
-    private boolean suffixMatch = false;
-
-    @Inject
-    public LuceneMessageSearchIndex(
-        MessageMapperFactory factory,
-        MailboxId.Factory mailboxIdFactory,
-        Directory directory,
-        MessageId.Factory messageIdFactory
-    ) throws IOException {
-        this(factory, mailboxIdFactory, directory, false, true, messageIdFactory);
-    }
-
-    public LuceneMessageSearchIndex(
-            MessageMapperFactory factory,
-            MailboxId.Factory mailboxIdFactory,
-            Directory directory,
-            boolean dropIndexOnStart,
-            boolean lenient,
-            MessageId.Factory messageIdFactory
-    ) throws IOException {
-        super(factory);
-        this.mailboxIdFactory = mailboxIdFactory;
-        this.messageIdFactory = messageIdFactory;
-        this.writer = new IndexWriter(directory,  createConfig(createAnalyzer(lenient), dropIndexOnStart));
-    }
-    
-    
-    public LuceneMessageSearchIndex(MessageMapperFactory factory, MailboxId.Factory mailboxIdFactory, MessageId.Factory messageIdFactory, IndexWriter writer) {
-        super(factory);
-        this.mailboxIdFactory = mailboxIdFactory;
-        this.messageIdFactory = messageIdFactory;
-        this.writer = writer;
-    }
-
-    @Override
-    public ListenerType getType() {
-        return ListenerType.EACH_NODE;
-    }
-
-
-    @Override
-    public EnumSet<SearchCapabilities> getSupportedCapabilities(EnumSet<MailboxManager.MessageCapabilities> messageCapabilities) {
-        return EnumSet.of(SearchCapabilities.MultimailboxSearch);
-
-    }
-    
-    /**
-     * Set the max count of results which will get returned from a query. The default is {@link #DEFAULT_MAX_QUERY_RESULTS}
-     * 
-     * @param maxQueryResults
-     */
-    public void setMaxQueryResults(int maxQueryResults) {
-        this.maxQueryResults = maxQueryResults;
-    }
-    
-    protected IndexWriterConfig createConfig(Analyzer analyzer, boolean dropIndexOnStart) {
-        IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_31, analyzer);
-        if (dropIndexOnStart) {
-            config.setOpenMode(OpenMode.CREATE);
-        } else {
-            config.setOpenMode(OpenMode.CREATE_OR_APPEND);
-        }
-        return config;
-    }
-    
-    /**
-     * Create a {@link Analyzer} which is used to index the {@link MailboxMessage}'s
-     * 
-     * @param lenient 
-     * 
-     * @return analyzer
-     */
-    protected Analyzer createAnalyzer(boolean lenient) {
-        if (lenient) {
-           return new LenientImapSearchAnalyzer();
-        } else {
-            return new StrictImapSearchAnalyzer();
-        }
-    }
-    
-    /**
-     * If set to true this implementation will use {@link WildcardQuery} to match suffix and prefix. This is what RFC3501 expects but is often not what the user does.
-     * It also slow things a lot if you have complex queries which use many "TEXT" arguments. If you want the implementation to behave strict like RFC3501 says, you should
-     * set this to true. 
-     * 
-     * The default is false for performance reasons
-     * 
-     * 
-     * @param suffixMatch
-     */
-    public void setEnableSuffixMatch(boolean suffixMatch) {
-        this.suffixMatch = suffixMatch;
-    }
-    
-    
-    
-    @Override
-    public Iterator<MessageUid> search(MailboxSession session, Mailbox mailbox, SearchQuery searchQuery) throws MailboxException {
-        Preconditions.checkArgument(session != null, "'session' is mandatory");
-
-        return searchMultimap(ImmutableList.of(mailbox.getMailboxId()), searchQuery)
-            .stream()
-            .map(SearchResult::getMessageUid)
-            .iterator();
-    }
-
-    @Override
-    public List<MessageId> search(MailboxSession session, Collection<MailboxId> mailboxIds, SearchQuery searchQuery, long limit) throws MailboxException {
-        Preconditions.checkArgument(session != null, "'session' is mandatory");
-        if (mailboxIds.isEmpty()) {
-            return ImmutableList.of();
-        }
-
-        return searchMultimap(mailboxIds, searchQuery)
-            .stream()
-            .map(searchResult -> searchResult.getMessageId().get())
-            .filter(SearchUtil.distinct())
-            .limit(Long.valueOf(limit).intValue())
-            .collect(Guavate.toImmutableList());
-    }
-    
-    private List<SearchResult> searchMultimap(Collection<MailboxId> mailboxIds, SearchQuery searchQuery) throws MailboxException {
-        ImmutableList.Builder<SearchResult> results = ImmutableList.builder();
-        IndexSearcher searcher = null;
-
-        Query inMailboxes = buildQueryFromMailboxes(mailboxIds);
-        
-        try {
-            searcher = new IndexSearcher(IndexReader.open(writer, true));
-            BooleanQuery query = new BooleanQuery();
-            query.add(inMailboxes, BooleanClause.Occur.MUST);
-            // Not return flags documents
-            query.add(new PrefixQuery(new Term(FLAGS_FIELD, "")), BooleanClause.Occur.MUST_NOT);
-
-            List<Criterion> crits = searchQuery.getCriterias();
-            for (Criterion crit : crits) {
-                query.add(createQuery(crit, inMailboxes, searchQuery.getRecentMessageUids()), BooleanClause.Occur.MUST);
-            }
-
-            // query for all the documents sorted as specified in the SearchQuery
-            TopDocs docs = searcher.search(query, null, maxQueryResults, createSort(searchQuery.getSorts()));
-            ScoreDoc[] sDocs = docs.scoreDocs;
-            for (ScoreDoc sDoc : sDocs) {
-                Document doc = searcher.doc(sDoc.doc);
-                MessageUid uid = MessageUid.of(Long.valueOf(doc.get(UID_FIELD)));
-                MailboxId mailboxId = mailboxIdFactory.fromString(doc.get(MAILBOX_ID_FIELD));
-                Optional<MessageId> messageId = toMessageId(Optional.ofNullable(doc.get(MESSAGE_ID_FIELD)));
-                results.add(new SearchResult(messageId, mailboxId, uid));
-            }
-        } catch (IOException e) {
-            throw new MailboxException("Unable to search the mailbox", e);
-        } finally {
-            if (searcher != null) {
-                try {
-                    searcher.close();
-                } catch (IOException e) {
-                    // ignore on close
-                }
-            }
-        }
-        return results.build();
-    }
-
-    private Optional<MessageId> toMessageId(Optional<String> messageIdField) {
-        if (messageIdField.isPresent()) {
-            return Optional.of(messageIdFactory.fromString(messageIdField.get()));
-        }
-        return Optional.empty();
-    }
-
-    private Query buildQueryFromMailboxes(Collection<MailboxId> mailboxIds) {
-        BooleanQuery query = new BooleanQuery();
-        for (MailboxId id: mailboxIds) {
-            String idAsString = id.serialize();
-            query.add(new TermQuery(new Term(MAILBOX_ID_FIELD, idAsString)), BooleanClause.Occur.SHOULD);
-        }
-        return query;
-    }
-
-
-    /**
-     * Create a new {@link Document} for the given {@link MailboxMessage}. This Document does not contain any flags data. The {@link Flags} are stored in a seperate Document.
-     * 
-     * See {@link #createFlagsDocument(MailboxMessage)}
-     * 
-     * @param membership
-     * @return document
-     */
-    private Document createMessageDocument(final MailboxSession session, final MailboxMessage membership) throws MailboxException {
-        final Document doc = new Document();
-        // TODO: Better handling
-        doc.add(new Field(USERS, session.getUser().getUserName().toUpperCase(Locale.US), Store.YES, Index.NOT_ANALYZED));
-        doc.add(new Field(MAILBOX_ID_FIELD, membership.getMailboxId().serialize().toUpperCase(Locale.US), Store.YES, Index.NOT_ANALYZED));
-        doc.add(new NumericField(UID_FIELD,Store.YES, true).setLongValue(membership.getUid().asLong()));
-        doc.add(new Field(HAS_ATTACHMENT_FIELD, Boolean.toString(hasAttachment(membership)), Store.YES, Index.NOT_ANALYZED));
-        doc.add(new Field(MESSAGE_ID_FIELD, SearchUtil.getSerializedMessageIdIfSupportedByUnderlyingStorageOrNull(membership), Store.YES, Index.NOT_ANALYZED));
-
-        // create an unqiue key for the document which can be used later on updates to find the document
-        doc.add(new Field(ID_FIELD, membership.getMailboxId().serialize().toUpperCase(Locale.US) + "-" + Long.toString(membership.getUid().asLong()), Store.YES, Index.NOT_ANALYZED));
-
-        doc.add(new Field(INTERNAL_DATE_FIELD_YEAR_RESOLUTION, DateTools.dateToString(membership.getInternalDate(), DateTools.Resolution.YEAR), Store.NO, Index.NOT_ANALYZED));
-        doc.add(new Field(INTERNAL_DATE_FIELD_MONTH_RESOLUTION, DateTools.dateToString(membership.getInternalDate(), DateTools.Resolution.MONTH), Store.NO, Index.NOT_ANALYZED));
-        doc.add(new Field(INTERNAL_DATE_FIELD_DAY_RESOLUTION, DateTools.dateToString(membership.getInternalDate(), DateTools.Resolution.DAY), Store.NO, Index.NOT_ANALYZED));
-        doc.add(new Field(INTERNAL_DATE_FIELD_HOUR_RESOLUTION, DateTools.dateToString(membership.getInternalDate(), DateTools.Resolution.HOUR), Store.NO, Index.NOT_ANALYZED));
-        doc.add(new Field(INTERNAL_DATE_FIELD_MINUTE_RESOLUTION, DateTools.dateToString(membership.getInternalDate(), DateTools.Resolution.MINUTE), Store.NO, Index.NOT_ANALYZED));
-        doc.add(new Field(INTERNAL_DATE_FIELD_SECOND_RESOLUTION, DateTools.dateToString(membership.getInternalDate(), DateTools.Resolution.SECOND), Store.NO, Index.NOT_ANALYZED));
-        doc.add(new Field(INTERNAL_DATE_FIELD_MILLISECOND_RESOLUTION, DateTools.dateToString(membership.getInternalDate(), DateTools.Resolution.MILLISECOND), Store.NO, Index.NOT_ANALYZED));
-
-        doc.add(new NumericField(SIZE_FIELD,Store.YES, true).setLongValue(membership.getFullContentOctets()));
-
-        // content handler which will index the headers and the body of the message
-        SimpleContentHandler handler = new SimpleContentHandler() {
-            
-
-            @Override
-            public void headers(Header header) {
-                
-                Date sentDate = null;
-                String firstFromMailbox = "";
-                String firstToMailbox = "";
-                String firstCcMailbox = "";
-                String firstFromDisplay = "";
-                String firstToDisplay = "";
-                
-                Iterator<org.apache.james.mime4j.stream.Field> fields = header.iterator();
-                while (fields.hasNext()) {
-                    org.apache.james.mime4j.stream.Field f = fields.next();
-                    String headerName = f.getName().toUpperCase(Locale.US);
-                    String headerValue = f.getBody().toUpperCase(Locale.US);
-                    String fullValue =  f.toString().toUpperCase(Locale.US);
-                    doc.add(new Field(HEADERS_FIELD, fullValue, Store.NO, Index.ANALYZED));
-                    doc.add(new Field(PREFIX_HEADER_FIELD + headerName, headerValue, Store.NO, Index.ANALYZED));
-                    
-                    if (f instanceof DateTimeField) {
-                        // We need to make sure we convert it to GMT
-                        final StringReader reader = new StringReader(f.getBody());
-                        try {
-                            DateTime dateTime = new DateTimeParser(reader).parseAll();
-                            Calendar cal = getGMT();
-                            cal.set(dateTime.getYear(), dateTime.getMonth() - 1, dateTime.getDay(), dateTime.getHour(), dateTime.getMinute(), dateTime.getSecond());
-                            sentDate =  cal.getTime();
-                            
-                        } catch (org.apache.james.mime4j.field.datetime.parser.ParseException e) {
-                            LOGGER.debug("Unable to parse Date header for proper indexing", e);
-                            // This should never happen anyway fallback to the already parsed field
-                            sentDate = ((DateTimeField) f).getDate();
-                        }
-                        if (sentDate == null) {
-                            sentDate = membership.getInternalDate();
-                        }
-
-                    } 
-                        String field = null;
-                        if ("To".equalsIgnoreCase(headerName)) {
-                            field = TO_FIELD;
-                        } else if ("From".equalsIgnoreCase(headerName)) {
-                            field = FROM_FIELD;
-                        } else if ("Cc".equalsIgnoreCase(headerName)) {
-                            field = CC_FIELD;
-                        } else if ("Bcc".equalsIgnoreCase(headerName)) {
-                            field = BCC_FIELD;
-                        }
-                        
-
-                        // Check if we can index the the address in the right manner
-                        if (field != null) {
-                                // not sure if we really should reparse it. It maybe be better to check just for the right type.
-                                // But this impl was easier in the first place
-                                AddressList aList = LenientAddressParser.DEFAULT.parseAddressList(MimeUtil.unfold(f.getBody()));
-                                for (int i = 0; i < aList.size(); i++) {
-                                    Address address = aList.get(i);
-                                    if (address instanceof org.apache.james.mime4j.dom.address.Mailbox) {
-                                        org.apache.james.mime4j.dom.address.Mailbox mailbox = (org.apache.james.mime4j.dom.address.Mailbox) address;
-                                        String value = AddressFormatter.DEFAULT.encode(mailbox).toUpperCase(Locale.US);
-                                        doc.add(new Field(field, value, Store.NO, Index.ANALYZED));
-                                        if (i == 0) {
-                                            String mailboxAddress = SearchUtil.getMailboxAddress(mailbox);
-                                            String mailboxDisplay = SearchUtil.getDisplayAddress(mailbox);
-
-                                            if ("To".equalsIgnoreCase(headerName)) {
-                                                firstToMailbox = mailboxAddress;
-                                                firstToDisplay = mailboxDisplay;
-                                            } else if ("From".equalsIgnoreCase(headerName)) {
-                                                firstFromMailbox = mailboxAddress;
-                                                firstFromDisplay = mailboxDisplay;
-                                                
-                                            } else if ("Cc".equalsIgnoreCase(headerName)) {
-                                                firstCcMailbox = mailboxAddress;
-                                            }
-                                            
-                                        }
-                                    } else if (address instanceof Group) {
-                                        MailboxList mList = ((Group) address).getMailboxes();
-                                        for (int a = 0; a < mList.size(); a++) {
-                                            org.apache.james.mime4j.dom.address.Mailbox mailbox = mList.get(a);
-                                            String value = AddressFormatter.DEFAULT.encode(mailbox).toUpperCase(Locale.US);
-                                            doc.add(new Field(field, value, Store.NO, Index.ANALYZED));
-
-                                            if (i == 0 && a == 0) {
-                                                String mailboxAddress = SearchUtil.getMailboxAddress(mailbox);
-                                                String mailboxDisplay = SearchUtil.getDisplayAddress(mailbox);
-
-                                                if ("To".equalsIgnoreCase(headerName)) {
-                                                    firstToMailbox = mailboxAddress;
-                                                    firstToDisplay = mailboxDisplay;
-                                                } else if ("From".equalsIgnoreCase(headerName)) {
-                                                    firstFromMailbox = mailboxAddress;
-                                                    firstFromDisplay = mailboxDisplay;
-
-                                                } else if ("Cc".equalsIgnoreCase(headerName)) {
-                                                    firstCcMailbox = mailboxAddress;
-                                                }
-                                            }
-                                        }
-                                    }
-                                }
-
-                            
-                            doc.add(new Field(field, headerValue, Store.NO, Index.ANALYZED));
-
-                    } else if (headerName.equalsIgnoreCase("Subject")) {
-                        doc.add(new Field(BASE_SUBJECT_FIELD, SearchUtil.getBaseSubject(headerValue), Store.YES, Index.NOT_ANALYZED));
-                    } 
-                }
-                if (sentDate == null) {
-                    sentDate = membership.getInternalDate();
-                } else {
-                    
-                    doc.add(new Field(SENT_DATE_FIELD_YEAR_RESOLUTION, DateTools.dateToString(sentDate, DateTools.Resolution.YEAR), Store.NO, Index.NOT_ANALYZED));
-                    doc.add(new Field(SENT_DATE_FIELD_MONTH_RESOLUTION, DateTools.dateToString(sentDate, DateTools.Resolution.MONTH), Store.NO, Index.NOT_ANALYZED));
-                    doc.add(new Field(SENT_DATE_FIELD_DAY_RESOLUTION, DateTools.dateToString(sentDate, DateTools.Resolution.DAY), Store.NO, Index.NOT_ANALYZED));
-                    doc.add(new Field(SENT_DATE_FIELD_HOUR_RESOLUTION, DateTools.dateToString(sentDate, DateTools.Resolution.HOUR), Store.NO, Index.NOT_ANALYZED));
-                    doc.add(new Field(SENT_DATE_FIELD_MINUTE_RESOLUTION, DateTools.dateToString(sentDate, DateTools.Resolution.MINUTE), Store.NO, Index.NOT_ANALYZED));
-                    doc.add(new Field(SENT_DATE_FIELD_SECOND_RESOLUTION, DateTools.dateToString(sentDate, DateTools.Resolution.SECOND), Store.NO, Index.NOT_ANALYZED));
-                    doc.add(new Field(SENT_DATE_FIELD_MILLISECOND_RESOLUTION, DateTools.dateToString(sentDate, DateTools.Resolution.MILLISECOND), Store.NO, Index.NOT_ANALYZED));
-                    
-                }
-                doc.add(new Field(SENT_DATE_SORT_FIELD_MILLISECOND_RESOLUTION,DateTools.dateToString(sentDate, DateTools.Resolution.MILLISECOND), Store.NO, Index.NOT_ANALYZED));
-
-                doc.add(new Field(FIRST_FROM_MAILBOX_NAME_FIELD, firstFromMailbox, Store.YES, Index.NOT_ANALYZED));
-                doc.add(new Field(FIRST_TO_MAILBOX_NAME_FIELD, firstToMailbox, Store.YES, Index.NOT_ANALYZED));
-                doc.add(new Field(FIRST_CC_MAILBOX_NAME_FIELD, firstCcMailbox, Store.YES, Index.NOT_ANALYZED));
-                doc.add(new Field(FIRST_FROM_MAILBOX_DISPLAY_FIELD, firstFromDisplay, Store.YES, Index.NOT_ANALYZED));
-                doc.add(new Field(FIRST_TO_MAILBOX_DISPLAY_FIELD, firstToDisplay, Store.YES, Index.NOT_ANALYZED));
-           
-            }
-
-            @Override
-            public void body(BodyDescriptor desc, InputStream in) throws MimeException, IOException {
-                String mediaType = desc.getMediaType();
-                if (MEDIA_TYPE_TEXT.equalsIgnoreCase(mediaType) || MEDIA_TYPE_MESSAGE.equalsIgnoreCase(mediaType)) {
-                    String cset = desc.getCharset();
-                    if (cset == null) {
-                        cset = DEFAULT_ENCODING;
-                    }
-                    Charset charset;
-                    try {
-                        charset = Charset.forName(cset);
-                    } catch (Exception e) {
-                        // Invalid charset found so fallback toe the DEFAULT_ENCODING
-                        charset = Charset.forName(DEFAULT_ENCODING);
-                    }
-                    
-                    // Read the content one line after the other and add it to the document
-                    BufferedReader bodyReader = new BufferedReader(new InputStreamReader(in, charset));
-                    String line = null;
-                    while ((line = bodyReader.readLine()) != null) {
-                        doc.add(new Field(BODY_FIELD,  line.toUpperCase(Locale.US),Store.NO, Index.ANALYZED));
-                    }
-                    
-                }
-            }
- 
-        };
-        //config.setStrictParsing(false);
-        MimeStreamParser parser = new MimeStreamParser(MimeConfig.PERMISSIVE);
-        parser.setContentDecoding(true);
-        parser.setContentHandler(handler);
-       
-        try {
-            // parse the message to index headers and body
-            parser.parse(membership.getFullContent());
-        } catch (MimeException | IOException e) {
-            // This should never happen as it was parsed before too without problems.            
-            throw new MailboxException("Unable to index content of message", e);
-        }
-
-
-        return doc;
-    }
-
-    private static boolean hasAttachment(MailboxMessage membership) {
-       return membership.getProperties().stream()
-            .anyMatch(PropertyBuilder.isHasAttachmentProperty());
-    }
-
-    private String toSentDateField(DateResolution res) {
-        switch (res) {
-            case Year:
-                return SENT_DATE_FIELD_YEAR_RESOLUTION;
-            case Month:
-                return SENT_DATE_FIELD_MONTH_RESOLUTION;
-            case Day:
-                return SENT_DATE_FIELD_DAY_RESOLUTION;
-            case Hour:
-                return SENT_DATE_FIELD_HOUR_RESOLUTION;
-            case Minute:
-                return SENT_DATE_FIELD_MINUTE_RESOLUTION;
-            case Second:
-                return SENT_DATE_FIELD_SECOND_RESOLUTION;
-            default:
-                return SENT_DATE_FIELD_MILLISECOND_RESOLUTION;
-        }
-    }
-
-    private static Calendar getGMT() {
-        return Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
-    }
-
-    private String toInteralDateField(DateResolution res) {
-        switch (res) {
-            case Year:
-                return INTERNAL_DATE_FIELD_YEAR_RESOLUTION;
-            case Month:
-                return INTERNAL_DATE_FIELD_MONTH_RESOLUTION;
-            case Day:
-                return INTERNAL_DATE_FIELD_DAY_RESOLUTION;
-            case Hour:
-                return INTERNAL_DATE_FIELD_HOUR_RESOLUTION;
-            case Minute:
-                return INTERNAL_DATE_FIELD_MINUTE_RESOLUTION;
-            case Second:
-                return INTERNAL_DATE_FIELD_SECOND_RESOLUTION;
-            default:
-                return INTERNAL_DATE_FIELD_MILLISECOND_RESOLUTION;
-        }
-    }
-    
-    /**
-     * Return a {@link Query} which is build based on the given {@link SearchQuery.InternalDateCriterion}
-     * 
-     * @param crit
-     * @return query
-     * @throws UnsupportedSearchException
-     */
-    private Query createInternalDateQuery(SearchQuery.InternalDateCriterion crit) throws UnsupportedSearchException {
-        DateOperator dop = crit.getOperator();
-        DateResolution res = dop.getDateResultion();
-        String field = toInteralDateField(res);
-        return createQuery(field, dop);
-    }
-    
-    /**
-     * Return a {@link Query} which is build based on the given {@link SearchQuery.SizeCriterion}
-     * 
-     * @param crit
-     * @return query
-     * @throws UnsupportedSearchException
-     */
-    private Query createSizeQuery(SearchQuery.SizeCriterion crit) throws UnsupportedSearchException {
-        NumericOperator op = crit.getOperator();
-        switch (op.getType()) {
-        case EQUALS:
-            return NumericRangeQuery.newLongRange(SIZE_FIELD, op.getValue(), op.getValue(), true, true);
-        case GREATER_THAN:
-            return NumericRangeQuery.newLongRange(SIZE_FIELD, op.getValue(), Long.MAX_VALUE, false, true);
-        case LESS_THAN:
-            return NumericRangeQuery.newLongRange(SIZE_FIELD, Long.MIN_VALUE, op.getValue(), true, false);
-        default:
-            throw new UnsupportedSearchException();
-        }
-    }
-    
-    /**
-     * This method will return the right {@link Query} depending if {@link #suffixMatch} is enabled
-     * 
-     * @param fieldName
-     * @param value
-     * @return query
-     */
-    private Query createTermQuery(String fieldName, String value) {
-        if (suffixMatch) {
-            return new WildcardQuery(new Term(fieldName, "*" + value + "*"));
-        } else {
-            return new PrefixQuery(new Term(fieldName, value));
-        }
-    }
-    
-    /**
-     * Return a {@link Query} which is build based on the given {@link SearchQuery.HeaderCriterion}
-     * 
-     * @param crit
-     * @return query
-     * @throws UnsupportedSearchException
-     */
-    private Query createHeaderQuery(SearchQuery.HeaderCriterion crit) throws UnsupportedSearchException {
-        HeaderOperator op = crit.getOperator();
-        String name = crit.getHeaderName().toUpperCase(Locale.US);
-        String fieldName = PREFIX_HEADER_FIELD + name;
-        if (op instanceof SearchQuery.ContainsOperator) {
-            ContainsOperator cop = (ContainsOperator) op;
-            return createTermQuery(fieldName, cop.getValue().toUpperCase(Locale.US));
-        } else if (op instanceof SearchQuery.ExistsOperator) {
-            return new PrefixQuery(new Term(fieldName, ""));
-        } else if (op instanceof SearchQuery.DateOperator) {
-                DateOperator dop = (DateOperator) op;
-                String field = toSentDateField(dop.getDateResultion());
-                return createQuery(field, dop);
-        } else if (op instanceof SearchQuery.AddressOperator) {
-            String field = name.toLowerCase(Locale.US);
-            return createTermQuery(field, ((SearchQuery.AddressOperator) op).getAddress().toUpperCase(Locale.US));
-        } else {
-            // Operator not supported
-            throw new UnsupportedSearchException();
-        }
-    }
-    
-    
-    private Query createQuery(String field, DateOperator dop) throws UnsupportedSearchException {
-        Date date = dop.getDate();
-        DateResolution res = dop.getDateResultion();
-        DateTools.Resolution dRes = toResolution(res);
-        String value = DateTools.dateToString(date, dRes);
-        switch (dop.getType()) {
-        case ON:
-            return new TermQuery(new Term(field, value));
-        case BEFORE: 
-            return new TermRangeQuery(field, DateTools.dateToString(MIN_DATE, dRes), value, true, false);
-        case AFTER: 
-            return new TermRangeQuery(field, value, DateTools.dateToString(MAX_DATE, dRes), false, true);
-        default:
-            throw new UnsupportedSearchException();
-        }
-    }
-    
-    private DateTools.Resolution toResolution(DateResolution res) {
-        switch (res) {
-        case Year:
-            return DateTools.Resolution.YEAR;
-        case Month:
-            return DateTools.Resolution.MONTH;
-        case Day:
-            return DateTools.Resolution.DAY;
-        case Hour:
-            return DateTools.Resolution.HOUR;
-        case Minute:
-            return DateTools.Resolution.MINUTE;
-        case Second:
-            return DateTools.Resolution.SECOND;
-        default:
-            return DateTools.Resolution.MILLISECOND;
-        }
-    }
-    
-    /**
-     * Return a {@link Query} which is build based on the given {@link SearchQuery.UidCriterion}
-     */
-    private Query createUidQuery(SearchQuery.UidCriterion crit) throws UnsupportedSearchException {
-        UidRange[] ranges = crit.getOperator().getRange();
-        if (ranges.length == 1) {
-            UidRange range = ranges[0];
-            return NumericRangeQuery.newLongRange(UID_FIELD, range.getLowValue().asLong(), range.getHighValue().asLong(), true, true);
-        } else {
-            BooleanQuery rangesQuery = new BooleanQuery();
-            for (UidRange range : ranges) {
-                rangesQuery.add(NumericRangeQuery.newLongRange(UID_FIELD, range.getLowValue().asLong(), range.getHighValue().asLong(), true, true), BooleanClause.Occur.SHOULD);
-            }        
-            return rangesQuery;
-        }
-    }
-    
-    
-    /**
-     * Return a {@link Query} which is build based on the given {@link SearchQuery.UidCriterion}
-     * 
-     * @param crit
-     * @return query
-     * @throws UnsupportedSearchException
-     */
-    private Query createModSeqQuery(SearchQuery.ModSeqCriterion crit) throws UnsupportedSearchException {
-        NumericOperator op = crit.getOperator();
-        switch (op.getType()) {
-        case EQUALS:
-            return NumericRangeQuery.newLongRange(MODSEQ_FIELD, op.getValue(), op.getValue(), true, true);
-        case GREATER_THAN:
-            return NumericRangeQuery.newLongRange(MODSEQ_FIELD, op.getValue(), Long.MAX_VALUE, false, true);
-        case LESS_THAN:
-            return NumericRangeQuery.newLongRange(MODSEQ_FIELD, Long.MIN_VALUE, op.getValue(), true, false);
-        default:
-            throw new UnsupportedSearchException();
-        }
-    }
-    
-    private Query createAttachmentQuery(boolean isSet) throws MailboxException {
-        return new TermQuery(new Term(HAS_ATTACHMENT_FIELD, Boolean.toString(isSet)));
-    }
-
-    /**
-     * Return a {@link Query} which is build based on the given {@link SearchQuery.FlagCriterion}. This is kind of a hack
-     * as it will do a search for the flags in this method and 
-     *
-     * @return query
-     * @throws MailboxException
-     */
-    private Query createFlagQuery(String flag, boolean isSet, Query inMailboxes, Collection<MessageUid> recentUids) throws MailboxException {
-        BooleanQuery query = new BooleanQuery();
-        
-        if (isSet) {   
-            query.add(new TermQuery(new Term(FLAGS_FIELD, flag)), BooleanClause.Occur.MUST);
-        } else {
-            // lucene does not support simple NOT queries so we do some nasty hack here
-            BooleanQuery bQuery = new BooleanQuery();
-            bQuery.add(new PrefixQuery(new Term(FLAGS_FIELD, "")), BooleanClause.Occur.MUST);
-            bQuery.add(new TermQuery(new Term(FLAGS_FIELD, flag)),BooleanClause.Occur.MUST_NOT);
-            
-            query.add(bQuery, BooleanClause.Occur.MUST);
-        }
-        query.add(inMailboxes, BooleanClause.Occur.MUST);
-        
-        
-        IndexSearcher searcher = null;
-
-        try {
-            Set<MessageUid> uids = new HashSet<>();
-            searcher = new IndexSearcher(IndexReader.open(writer, true));
-            
-            // query for all the documents sorted by uid
-            TopDocs docs = searcher.search(query, null, maxQueryResults, new Sort(UID_SORT));
-            ScoreDoc[] sDocs = docs.scoreDocs;
-            for (ScoreDoc sDoc : sDocs) {
-                MessageUid uid = MessageUid.of(Long.valueOf(searcher.doc(sDoc.doc).get(UID_FIELD)));
-                uids.add(uid);
-            }
-            
-            // add or remove recent uids
-            if (flag.equalsIgnoreCase("\\RECENT")) {
-                if (isSet) {
-                    uids.addAll(recentUids);
-                } else {
-                    uids.removeAll(recentUids);
-                }
-            }
-            
-            List<MessageRange> ranges = MessageRange.toRanges(new ArrayList<>(uids));
-            UidRange[] nRanges = new UidRange[ranges.size()];
-            for (int i = 0; i < ranges.size(); i++) {
-                MessageRange range = ranges.get(i);
-                nRanges[i] = new UidRange(range.getUidFrom(), range.getUidTo());
-            }
-            return createUidQuery((UidCriterion) SearchQuery.uid(nRanges));
-        } catch (IOException e) {
-            throw new MailboxException("Unable to search mailbox " + inMailboxes, e);
-        } finally {
-            if (searcher != null) {
-                try {
-                    searcher.close();
-                } catch (IOException e) {
-                    // ignore on close
-                }
-            }
-        }
-    }
-    
-    private Sort createSort(List<SearchQuery.Sort> sorts) {
-        List<SortField> fields = new ArrayList<>();
-
-        for (SearchQuery.Sort sort : sorts) {
-            boolean reverse = sort.isReverse();
-            SortField sortField = createSortField(sort, reverse);
-            if (sortField != null) {
-
-                fields.add(sortField);
-
-                // Add the uid sort as tie-breaker
-                if (sortField == SENT_DATE_SORT) {
-                    fields.add(UID_SORT);
-                } else if (sortField == SENT_DATE_SORT_REVERSE) {
-                    fields.add(UID_SORT_REVERSE);
-                }
-            }
-        }
-        // add the uid sorting as last so if no other sorting was able to do the job it will get sorted by the uid
-        fields.add(UID_SORT);
-        Sort sort = new Sort();
-        sort.setSort(fields.toArray(new SortField[0]));
-        return sort;
-    }
-
-    private SortField createSortField(SearchQuery.Sort s, boolean reverse) {
-        switch (s.getSortClause()) {
-            case Arrival:
-                if (reverse) {
-                    return ARRIVAL_MAILBOX_SORT_REVERSE;
-                }
-                return ARRIVAL_MAILBOX_SORT;
-            case SentDate:
-                if (reverse) {
-                    return SENT_DATE_SORT_REVERSE;
-                }
-                return SENT_DATE_SORT;
-            case MailboxCc:
-                if (reverse) {
-                    return FIRST_CC_MAILBOX_SORT_REVERSE;
-                }
-                return FIRST_CC_MAILBOX_SORT;
-            case MailboxFrom:
-                if (reverse) {
-                    return FIRST_FROM_MAILBOX_SORT_REVERSE;
-                }
-                return FIRST_FROM_MAILBOX_SORT;
-            case Size:
-                if (reverse) {
-                    return SIZE_SORT_REVERSE;
-                }
-                return SIZE_SORT;
-            case BaseSubject:
-                if (reverse) {
-                    return BASE_SUBJECT_SORT_REVERSE;
-                }
-                return BASE_SUBJECT_SORT;
-            case MailboxTo:
-                if (reverse) {
-                    return FIRST_TO_MAILBOX_SORT_REVERSE;
-                }
-                return FIRST_TO_MAILBOX_SORT;
-            case Uid:
-                if (reverse) {
-                    return UID_SORT_REVERSE;
-                }
-                return UID_SORT;
-            case DisplayFrom:
-                if (reverse) {
-                    return FIRST_FROM_MAILBOX_DISPLAY_SORT_REVERSE;
-                }
-                return FIRST_FROM_MAILBOX_DISPLAY_SORT;
-            case DisplayTo:
-                if (reverse) {
-                    return FIRST_TO_MAILBOX_DISPLAY_SORT_REVERSE;
-                }
-                return FIRST_TO_MAILBOX_DISPLAY_SORT;
-            default:
-                return null;
-        }
-    }
-
-    /**
-     * Convert the given {@link Flag} to a String
-     * 
-     * @param flag
-     * @return flagString
-     */
-    private String toString(Flag flag) {
-        if (Flag.ANSWERED.equals(flag)) {
-            return "\\ANSWERED";
-        } else if (Flag.DELETED.equals(flag)) {
-            return "\\DELETED";
-        } else if (Flag.DRAFT.equals(flag)) {
-            return "\\DRAFT";
-        } else if (Flag.FLAGGED.equals(flag)) {
-            return "\\FLAGGED";
-        } else if (Flag.RECENT.equals(flag)) {
-            return "\\RECENT";
-        } else if (Flag.SEEN.equals(flag)) {
-            return "\\FLAG";
-        } else {
-            return flag.toString();
-        }
-    }
-    
-    /**
-     * Return a {@link Query} which is build based on the given {@link SearchQuery.TextCriterion}
-     * 
-     * @param crit
-     * @return query
-     * @throws UnsupportedSearchException
-     */
-    private Query createTextQuery(SearchQuery.TextCriterion crit) throws UnsupportedSearchException {
-        String value = crit.getOperator().getValue().toUpperCase(Locale.US);
-        switch (crit.getType()) {
-        case BODY:
-            return createTermQuery(BODY_FIELD, value);
-        case FULL: 
-            BooleanQuery query = new BooleanQuery();
-            query.add(createTermQuery(BODY_FIELD, value), BooleanClause.Occur.SHOULD);
-            query.add(createTermQuery(HEADERS_FIELD,value), BooleanClause.Occur.SHOULD);
-            return query;
-        default:
-            throw new UnsupportedSearchException();
-        }
-    }
-    
-    /**
-     * Return a {@link Query} which is build based on the given {@link SearchQuery.AllCriterion}
-     * 
-     * @param crit
-     * @return query
-     * @throws UnsupportedSearchException
-     */
-    private Query createAllQuery(SearchQuery.AllCriterion crit) throws UnsupportedSearchException {
-        BooleanQuery query = new BooleanQuery();
-        
-        query.add(createQuery(MessageRange.all()), BooleanClause.Occur.MUST);
-        query.add(new PrefixQuery(new Term(FLAGS_FIELD, "")), BooleanClause.Occur.MUST_NOT);
-        
-        return query;
-    }
-    
-    /**
-     * Return a {@link Query} which is build based on the given {@link SearchQuery.ConjunctionCriterion}
-     * 
-     * @param crit
-     * @return query
-     * @throws UnsupportedSearchException
-     */
-    private Query createConjunctionQuery(SearchQuery.ConjunctionCriterion crit, Query inMailboxes, Collection<MessageUid> recentUids) throws UnsupportedSearchException, MailboxException {
-        List<Criterion> crits = crit.getCriteria();
-        BooleanQuery conQuery = new BooleanQuery();
-        switch (crit.getType()) {
-        case AND:
-            for (Criterion criterion : crits) {
-                conQuery.add(createQuery(criterion, inMailboxes, recentUids), BooleanClause.Occur.MUST);
-            }
-            return conQuery;
-        case OR:
-            for (Criterion criterion : crits) {
-                conQuery.add(createQuery(criterion, inMailboxes, recentUids), BooleanClause.Occur.SHOULD);
-            }
-            return conQuery;
-        case NOR:
-            BooleanQuery nor = new BooleanQuery();
-            for (Criterion criterion : crits) {
-                conQuery.add(createQuery(criterion, inMailboxes, recentUids), BooleanClause.Occur.SHOULD);
-            }
-            nor.add(inMailboxes, BooleanClause.Occur.MUST);
-
-            nor.add(conQuery, BooleanClause.Occur.MUST_NOT);
-            return nor;
-        default:
-            throw new UnsupportedSearchException();
-        }
-
-    }
-    
-    /**
-     * Return a {@link Query} which is builded based on the given {@link Criterion}
-     * 
-     * @param criterion
-     * @return query
-     * @throws UnsupportedSearchException
-     */
-    private Query createQuery(Criterion criterion, Query inMailboxes, Collection<MessageUid> recentUids) throws MailboxException {
-        if (criterion instanceof SearchQuery.InternalDateCriterion) {
-            SearchQuery.InternalDateCriterion crit = (SearchQuery.InternalDateCriterion) criterion;
-            return createInternalDateQuery(crit);
-        } else if (criterion instanceof SearchQuery.SizeCriterion) {
-            SearchQuery.SizeCriterion crit = (SearchQuery.SizeCriterion) criterion;
-            return createSizeQuery(crit);
-        } else if (criterion instanceof SearchQuery.HeaderCriterion) {
-            HeaderCriterion crit = (HeaderCriterion) criterion;
-            return createHeaderQuery(crit);
-        } else if (criterion instanceof SearchQuery.UidCriterion) {
-            SearchQuery.UidCriterion crit = (SearchQuery.UidCriterion) criterion;
-            return createUidQuery(crit);
-        } else if (criterion instanceof SearchQuery.FlagCriterion) {
-            FlagCriterion crit = (FlagCriterion) criterion;
-            return createFlagQuery(toString(crit.getFlag()), crit.getOperator().isSet(), inMailboxes, recentUids);
-        } else if (criterion instanceof SearchQuery.AttachmentCriterion) {
-            AttachmentCriterion crit = (AttachmentCriterion) criterion;
-            return createAttachmentQuery(crit.getOperator().isSet());
-        } else if (criterion instanceof SearchQuery.CustomFlagCriterion) {
-            CustomFlagCriterion crit = (CustomFlagCriterion) criterion;
-            return createFlagQuery(crit.getFlag(), crit.getOperator().isSet(), inMailboxes, recentUids);
-        } else if (criterion instanceof SearchQuery.TextCriterion) {
-            SearchQuery.TextCriterion crit = (SearchQuery.TextCriterion) criterion;
-            return createTextQuery(crit);
-        } else if (criterion instanceof SearchQuery.AllCriterion) {
-            return createAllQuery((AllCriterion) criterion);
-        } else if (criterion instanceof SearchQuery.ConjunctionCriterion) {
-            SearchQuery.ConjunctionCriterion crit = (SearchQuery.ConjunctionCriterion) criterion;
-            return createConjunctionQuery(crit, inMailboxes, recentUids);
-        } else if (criterion instanceof SearchQuery.ModSeqCriterion) {
-            return createModSeqQuery((SearchQuery.ModSeqCriterion) criterion);
-        } else if (criterion instanceof SearchQuery.MimeMessageIDCriterion) {
-            SearchQuery.MimeMessageIDCriterion mimeMessageIDCriterion = (SearchQuery.MimeMessageIDCriterion) criterion;
-            return createHeaderQuery(mimeMessageIDCriterion.asHeaderCriterion());
-        }
-        throw new UnsupportedSearchException();
-    }
-
-    @Override
-    public void add(MailboxSession session, Mailbox mailbox, MailboxMessage membership) throws MailboxException {
-        Document doc = createMessageDocument(session, membership);
-        Document flagsDoc = createFlagsDocument(membership);
-
-        try {
-            writer.addDocument(doc);
-            writer.addDocument(flagsDoc);
-        } catch (IOException e) {
-            throw new MailboxException("Unable to add message to index", e);
-        }
-    }
-
-    @Override
-    public void update(MailboxSession session, Mailbox mailbox, List<UpdatedFlags> updatedFlagsList) throws MailboxException {
-        for (UpdatedFlags updatedFlags : updatedFlagsList) {
-            update(mailbox, updatedFlags.getUid(), updatedFlags.getNewFlags());
-        }
-    }
-
-    private void update(Mailbox mailbox, MessageUid uid, Flags f) throws MailboxException {
-        IndexSearcher searcher = null;
-        try {
-            searcher = new IndexSearcher(IndexReader.open(writer, true));
-            BooleanQuery query = new BooleanQuery();
-            query.add(new TermQuery(new Term(MAILBOX_ID_FIELD, mailbox.getMailboxId().serialize())), BooleanClause.Occur.MUST);
-            query.add(createQuery(MessageRange.one(uid)), BooleanClause.Occur.MUST);
-            query.add(new PrefixQuery(new Term(FLAGS_FIELD, "")), BooleanClause.Occur.MUST);
-
-            TopDocs docs = searcher.search(query, 100000);
-            ScoreDoc[] sDocs = docs.scoreDocs;
-            for (ScoreDoc sDoc : sDocs) {
-                Document doc = searcher.doc(sDoc.doc);
-
-                if (doc.getFieldable(FLAGS_FIELD) == null) {
-                    doc.removeFields(FLAGS_FIELD);
-                    indexFlags(doc, f);
-
-                    writer.updateDocument(new Term(ID_FIELD, doc.get(ID_FIELD)), doc);
-
-                }
-            }
-        } catch (IOException e) {
-            throw new MailboxException("Unable to add messages in index", e);
-
-        } finally {
-            try {
-                IOUtils.closeWhileHandlingException(searcher);
-            } catch (IOException e) {
-                //can't happen anyway
-            }
-        }
-        
-    }
-
-    /**
-     * Index the {@link Flags} and add it to the {@link Document}
-     */
-    private Document createFlagsDocument(MailboxMessage message) {
-        Document doc = new Document();
-        doc.add(new Field(ID_FIELD, "flags-" + message.getMailboxId().serialize() + "-" + Long.toString(message.getUid().asLong()), Store.YES, Index.NOT_ANALYZED));
-        doc.add(new Field(MAILBOX_ID_FIELD, message.getMailboxId().serialize(), Store.YES, Index.NOT_ANALYZED));
-        doc.add(new NumericField(UID_FIELD,Store.YES, true).setLongValue(message.getUid().asLong()));
-        
-        indexFlags(doc, message.createFlags());
-        return doc;
-    }
-    
-    /**
-     * Add the given {@link Flags} to the {@link Document}
-     * 
-     * @param doc
-     * @param f
-     */
-    private void indexFlags(Document doc, Flags f) {
-        List<String> fString = new ArrayList<>();
-        Flag[] flags = f.getSystemFlags();
-        for (Flag flag : flags) {
-            fString.add(toString(flag));
-            doc.add(new Field(FLAGS_FIELD, toString(flag), Store.NO, Index.NOT_ANALYZED));
-        }
-        
-        String[] userFlags = f.getUserFlags();
-        for (String userFlag : userFlags) {
-            doc.add(new Field(FLAGS_FIELD, userFlag, Store.NO, Index.NOT_ANALYZED));
-        }
-        
-        // if no flags are there we just use a empty field
-        if (flags.length == 0 && userFlags.length == 0) {
-            doc.add(new Field(FLAGS_FIELD, "",Store.NO, Index.NOT_ANALYZED));
-        }
-        
-    }
-    
-    private Query createQuery(MessageRange range) {
-        switch (range.getType()) {
-        case ONE:
-            return NumericRangeQuery.newLongRange(UID_FIELD, 
-                    range.getUidFrom().asLong(), 
-                    range.getUidTo().asLong(), true, true);
-        case FROM:
-            return NumericRangeQuery.newLongRange(UID_FIELD, 
-                    range.getUidFrom().asLong(), 
-                    MessageUid.MAX_VALUE.asLong(), true, true);
-        default:
-            return NumericRangeQuery.newLongRange(UID_FIELD, MessageUid.MIN_VALUE.asLong(), MessageUid.MAX_VALUE.asLong(), true, true);
-        }
-    }
-
-    @Override
-    public void delete(MailboxSession session, Mailbox mailbox, List<MessageUid> expungedUids) throws MailboxException {
-        Collection<MessageRange> messageRanges = MessageRange.toRanges(expungedUids);
-        for (MessageRange messageRange : messageRanges) {
-            delete(mailbox, messageRange);
-        }
-    }
-
-    @Override
-    public void deleteAll(MailboxSession session, Mailbox mailbox) throws MailboxException {
-        delete(mailbox, MessageRange.all());
-    }
-
-    public void delete(Mailbox mailbox, MessageRange range) throws MailboxException {
-        BooleanQuery query = new BooleanQuery();
-        query.add(new TermQuery(new Term(MAILBOX_ID_FIELD, mailbox.getMailboxId().serialize())), BooleanClause.Occur.MUST);
-        query.add(createQuery(range), BooleanClause.Occur.MUST);
-        
-        try {
-            writer.deleteDocuments(query);
-        } catch (IOException e) {
-            throw new MailboxException("Unable to delete message from index", e);
-        }
-    }
+/****************************************************************
+ * 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.mailbox.lucene.search;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.StringReader;
+import java.nio.charset.Charset;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Date;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.Set;
+import java.util.TimeZone;
+
+import javax.inject.Inject;
+import javax.mail.Flags;
+import javax.mail.Flags.Flag;
+
+import org.apache.james.mailbox.MailboxManager;
+import org.apache.james.mailbox.MailboxManager.SearchCapabilities;
+import org.apache.james.mailbox.MailboxSession;
+import org.apache.james.mailbox.MessageUid;
+import org.apache.james.mailbox.exception.MailboxException;
+import org.apache.james.mailbox.exception.UnsupportedSearchException;
+import org.apache.james.mailbox.model.MailboxId;
+import org.apache.james.mailbox.model.MessageId;
+import org.apache.james.mailbox.model.MessageRange;
+import org.apache.james.mailbox.model.SearchQuery;
+import org.apache.james.mailbox.model.SearchQuery.AllCriterion;
+import org.apache.james.mailbox.model.SearchQuery.AttachmentCriterion;
+import org.apache.james.mailbox.model.SearchQuery.ContainsOperator;
+import org.apache.james.mailbox.model.SearchQuery.Criterion;
+import org.apache.james.mailbox.model.SearchQuery.CustomFlagCriterion;
+import org.apache.james.mailbox.model.SearchQuery.DateOperator;
+import org.apache.james.mailbox.model.SearchQuery.DateResolution;
+import org.apache.james.mailbox.model.SearchQuery.FlagCriterion;
+import org.apache.james.mailbox.model.SearchQuery.HeaderCriterion;
+import org.apache.james.mailbox.model.SearchQuery.HeaderOperator;
+import org.apache.james.mailbox.model.SearchQuery.NumericOperator;
+import org.apache.james.mailbox.model.SearchQuery.UidCriterion;
+import org.apache.james.mailbox.model.SearchQuery.UidRange;
+import org.apache.james.mailbox.model.UpdatedFlags;
+import org.apache.james.mailbox.store.mail.MessageMapperFactory;
+import org.apache.james.mailbox.store.mail.model.Mailbox;
+import org.apache.james.mailbox.store.mail.model.MailboxMessage;
+import org.apache.james.mailbox.store.mail.model.impl.PropertyBuilder;
+import org.apache.james.mailbox.store.search.ListeningMessageSearchIndex;
+import org.apache.james.mailbox.store.search.SearchUtil;
+import org.apache.james.mime4j.MimeException;
+import org.apache.james.mime4j.dom.Header;
+import org.apache.james.mime4j.dom.address.Address;
+import org.apache.james.mime4j.dom.address.AddressList;
+import org.apache.james.mime4j.dom.address.Group;
+import org.apache.james.mime4j.dom.address.MailboxList;
+import org.apache.james.mime4j.dom.datetime.DateTime;
+import org.apache.james.mime4j.dom.field.DateTimeField;
+import org.apache.james.mime4j.field.address.AddressFormatter;
+import org.apache.james.mime4j.field.address.LenientAddressParser;
+import org.apache.james.mime4j.field.datetime.parser.DateTimeParser;
+import org.apache.james.mime4j.message.SimpleContentHandler;
+import org.apache.james.mime4j.parser.MimeStreamParser;
+import org.apache.james.mime4j.stream.BodyDescriptor;
+import org.apache.james.mime4j.stream.MimeConfig;
+import org.apache.james.mime4j.util.MimeUtil;
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.document.DateTools;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.Field;
+import org.apache.lucene.document.Field.Index;
+import org.apache.lucene.document.Field.Store;
+import org.apache.lucene.document.NumericField;
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.index.IndexWriterConfig.OpenMode;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.BooleanClause;
+import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.NumericRangeQuery;
+import org.apache.lucene.search.PrefixQuery;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.ScoreDoc;
+import org.apache.lucene.search.Sort;
+import org.apache.lucene.search.SortField;
+import org.apache.lucene.search.TermQuery;
+import org.apache.lucene.search.TermRangeQuery;
+import org.apache.lucene.search.TopDocs;
+import org.apache.lucene.search.WildcardQuery;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.util.Version;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.github.steveash.guavate.Guavate;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+/**
+ * Lucene based {@link ListeningMessageSearchIndex} which offers message searching via a Lucene index
+ * 
+ * 
+
+ * @param 
+ */
+public class LuceneMessageSearchIndex extends ListeningMessageSearchIndex {
+    private static final Logger LOGGER = LoggerFactory.getLogger(LuceneMessageSearchIndex.class);
+    private static final Date MAX_DATE;
+    private static final Date MIN_DATE;
+    
+    static {
+        Calendar cal = Calendar.getInstance();
+        cal.set(9999, 11, 31);
+        MAX_DATE = cal.getTime();
+        
+        cal.set(0000, 0, 1);
+        MIN_DATE = cal.getTime();
+    }
+    
+    /**
+     * Default max query results
+     */
+    private static final int DEFAULT_MAX_QUERY_RESULTS = 100000;
+    
+    /**
+     * {@link Field} which will contain the unique index of the {@link Document}
+     */
+    private static final String ID_FIELD = "id";
+    
+    
+    /**
+     * {@link Field} which will contain uid of the {@link MailboxMessage}
+     */
+    private static final String UID_FIELD = "uid";
+    
+    /**
+     * {@link Field} boolean field that say if the message as an attachment or not
+     */
+    private static final String HAS_ATTACHMENT_FIELD = "hasAttachment";
+
+    /**
+     * {@link Field} which will contain the {@link Flags} of the {@link MailboxMessage}
+     */
+    private static final String FLAGS_FIELD = "flags";
+  
+    /**
+     * {@link Field} which will contain the size of the {@link MailboxMessage}
+     */
+    private static final String SIZE_FIELD = "size";
+
+    /**
+     * {@link Field} which will contain the body of the {@link MailboxMessage}
+     */
+    private static final String BODY_FIELD = "body";
+    
+    
+    /**
+     * Prefix which will be used for each message header to store it also in a seperate {@link Field}
+     */
+    private static final String PREFIX_HEADER_FIELD = "header_";
+    
+    /**
+     * {@link Field} which will contain the whole message header of the {@link MailboxMessage}
+     */
+    private static final String HEADERS_FIELD = "headers";
+
+    /**
+     * {@link Field} which will contain the mod-sequence of the message
+     */
+    private static final String MODSEQ_FIELD = "modSeq";
+
+    /**
+     * {@link Field} which will contain the TO-Address of the message
+     */
+    private static final String TO_FIELD = "to";
+    
+    private static final String FIRST_TO_MAILBOX_NAME_FIELD = "firstToMailboxName";
+    private static final String FIRST_TO_MAILBOX_DISPLAY_FIELD = "firstToMailboxDisplay";
+
+    /**
+     * {@link Field} which will contain the CC-Address of the message
+     */
+    private static final String CC_FIELD = "cc";
+
+    private static final String FIRST_CC_MAILBOX_NAME_FIELD = "firstCcMailboxName";
+    
+
+    /**
+     * {@link Field} which will contain the FROM-Address of the message
+     */
+    private static final String FROM_FIELD = "from";
+    
+    private static final String FIRST_FROM_MAILBOX_NAME_FIELD = "firstFromMailboxName";
+    private static final String FIRST_FROM_MAILBOX_DISPLAY_FIELD = "firstFromMailboxDisplay";
+
+    /**
+     * {@link Field} which will contain the BCC-Address of the message
+     */
+    private static final String BCC_FIELD = "bcc";
+    
+    
+    private static final String BASE_SUBJECT_FIELD = "baseSubject";
+    
+    /**
+     * {@link Field} which contain the internalDate of the message with YEAR-Resolution
+     */
+    private static final String INTERNAL_DATE_FIELD_YEAR_RESOLUTION = "internaldateYearResolution";
+    
+    
+    /**
+     * {@link Field} which contain the internalDate of the message with MONTH-Resolution
+     */
+    private static final String INTERNAL_DATE_FIELD_MONTH_RESOLUTION = "internaldateMonthResolution";
+    
+    /**
+     * {@link Field} which contain the internalDate of the message with DAY-Resolution
+     */
+    private static final String INTERNAL_DATE_FIELD_DAY_RESOLUTION = "internaldateDayResolution";
+    
+    /**
+     * {@link Field} which contain the internalDate of the message with HOUR-Resolution
+     */
+    private static final String INTERNAL_DATE_FIELD_HOUR_RESOLUTION = "internaldateHourResolution";
+    
+    /**
+     * {@link Field} which contain the internalDate of the message with MINUTE-Resolution
+     */
+    private static final String INTERNAL_DATE_FIELD_MINUTE_RESOLUTION = "internaldateMinuteResolution";
+    
+    /**
+     * {@link Field} which contain the internalDate of the message with SECOND-Resolution
+     */
+    private static final String INTERNAL_DATE_FIELD_SECOND_RESOLUTION = "internaldateSecondResolution";
+    
+    
+    /**
+     * {@link Field} which contain the internalDate of the message with MILLISECOND-Resolution
+     */
+    private static final String INTERNAL_DATE_FIELD_MILLISECOND_RESOLUTION = "internaldateMillisecondResolution";
+
+    /**
+     * {@link Field} which will contain the id of the {@link Mailbox}
+     */
+    private static final String MAILBOX_ID_FIELD = "mailboxid";
+
+    /**
+     * {@link Field} which will contain the user of the {@link MailboxSession}
+     */
+    private static final String USERS = "userSession";
+    /**
+     * {@link Field} which will contain the id of the {@link MessageId}
+     */
+    private static final String MESSAGE_ID_FIELD = "messageid";
+
+    /**
+     * {@link Field} which contain the Date header of the message with YEAR-Resolution
+     */
+    private static final String SENT_DATE_FIELD_YEAR_RESOLUTION = "sentdateYearResolution";
+    
+    
+    /**
+     * {@link Field} which contain the Date header of the message with MONTH-Resolution
+     */
+    private static final String SENT_DATE_FIELD_MONTH_RESOLUTION = "sentdateMonthResolution";
+    
+    /**
+     * {@link Field} which contain the Date header of the message with DAY-Resolution
+     */
+    private static final String SENT_DATE_FIELD_DAY_RESOLUTION = "sentdateDayResolution";
+    
+    /**
+     * {@link Field} which contain the Date header of the message with HOUR-Resolution
+     */
+    private static final String SENT_DATE_FIELD_HOUR_RESOLUTION = "sentdateHourResolution";
+    
+    /**
+     * {@link Field} which contain the Date header of the message with MINUTE-Resolution
+     */
+    private static final String SENT_DATE_FIELD_MINUTE_RESOLUTION = "sentdateMinuteResolution";
+    
+    /**
+     * {@link Field} which contain the Date header of the message with SECOND-Resolution
+     */
+    private static final String SENT_DATE_FIELD_SECOND_RESOLUTION = "sentdateSecondResolution";
+    
+    
+    /**
+     * {@link Field} which contain the Date header of the message with MILLISECOND-Resolution
+     */
+    private static final String SENT_DATE_FIELD_MILLISECOND_RESOLUTION = "sentdateMillisecondResolution";
+
+    private static final String SENT_DATE_SORT_FIELD_MILLISECOND_RESOLUTION = "sentdateSort";
+
+    private static final String MEDIA_TYPE_TEXT = "text";
+    private static final String MEDIA_TYPE_MESSAGE = "message";
+    private static final String DEFAULT_ENCODING = "US-ASCII";
+    
+    private static final SortField UID_SORT = new SortField(UID_FIELD, SortField.LONG);
+    private static final SortField UID_SORT_REVERSE = new SortField(UID_FIELD, SortField.LONG, true);
+
+    private static final SortField SIZE_SORT = new SortField(SIZE_FIELD, SortField.LONG);
+    private static final SortField SIZE_SORT_REVERSE = new SortField(SIZE_FIELD, SortField.LONG, true);
+
+    private static final SortField FIRST_CC_MAILBOX_SORT = new SortField(FIRST_CC_MAILBOX_NAME_FIELD, SortField.STRING);
+    private static final SortField FIRST_CC_MAILBOX_SORT_REVERSE = new SortField(FIRST_CC_MAILBOX_NAME_FIELD, SortField.STRING, true);
+
+    private static final SortField FIRST_TO_MAILBOX_SORT = new SortField(FIRST_TO_MAILBOX_NAME_FIELD, SortField.STRING);
+    private static final SortField FIRST_TO_MAILBOX_SORT_REVERSE = new SortField(FIRST_TO_MAILBOX_NAME_FIELD, SortField.STRING, true);
+
+    private static final SortField FIRST_FROM_MAILBOX_SORT = new SortField(FIRST_FROM_MAILBOX_NAME_FIELD, SortField.STRING);
+    private static final SortField FIRST_FROM_MAILBOX_SORT_REVERSE = new SortField(FIRST_FROM_MAILBOX_NAME_FIELD, SortField.STRING, true);
+
+    
+    private static final SortField ARRIVAL_MAILBOX_SORT = new SortField(INTERNAL_DATE_FIELD_MILLISECOND_RESOLUTION, SortField.LONG);
+    private static final SortField ARRIVAL_MAILBOX_SORT_REVERSE = new SortField(INTERNAL_DATE_FIELD_MILLISECOND_RESOLUTION, SortField.LONG, true);
+
+    private static final SortField BASE_SUBJECT_SORT = new SortField(BASE_SUBJECT_FIELD, SortField.STRING);
+    private static final SortField BASE_SUBJECT_SORT_REVERSE = new SortField(BASE_SUBJECT_FIELD, SortField.STRING, true);
+    
+    private static final SortField SENT_DATE_SORT = new SortField(SENT_DATE_SORT_FIELD_MILLISECOND_RESOLUTION, SortField.LONG);
+    private static final SortField SENT_DATE_SORT_REVERSE = new SortField(SENT_DATE_SORT_FIELD_MILLISECOND_RESOLUTION, SortField.LONG, true);
+    
+    private static final SortField FIRST_TO_MAILBOX_DISPLAY_SORT = new SortField(FIRST_TO_MAILBOX_DISPLAY_FIELD, SortField.STRING);
+    private static final SortField FIRST_TO_MAILBOX_DISPLAY_SORT_REVERSE = new SortField(FIRST_TO_MAILBOX_DISPLAY_FIELD, SortField.STRING, true);
+
+    private static final SortField FIRST_FROM_MAILBOX_DISPLAY_SORT = new SortField(FIRST_FROM_MAILBOX_DISPLAY_FIELD, SortField.STRING);
+    private static final SortField FIRST_FROM_MAILBOX_DISPLAY_SORT_REVERSE = new SortField(FIRST_FROM_MAILBOX_DISPLAY_FIELD, SortField.STRING, true);
+    
+    private final MailboxId.Factory mailboxIdFactory;
+    private final MessageId.Factory messageIdFactory;
+    private final IndexWriter writer;
+
+    private int maxQueryResults = DEFAULT_MAX_QUERY_RESULTS;
+
+    private boolean suffixMatch = false;
+
+    @Inject
+    public LuceneMessageSearchIndex(
+        MessageMapperFactory factory,
+        MailboxId.Factory mailboxIdFactory,
+        Directory directory,
+        MessageId.Factory messageIdFactory
+    ) throws IOException {
+        this(factory, mailboxIdFactory, directory, false, true, messageIdFactory);
+    }
+
+    public LuceneMessageSearchIndex(
+            MessageMapperFactory factory,
+            MailboxId.Factory mailboxIdFactory,
+            Directory directory,
+            boolean dropIndexOnStart,
+            boolean lenient,
+            MessageId.Factory messageIdFactory
+    ) throws IOException {
+        super(factory);
+        this.mailboxIdFactory = mailboxIdFactory;
+        this.messageIdFactory = messageIdFactory;
+        this.writer = new IndexWriter(directory,  createConfig(createAnalyzer(lenient), dropIndexOnStart));
+    }
+    
+    
+    public LuceneMessageSearchIndex(MessageMapperFactory factory, MailboxId.Factory mailboxIdFactory, MessageId.Factory messageIdFactory, IndexWriter writer) {
+        super(factory);
+        this.mailboxIdFactory = mailboxIdFactory;
+        this.messageIdFactory = messageIdFactory;
+        this.writer = writer;
+    }
+
+    @Override
+    public ListenerType getType() {
+        return ListenerType.EACH_NODE;
+    }
+
+
+    @Override
+    public EnumSet<SearchCapabilities> getSupportedCapabilities(EnumSet<MailboxManager.MessageCapabilities> messageCapabilities) {
+        return EnumSet.of(SearchCapabilities.MultimailboxSearch);
+
+    }
+    
+    /**
+     * Set the max count of results which will get returned from a query. The default is {@link #DEFAULT_MAX_QUERY_RESULTS}
+     * 
+     * @param maxQueryResults
+     */
+    public void setMaxQueryResults(int maxQueryResults) {
+        this.maxQueryResults = maxQueryResults;
+    }
+    
+    protected IndexWriterConfig createConfig(Analyzer analyzer, boolean dropIndexOnStart) {
+        IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_31, analyzer);
+        if (dropIndexOnStart) {
+            config.setOpenMode(OpenMode.CREATE);
+        } else {
+            config.setOpenMode(OpenMode.CREATE_OR_APPEND);
+        }
+        return config;
+    }
+    
+    /**
+     * Create a {@link Analyzer} which is used to index the {@link MailboxMessage}'s
+     * 
+     * @param lenient 
+     * 
+     * @return analyzer
+     */
+    protected Analyzer createAnalyzer(boolean lenient) {
+        if (lenient) {
+           return new LenientImapSearchAnalyzer();
+        } else {
+            return new StrictImapSearchAnalyzer();
+        }
+    }
+    
+    /**
+     * If set to true this implementation will use {@link WildcardQuery} to match suffix and prefix. This is what RFC3501 expects but is often not what the user does.
+     * It also slow things a lot if you have complex queries which use many "TEXT" arguments. If you want the implementation to behave strict like RFC3501 says, you should
+     * set this to true. 
+     * 
+     * The default is false for performance reasons
+     * 
+     * 
+     * @param suffixMatch
+     */
+    public void setEnableSuffixMatch(boolean suffixMatch) {
+        this.suffixMatch = suffixMatch;
+    }
+    
+    
+    
+    @Override
+    public Iterator<MessageUid> search(MailboxSession session, Mailbox mailbox, SearchQuery searchQuery) throws MailboxException {
+        Preconditions.checkArgument(session != null, "'session' is mandatory");
+
+        return searchMultimap(ImmutableList.of(mailbox.getMailboxId()), searchQuery)
+            .stream()
+            .map(SearchResult::getMessageUid)
+            .iterator();
+    }
+
+    @Override
+    public List<MessageId> search(MailboxSession session, Collection<MailboxId> mailboxIds, SearchQuery searchQuery, long limit) throws MailboxException {
+        Preconditions.checkArgument(session != null, "'session' is mandatory");
+        if (mailboxIds.isEmpty()) {
+            return ImmutableList.of();
+        }
+
+        return searchMultimap(mailboxIds, searchQuery)
+            .stream()
+            .map(searchResult -> searchResult.getMessageId().get())
+            .filter(SearchUtil.distinct())
+            .limit(Long.valueOf(limit).intValue())
+            .collect(Guavate.toImmutableList());
+    }
+    
+    private List<SearchResult> searchMultimap(Collection<MailboxId> mailboxIds, SearchQuery searchQuery) throws MailboxException {
+        ImmutableList.Builder<SearchResult> results = ImmutableList.builder();
+
+        Query inMailboxes = buildQueryFromMailboxes(mailboxIds);
+        
+        try (IndexSearcher searcher = new IndexSearcher(IndexReader.open(writer, true))) {
+            BooleanQuery query = new BooleanQuery();
+            query.add(inMailboxes, BooleanClause.Occur.MUST);
+            // Not return flags documents
+            query.add(new PrefixQuery(new Term(FLAGS_FIELD, "")), BooleanClause.Occur.MUST_NOT);
+
+            List<Criterion> crits = searchQuery.getCriterias();
+            for (Criterion crit : crits) {
+                query.add(createQuery(crit, inMailboxes, searchQuery.getRecentMessageUids()), BooleanClause.Occur.MUST);
+            }
+
+            // query for all the documents sorted as specified in the SearchQuery
+            TopDocs docs = searcher.search(query, null, maxQueryResults, createSort(searchQuery.getSorts()));
+            ScoreDoc[] sDocs = docs.scoreDocs;
+            for (ScoreDoc sDoc : sDocs) {
+                Document doc = searcher.doc(sDoc.doc);
+                MessageUid uid = MessageUid.of(Long.valueOf(doc.get(UID_FIELD)));
+                MailboxId mailboxId = mailboxIdFactory.fromString(doc.get(MAILBOX_ID_FIELD));
+                Optional<MessageId> messageId = toMessageId(Optional.ofNullable(doc.get(MESSAGE_ID_FIELD)));
+                results.add(new SearchResult(messageId, mailboxId, uid));
+            }
+        } catch (IOException e) {
+            throw new MailboxException("Unable to search the mailbox", e);
+        }
+        return results.build();
+    }
+
+    private Optional<MessageId> toMessageId(Optional<String> messageIdField) {
+        if (messageIdField.isPresent()) {
+            return Optional.of(messageIdFactory.fromString(messageIdField.get()));
+        }
+        return Optional.empty();
+    }
+
+    private Query buildQueryFromMailboxes(Collection<MailboxId> mailboxIds) {
+        BooleanQuery query = new BooleanQuery();
+        for (MailboxId id: mailboxIds) {
+            String idAsString = id.serialize();
+            query.add(new TermQuery(new Term(MAILBOX_ID_FIELD, idAsString)), BooleanClause.Occur.SHOULD);
+        }
+        return query;
+    }
+
+
+    /**
+     * Create a new {@link Document} for the given {@link MailboxMessage}. This Document does not contain any flags data. The {@link Flags} are stored in a seperate Document.
+     * 
+     * See {@link #createFlagsDocument(MailboxMessage)}
+     * 
+     * @param membership
+     * @return document
+     */
+    private Document createMessageDocument(final MailboxSession session, final MailboxMessage membership) throws MailboxException {
+        final Document doc = new Document();
+        // TODO: Better handling
+        doc.add(new Field(USERS, session.getUser().getUserName().toUpperCase(Locale.US), Store.YES, Index.NOT_ANALYZED));
+        doc.add(new Field(MAILBOX_ID_FIELD, membership.getMailboxId().serialize().toUpperCase(Locale.US), Store.YES, Index.NOT_ANALYZED));
+        doc.add(new NumericField(UID_FIELD,Store.YES, true).setLongVal

<TRUNCATED>

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


[09/20] james-project git commit: JAMES-2517 Use try-with-resource in more places

Posted by bt...@apache.org.
JAMES-2517 Use try-with-resource in more places


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

Branch: refs/heads/master
Commit: 3c275fe650fcd6b0ecb9840231a634d75966d58a
Parents: a58e7dd
Author: Benoit Tellier <bt...@linagora.com>
Authored: Fri Aug 3 11:00:29 2018 +0700
Committer: Benoit Tellier <bt...@linagora.com>
Committed: Fri Aug 3 15:51:21 2018 +0700

----------------------------------------------------------------------
 .../hbase/HBaseMailboxSessionMapperFactory.java |    7 +-
 .../mailbox/hbase/io/ChunkInputStream.java      |    9 +-
 .../mailbox/hbase/io/ChunkOutputStream.java     |    8 +-
 .../mailbox/hbase/mail/HBaseMailboxMapper.java  |  212 +-
 .../mailbox/hbase/mail/HBaseMessageMapper.java  |   75 +-
 .../mailbox/hbase/mail/HBaseUidProvider.java    |   24 +-
 .../org/apache/james/mailbox/jcr/JCRUtils.java  |    8 +-
 .../lucene/search/LuceneMessageSearchIndex.java | 2732 +++++++++---------
 .../maildir/user/MaildirSubscriptionMapper.java |   29 +-
 .../base/AutomaticallySentMailDetectorImpl.java |   13 +-
 .../james/transport/mailets/LogMessage.java     |    5 +-
 .../james/mpt/ant/MailProtocolTestTask.java     |   20 +-
 .../org/apache/james/server/core/MailImpl.java  |   13 +-
 .../apache/james/system/hbase/TablePool.java    |    5 +-
 .../mailets/JDBCRecipientRewriteTable.java      |   32 +-
 .../apache/james/queue/jms/JMSMailQueue.java    |   97 +-
 16 files changed, 1537 insertions(+), 1752 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/3c275fe6/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/HBaseMailboxSessionMapperFactory.java
----------------------------------------------------------------------
diff --git a/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/HBaseMailboxSessionMapperFactory.java b/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/HBaseMailboxSessionMapperFactory.java
index db441ca..1c840af 100644
--- a/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/HBaseMailboxSessionMapperFactory.java
+++ b/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/HBaseMailboxSessionMapperFactory.java
@@ -36,7 +36,6 @@ import org.apache.hadoop.hbase.HTableDescriptor;
 import org.apache.hadoop.hbase.MasterNotRunningException;
 import org.apache.hadoop.hbase.ZooKeeperConnectionException;
 import org.apache.hadoop.hbase.client.HBaseAdmin;
-import org.apache.hadoop.io.IOUtils;
 import org.apache.james.mailbox.MailboxSession;
 import org.apache.james.mailbox.exception.MailboxException;
 import org.apache.james.mailbox.exception.SubscriptionException;
@@ -82,9 +81,7 @@ public class HBaseMailboxSessionMapperFactory extends MailboxSessionMapperFactor
         this.messageIdFactory = messageIdFactory;
 
         //TODO: add better exception handling for this
-        HBaseAdmin hbaseAdmin = null;
-        try {
-            hbaseAdmin = new HBaseAdmin(conf);
+        try (HBaseAdmin hbaseAdmin = new HBaseAdmin(conf)) {
             HTableDescriptor desc = null;
             HColumnDescriptor hColumnDescriptor = null;
 
@@ -127,8 +124,6 @@ public class HBaseMailboxSessionMapperFactory extends MailboxSessionMapperFactor
 
         } catch (Exception e) {
             throw new RuntimeException(e);
-        } finally {
-            IOUtils.cleanup(null, hbaseAdmin);
         }
     }
 

http://git-wip-us.apache.org/repos/asf/james-project/blob/3c275fe6/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/io/ChunkInputStream.java
----------------------------------------------------------------------
diff --git a/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/io/ChunkInputStream.java b/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/io/ChunkInputStream.java
index 277a0e5..76a5009 100644
--- a/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/io/ChunkInputStream.java
+++ b/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/io/ChunkInputStream.java
@@ -74,10 +74,8 @@ public class ChunkInputStream extends InputStream {
      * @throws IOException
      */
     private boolean fetchChunk() throws IOException {
-        HTable messages = null;
-        try {
+        try (HTable messages = new HTable(conf, tableName)) {
             byte[] cp = Bytes.toBytes(chunkPos);
-            messages = new HTable(conf, tableName);
             Get get = new Get(key);
             get.addColumn(cf, cp);
             get.setMaxVersions(1);
@@ -92,11 +90,6 @@ public class ChunkInputStream extends InputStream {
             }
         } catch (IOException e) {
             throw new IOException("Unable to read data", e);
-        } finally {
-            if (messages != null) {
-                messages.close();
-
-            }
         }
     }
 

http://git-wip-us.apache.org/repos/asf/james-project/blob/3c275fe6/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/io/ChunkOutputStream.java
----------------------------------------------------------------------
diff --git a/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/io/ChunkOutputStream.java b/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/io/ChunkOutputStream.java
index f66fa5b..4b5eae1 100644
--- a/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/io/ChunkOutputStream.java
+++ b/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/io/ChunkOutputStream.java
@@ -93,9 +93,7 @@ public class ChunkOutputStream extends OutputStream {
      */
     private void writeData(boolean close) throws IOException {
         if (pos != 0 && (close || pos == chunk.length - 1)) {
-            HTable messages = null;
-            try {
-                messages = new HTable(conf, tableName);
+            try (HTable messages = new HTable(conf, tableName)) {
                 Put put = new Put(key);
                 put.add(cf, Bytes.toBytes(chunkPos), Bytes.head(chunk, (int) pos + 1));
                 messages.put(put);
@@ -104,10 +102,6 @@ public class ChunkOutputStream extends OutputStream {
 
             } catch (IOException e) {
                 throw new IOException("Unable to write data", e);
-            } finally {
-                if (messages != null) {
-                    messages.close();
-                }
             }
         }
     }

http://git-wip-us.apache.org/repos/asf/james-project/blob/3c275fe6/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/mail/HBaseMailboxMapper.java
----------------------------------------------------------------------
diff --git a/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/mail/HBaseMailboxMapper.java b/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/mail/HBaseMailboxMapper.java
index b5926e4..847d682 100644
--- a/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/mail/HBaseMailboxMapper.java
+++ b/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/mail/HBaseMailboxMapper.java
@@ -81,11 +81,9 @@ public class HBaseMailboxMapper extends HBaseNonTransactionalMapper implements M
     
     @Override
     public Mailbox findMailboxByPath(MailboxPath mailboxPath) throws MailboxException, MailboxNotFoundException {
-        HTable mailboxes = null;
-        ResultScanner scanner = null;
-        try {
-            mailboxes = new HTable(conf, MAILBOXES_TABLE);
-            
+
+        try (HTable mailboxes = new HTable(conf, MAILBOXES_TABLE)) {
+
             Scan scan = new Scan();
             scan.addFamily(MAILBOX_CF);
             scan.setCaching(mailboxes.getConfiguration().getInt("hbase.client.scanner.caching", 1) * 2);
@@ -107,35 +105,24 @@ public class HBaseMailboxMapper extends HBaseNonTransactionalMapper implements M
             filters.addFilter(nameFilter);
             SingleColumnValueFilter namespaceFilter = new SingleColumnValueFilter(MAILBOX_CF, MAILBOX_NAMESPACE, CompareOp.EQUAL, Bytes.toBytes(mailboxPath.getNamespace()));
             filters.addFilter(namespaceFilter);
-            
             scan.setFilter(filters);
-            scanner = mailboxes.getScanner(scan);
-            Result result = scanner.next();
-            
-            if (result == null) {
-                throw new MailboxNotFoundException(mailboxPath);
+
+            try (ResultScanner scanner = mailboxes.getScanner(scan)) {
+                Result result = scanner.next();
+                if (result == null) {
+                    throw new MailboxNotFoundException(mailboxPath);
+                }
+                return mailboxFromResult(result);
             }
-            return mailboxFromResult(result);
         } catch (IOException e) {
             throw new MailboxException("Search of mailbox " + mailboxPath + " failed", e);
-        } finally {
-            scanner.close();
-            if (mailboxes != null) {
-                try {
-                    mailboxes.close();
-                } catch (IOException ex) {
-                    throw new MailboxException("Error closing table " + mailboxes, ex);
-                }
-            }
         }
     }
 
     @Override
     public Mailbox findMailboxById(MailboxId id) throws MailboxException, MailboxNotFoundException {
         HBaseId mailboxId = (HBaseId)id;
-        HTable mailboxes = null;
-        try {
-            mailboxes = new HTable(conf, MAILBOXES_TABLE);
+        try (HTable mailboxes = new HTable(conf, MAILBOXES_TABLE)) {
             Get get = new Get(mailboxId.toBytes());
             Result result = mailboxes.get(get);
             if (result == null) {
@@ -144,24 +131,12 @@ public class HBaseMailboxMapper extends HBaseNonTransactionalMapper implements M
             return mailboxFromResult(result);
         } catch (IOException ex) {
             throw new MailboxException("IOException in HBase cluster during get()", ex);
-        } finally {
-            if (mailboxes != null) {
-                try {
-                    mailboxes.close();
-                } catch (IOException ex) {
-                    throw new MailboxException("Error closing table " + mailboxes, ex);
-                }
-            }
         }
     }
     
     @Override
     public List<Mailbox> findMailboxWithPathLike(MailboxPath mailboxPath) throws MailboxException {
-        HTable mailboxes = null;
-        ResultScanner scanner = null;
-        try {
-            mailboxes = new HTable(conf, MAILBOXES_TABLE);
-            
+        try (HTable mailboxes = new HTable(conf, MAILBOXES_TABLE)) {
             Scan scan = new Scan();
             scan.addFamily(MAILBOX_CF);
             scan.setCaching(mailboxes.getConfiguration().getInt("hbase.client.scanner.caching", 1) * 2);
@@ -195,59 +170,38 @@ public class HBaseMailboxMapper extends HBaseNonTransactionalMapper implements M
             filters.addFilter(namespaceFilter);
             
             scan.setFilter(filters);
-            scanner = mailboxes.getScanner(scan);
-            
-            List<Mailbox> mailboxList = new ArrayList<>();
-            
-            for (Result result : scanner) {
-                mailboxList.add(mailboxFromResult(result));
+            try (ResultScanner scanner = mailboxes.getScanner(scan)) {
+                List<Mailbox> mailboxList = new ArrayList<>();
+                for (Result result : scanner) {
+                    mailboxList.add(mailboxFromResult(result));
+                }
+                return mailboxList;
             }
-            return mailboxList;
         } catch (IOException e) {
             throw new MailboxException("Search of mailbox " + mailboxPath + " failed", e);
-        } finally {
-            scanner.close();
-            if (mailboxes != null) {
-                try {
-                    mailboxes.close();
-                } catch (IOException ex) {
-                    throw new MailboxException("Error closing table " + mailboxes, ex);
-                }
-            }
         }
     }
     
     @Override
     public List<Mailbox> list() throws MailboxException {
-        HTable mailboxes = null;
-        ResultScanner scanner = null;
         //TODO: possible performance isssues, we are creating an object from all the rows in HBase mailbox table
-        try {
-            mailboxes = new HTable(conf, MAILBOXES_TABLE);
+        try (HTable mailboxes = new HTable(conf, MAILBOXES_TABLE)) {
             Scan scan = new Scan();
             scan.addFamily(MAILBOX_CF);
             scan.setCaching(mailboxes.getConfiguration().getInt("hbase.client.scanner.caching", 1) * 2);
             scan.setMaxVersions(1);
-            scanner = mailboxes.getScanner(scan);
-            List<Mailbox> mailboxList = new ArrayList<>();
-            
-            Result result;
-            while ((result = scanner.next()) != null) {
-                Mailbox mlbx = mailboxFromResult(result);
-                mailboxList.add(mlbx);
+
+            try (ResultScanner scanner = mailboxes.getScanner(scan)) {
+                List<Mailbox> mailboxList = new ArrayList<>();
+                Result result;
+                while ((result = scanner.next()) != null) {
+                    Mailbox mlbx = mailboxFromResult(result);
+                    mailboxList.add(mlbx);
+                }
+                return mailboxList;
             }
-            return mailboxList;
         } catch (IOException ex) {
             throw new MailboxException("HBase IOException in list()", ex);
-        } finally {
-            scanner.close();
-            if (mailboxes != null) {
-                try {
-                    mailboxes.close();
-                } catch (IOException ex) {
-                    throw new MailboxException("Error closing table " + mailboxes, ex);
-                }
-            }
         }
     }
     
@@ -258,9 +212,7 @@ public class HBaseMailboxMapper extends HBaseNonTransactionalMapper implements M
     @Override
     public MailboxId save(Mailbox mlbx) throws MailboxException {
         //TODO: maybe switch to checkAndPut for transactions
-        HTable mailboxes = null;
-        try {
-            mailboxes = new HTable(conf, MAILBOXES_TABLE);
+        try (HTable mailboxes = new HTable(conf, MAILBOXES_TABLE)) {
             /*
              * cast to HBaseMailbox to access lastuid and ModSeq
              */
@@ -269,47 +221,25 @@ public class HBaseMailboxMapper extends HBaseNonTransactionalMapper implements M
             return mlbx.getMailboxId();
         } catch (IOException ex) {
             throw new MailboxException("IOExeption", ex);
-        } finally {
-            if (mailboxes != null) {
-                try {
-                    mailboxes.close();
-                } catch (IOException ex) {
-                    throw new MailboxException("Error closing table " + mailboxes, ex);
-                }
-            }
         }
     }
     
     @Override
     public void delete(Mailbox mlbx) throws MailboxException {
         //TODO: maybe switch to checkAndDelete
-        HTable mailboxes = null;
         HBaseId mailboxId = (HBaseId) mlbx.getMailboxId();
-        try {
-            mailboxes = new HTable(conf, MAILBOXES_TABLE);
+        try (HTable mailboxes = new HTable(conf, MAILBOXES_TABLE)) {
             //TODO: delete all maessages from this mailbox
             Delete delete = new Delete(mailboxId.toBytes());
             mailboxes.delete(delete);
         } catch (IOException ex) {
             throw new MailboxException("IOException in HBase cluster during delete()", ex);
-        } finally {
-            if (mailboxes != null) {
-                try {
-                    mailboxes.close();
-                } catch (IOException ex) {
-                    throw new MailboxException("Error closing table " + mailboxes, ex);
-                }
-            }
         }
     }
     
     @Override
     public boolean hasChildren(Mailbox mailbox, char c) throws MailboxException, MailboxNotFoundException {
-        HTable mailboxes = null;
-        ResultScanner scanner = null;
-        try {
-            mailboxes = new HTable(conf, MAILBOXES_TABLE);
-            
+        try (HTable mailboxes = new HTable(conf, MAILBOXES_TABLE)) {
             Scan scan = new Scan();
             scan.addFamily(MAILBOX_CF);
             scan.setCaching(mailboxes.getConfiguration().getInt("hbase.client.scanner.caching", 1) * 2);
@@ -330,8 +260,7 @@ public class HBaseMailboxMapper extends HBaseNonTransactionalMapper implements M
             filters.addFilter(namespaceFilter);
             
             scan.setFilter(filters);
-            scanner = mailboxes.getScanner(scan);
-            try {
+            try (ResultScanner scanner = mailboxes.getScanner(scan)) {
                 if (scanner.next() != null) {
                     return true;
                 }
@@ -341,57 +270,46 @@ public class HBaseMailboxMapper extends HBaseNonTransactionalMapper implements M
             return false;
         } catch (IOException e) {
             throw new MailboxException("Search of mailbox " + mailbox + " failed", e);
-        } finally {
-            scanner.close();
-            if (mailboxes != null) {
-                try {
-                    mailboxes.close();
-                } catch (IOException ex) {
-                    throw new MailboxException("Error closing table " + mailboxes, ex);
-                }
-            }
         }
     }
     
     public void deleteAllMemberships() {
-        HTable messages = null;
-        HTable mailboxes = null;
-        ResultScanner scanner = null;
-        try {
-            messages = new HTable(conf, MESSAGES_TABLE);
-            mailboxes = new HTable(conf, MAILBOXES_TABLE);
-            Scan scan = new Scan();
-            scan.setMaxVersions(1);
-            scan.addColumn(MESSAGES_META_CF, MESSAGE_INTERNALDATE);
-            scanner = messages.getScanner(scan);
-            Result result;
-            List<Delete> deletes = new ArrayList<>();
-            while ((result = scanner.next()) != null) {
-                deletes.add(new Delete(result.getRow()));
-            }
-            long totalDeletes = deletes.size();
-            messages.delete(deletes);
-            if (deletes.size() > 0) {
-                //TODO: what shoul we do if not all messages are deleted?
-                System.out.println("Just " + deletes.size() + " out of " + totalDeletes + " messages have been deleted");
-                //throw new RuntimeException("Just " + deletes.size() + " out of " + totalDeletes + " messages have been deleted");
-            }
-            List<Put> puts = new ArrayList<>();
-            scan = new Scan();
-            scan.setMaxVersions(1);
-            scan.addColumn(MAILBOX_CF, MAILBOX_MESSAGE_COUNT);
-            IOUtils.cleanup(null, scanner);
-            scanner = mailboxes.getScanner(scan);
-            Put put = null;
-            while ((result = scanner.next()) != null) {
-                put = new Put(result.getRow());
-                put.add(MAILBOX_CF, MAILBOX_MESSAGE_COUNT, Bytes.toBytes(0L));
-                puts.add(new Put());
+        try (HTable messages = new HTable(conf, MESSAGES_TABLE)) {
+            try (HTable mailboxes = new HTable(conf, MAILBOXES_TABLE)) {
+                Scan scan = new Scan();
+                scan.setMaxVersions(1);
+                scan.addColumn(MESSAGES_META_CF, MESSAGE_INTERNALDATE);
+                try (ResultScanner scanner = messages.getScanner(scan)) {
+                    Result result;
+                    List<Delete> deletes = new ArrayList<>();
+                    while ((result = scanner.next()) != null) {
+                        deletes.add(new Delete(result.getRow()));
+                    }
+                    long totalDeletes = deletes.size();
+                    messages.delete(deletes);
+                    if (deletes.size() > 0) {
+                        //TODO: what shoul we do if not all messages are deleted?
+                        System.out.println("Just " + deletes.size() + " out of " + totalDeletes + " messages have been deleted");
+                        //throw new RuntimeException("Just " + deletes.size() + " out of " + totalDeletes + " messages have been deleted");
+                    }
+                }
+
+                List<Put> puts = new ArrayList<>();
+                scan = new Scan();
+                scan.setMaxVersions(1);
+                scan.addColumn(MAILBOX_CF, MAILBOX_MESSAGE_COUNT);
+                try (ResultScanner scanner = mailboxes.getScanner(scan)) {
+                    Put put = null;
+                    Result result;
+                    while ((result = scanner.next()) != null) {
+                        put = new Put(result.getRow());
+                        put.add(MAILBOX_CF, MAILBOX_MESSAGE_COUNT, Bytes.toBytes(0L));
+                        puts.add(new Put());
+                    }
+                }
             }
         } catch (IOException e) {
             throw new RuntimeException("Error deleting MESSAGES table ", e);
-        } finally {
-            IOUtils.cleanup(null, scanner, messages, mailboxes);
         }
     }
     

http://git-wip-us.apache.org/repos/asf/james-project/blob/3c275fe6/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/mail/HBaseMessageMapper.java
----------------------------------------------------------------------
diff --git a/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/mail/HBaseMessageMapper.java b/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/mail/HBaseMessageMapper.java
index e4f7c7a..d6d602f 100644
--- a/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/mail/HBaseMessageMapper.java
+++ b/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/mail/HBaseMessageMapper.java
@@ -363,11 +363,9 @@ public class HBaseMessageMapper extends NonTransactionalMapper implements Messag
         /* TODO: see if it is possible to store the number of unseen messages in the mailbox table
          * and just return that value with a Get and kepp it up to date.
          */
-        HTable messages = null;
         ResultScanner scanner = null;
         HBaseId mailboxId = (HBaseId) mailbox.getMailboxId();
-        try {
-            messages = new HTable(conf, MESSAGES_TABLE);
+        try (HTable messages = new HTable(conf, MESSAGES_TABLE)) {
             /* Limit the number of entries scanned to just the mails in this mailbox */
             Scan scan = new Scan(
                     messageRowKey(mailboxId, MessageUid.MAX_VALUE),
@@ -382,13 +380,6 @@ public class HBaseMessageMapper extends NonTransactionalMapper implements Messag
             throw new MailboxException("Search of first unseen message failed in mailbox " + mailbox, e);
         } finally {
             scanner.close();
-            if (messages != null) {
-                try {
-                    messages.close();
-                } catch (IOException ex) {
-                    throw new MailboxException("Error closing table " + messages, ex);
-                }
-            }
         }
     }
 
@@ -433,11 +424,8 @@ public class HBaseMessageMapper extends NonTransactionalMapper implements Messag
 
     @Override
     public MessageUid findFirstUnseenMessageUid(Mailbox mailbox) throws MailboxException {
-        HTable messages = null;
-        ResultScanner scanner = null;
         HBaseId mailboxId = (HBaseId) mailbox.getMailboxId();
-        try {
-            messages = new HTable(conf, MESSAGES_TABLE);
+        try (HTable messages = new HTable(conf, MESSAGES_TABLE)) {
             /* Limit the number of entries scanned to just the mails in this mailbox */
             Scan scan = new Scan(
                     messageRowKey(mailboxId, MessageUid.MAX_VALUE), 
@@ -448,28 +436,20 @@ public class HBaseMessageMapper extends NonTransactionalMapper implements Messag
             scan.setFilter(filter);
             scan.setCaching(messages.getConfiguration().getInt("hbase.client.scanner.caching", 1) * 2);
             scan.setMaxVersions(1);
-            scanner = messages.getScanner(scan);
-            Result result;
-            MessageUid lastUnseen = null;
-            byte[] row = null;
-            while ((result = scanner.next()) != null) {
-                row = result.getRow();
-            }
-            if (row != null) {
-                lastUnseen = MessageUid.of(Long.MAX_VALUE - Bytes.toLong(row, 16, 8));
+            try (ResultScanner scanner = messages.getScanner(scan)) {
+                Result result;
+                MessageUid lastUnseen = null;
+                byte[] row = null;
+                while ((result = scanner.next()) != null) {
+                    row = result.getRow();
+                }
+                if (row != null) {
+                    lastUnseen = MessageUid.of(Long.MAX_VALUE - Bytes.toLong(row, 16, 8));
+                }
+                return lastUnseen;
             }
-            return lastUnseen;
         } catch (IOException e) {
             throw new MailboxException("Search of first unseen message failed in mailbox " + mailbox, e);
-        } finally {
-            scanner.close();
-            if (messages != null) {
-                try {
-                    messages.close();
-                } catch (IOException ex) {
-                    throw new MailboxException("Error closing table " + messages, ex);
-                }
-            }
         }
     }
 
@@ -478,11 +458,8 @@ public class HBaseMessageMapper extends NonTransactionalMapper implements Messag
         /** TODO: improve performance by implementing a last seen and last recent value per mailbox.
          * maybe one more call to HBase is less expensive than iterating throgh all rows.
          */
-        HTable messages = null;
-        ResultScanner scanner = null;
         HBaseId mailboxId = (HBaseId) mailbox.getMailboxId();
-        try {
-            messages = new HTable(conf, MESSAGES_TABLE);
+        try (HTable messages = new HTable(conf, MESSAGES_TABLE)) {
             /* Limit the number of entries scanned to just the mails in this mailbox */
             Scan scan = new Scan(
                     messageRowKey(mailboxId, MessageUid.MAX_VALUE),
@@ -494,25 +471,17 @@ public class HBaseMessageMapper extends NonTransactionalMapper implements Messag
             scan.setCaching(messages.getConfiguration().getInt("hbase.client.scanner.caching", 1) * 2);
             scan.setMaxVersions(1);
 
-            scanner = messages.getScanner(scan);
-            Result result;
-            List<MessageUid> uids = new ArrayList<>();
-            while ((result = scanner.next()) != null) {
-                uids.add(MessageUid.of(Long.MAX_VALUE - Bytes.toLong(result.getRow(), 16, 8)));
+            try (ResultScanner scanner = messages.getScanner(scan)) {
+                Result result;
+                List<MessageUid> uids = new ArrayList<>();
+                while ((result = scanner.next()) != null) {
+                    uids.add(MessageUid.of(Long.MAX_VALUE - Bytes.toLong(result.getRow(), 16, 8)));
+                }
+                Collections.reverse(uids);
+                return uids;
             }
-            Collections.reverse(uids);
-            return uids;
         } catch (IOException e) {
             throw new MailboxException("Search of recent messages failed in mailbox " + mailbox, e);
-        } finally {
-            scanner.close();
-            if (messages != null) {
-                try {
-                    messages.close();
-                } catch (IOException ex) {
-                    throw new MailboxException("Error closing table " + messages, ex);
-                }
-            }
         }
     }
 

http://git-wip-us.apache.org/repos/asf/james-project/blob/3c275fe6/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/mail/HBaseUidProvider.java
----------------------------------------------------------------------
diff --git a/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/mail/HBaseUidProvider.java b/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/mail/HBaseUidProvider.java
index e547524..3f5b0db 100644
--- a/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/mail/HBaseUidProvider.java
+++ b/mailbox/hbase/src/main/java/org/apache/james/mailbox/hbase/mail/HBaseUidProvider.java
@@ -53,10 +53,8 @@ public class HBaseUidProvider implements UidProvider {
 
     @Override
     public Optional<MessageUid> lastUid(MailboxSession session, Mailbox mailbox) throws MailboxException {
-        HTable mailboxes = null;
         HBaseId mailboxId = (HBaseId) mailbox.getMailboxId();
-        try {
-            mailboxes = new HTable(conf, MAILBOXES_TABLE);
+        try (HTable mailboxes = new HTable(conf, MAILBOXES_TABLE)) {
             Get get = new Get(mailboxId.toBytes());
             get.addColumn(MAILBOX_CF, MAILBOX_LASTUID);
             get.setMaxVersions(1);
@@ -72,14 +70,6 @@ public class HBaseUidProvider implements UidProvider {
             return Optional.of(MessageUid.of(rawUid));
         } catch (IOException e) {
             throw new MailboxException("lastUid", e);
-        } finally {
-            if (mailboxes != null) {
-                try {
-                    mailboxes.close();
-                } catch (IOException ex) {
-                    throw new MailboxException("Error closing table " + mailboxes, ex);
-                }
-            }
         }
     }
 
@@ -91,22 +81,12 @@ public class HBaseUidProvider implements UidProvider {
     @Override
     public MessageUid nextUid(MailboxSession session, MailboxId mailboxId) throws MailboxException {
         HBaseId hbaseId = (HBaseId) mailboxId;
-        HTable mailboxes = null;
-        try {
-            mailboxes = new HTable(conf, MAILBOXES_TABLE);
+        try (HTable mailboxes = new HTable(conf, MAILBOXES_TABLE)) {
             MessageUid newValue = MessageUid.of(mailboxes.incrementColumnValue(hbaseId.toBytes(), MAILBOX_CF, MAILBOX_LASTUID, 1));
             mailboxes.close();
             return newValue;
         } catch (IOException e) {
             throw new MailboxException("lastUid", e);
-        } finally {
-            if (mailboxes != null) {
-                try {
-                    mailboxes.close();
-                } catch (IOException ex) {
-                    throw new MailboxException("Error closing table " + mailboxes, ex);
-                }
-            }
         }
     }
 

http://git-wip-us.apache.org/repos/asf/james-project/blob/3c275fe6/mailbox/jcr/src/main/java/org/apache/james/mailbox/jcr/JCRUtils.java
----------------------------------------------------------------------
diff --git a/mailbox/jcr/src/main/java/org/apache/james/mailbox/jcr/JCRUtils.java b/mailbox/jcr/src/main/java/org/apache/james/mailbox/jcr/JCRUtils.java
index 8c50d68..192b548 100644
--- a/mailbox/jcr/src/main/java/org/apache/james/mailbox/jcr/JCRUtils.java
+++ b/mailbox/jcr/src/main/java/org/apache/james/mailbox/jcr/JCRUtils.java
@@ -64,14 +64,12 @@ public class JCRUtils implements JCRImapConstants {
     
     /**
      * Register the imap CND file 
-     * 
-     * @param session
      */
     public static void registerCnd(Session session) {
         // Register the custom node types defined in the CND file
-        InputStream is = Thread.currentThread().getContextClassLoader()
-                              .getResourceAsStream("mailbox-jcr.cnd");
-        try {
+        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
+
+        try (InputStream is = contextClassLoader.getResourceAsStream("mailbox-jcr.cnd")) {
             CndImporter.registerNodeTypes(new InputStreamReader(is), session);
         } catch (Exception e) {
             throw new RuntimeException("Unable to register cnd file", e);


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


[11/20] james-project git commit: JAMES-2513 Disable DomainList localhost translation when autoDetect is false

Posted by bt...@apache.org.
JAMES-2513 Disable DomainList localhost translation when autoDetect is false


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

Branch: refs/heads/master
Commit: 5bb6ddeccd2756c8e189a043ba959cdbf7f1b14d
Parents: 8daad38
Author: benwa <bt...@linagora.com>
Authored: Thu Aug 2 16:46:07 2018 +0700
Committer: Benoit Tellier <bt...@linagora.com>
Committed: Fri Aug 3 15:51:29 2018 +0700

----------------------------------------------------------------------
 .../apache/james/domainlist/lib/AbstractDomainList.java   |  2 +-
 .../lib/AbstractDomainListPrivateMethodsTest.java         | 10 ++++++++++
 2 files changed, 11 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/5bb6ddec/server/data/data-library/src/main/java/org/apache/james/domainlist/lib/AbstractDomainList.java
----------------------------------------------------------------------
diff --git a/server/data/data-library/src/main/java/org/apache/james/domainlist/lib/AbstractDomainList.java b/server/data/data-library/src/main/java/org/apache/james/domainlist/lib/AbstractDomainList.java
index e27ed5e..6c67045 100644
--- a/server/data/data-library/src/main/java/org/apache/james/domainlist/lib/AbstractDomainList.java
+++ b/server/data/data-library/src/main/java/org/apache/james/domainlist/lib/AbstractDomainList.java
@@ -126,7 +126,7 @@ public abstract class AbstractDomainList implements DomainList, Configurable {
     }
 
     private boolean mayChangeDefaultDomain() {
-        return Domain.LOCALHOST.equals(defaultDomain);
+        return autoDetect && Domain.LOCALHOST.equals(defaultDomain);
     }
 
     private void setDefaultDomain(Domain defaultDomain) throws DomainListException {

http://git-wip-us.apache.org/repos/asf/james-project/blob/5bb6ddec/server/data/data-library/src/test/java/org/apache/james/domainlist/lib/AbstractDomainListPrivateMethodsTest.java
----------------------------------------------------------------------
diff --git a/server/data/data-library/src/test/java/org/apache/james/domainlist/lib/AbstractDomainListPrivateMethodsTest.java b/server/data/data-library/src/test/java/org/apache/james/domainlist/lib/AbstractDomainListPrivateMethodsTest.java
index 4ecd689..96a59ae 100644
--- a/server/data/data-library/src/test/java/org/apache/james/domainlist/lib/AbstractDomainListPrivateMethodsTest.java
+++ b/server/data/data-library/src/test/java/org/apache/james/domainlist/lib/AbstractDomainListPrivateMethodsTest.java
@@ -306,4 +306,14 @@ public class AbstractDomainListPrivateMethodsTest {
         assertThat(domainList.getDomains()).contains(domain1, domain2);
     }
 
+    @Test
+    public void configureShouldNotAttemptToChangeLocalHostDefaultDomainWhenNoAutoDetect() throws Exception {
+        domainList.configure(DomainListConfiguration.builder()
+            .autoDetect(false)
+            .autoDetectIp(false)
+            .defaultDomain(Domain.LOCALHOST));
+
+        assertThat(domainList.getDefaultDomain()).isEqualTo(Domain.LOCALHOST);
+    }
+
 }


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


[12/20] james-project git commit: JAMES-2513 Improve XMLDomainListTest

Posted by bt...@apache.org.
JAMES-2513 Improve XMLDomainListTest

Use DomainListConfiguration

We also sole an issue in 'configureShouldNotFailWhenConfiguringDefaultDomain'.
The assertion concerned the domain number count, affected by no more auto-detecting localhost default domain. Hence I reworked it.


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

Branch: refs/heads/master
Commit: 7063734f59efbc6bfcaa52b08dee5d771879a6dc
Parents: 5bb6dde
Author: benwa <bt...@linagora.com>
Authored: Thu Aug 2 10:52:34 2018 +0700
Committer: Benoit Tellier <bt...@linagora.com>
Committed: Fri Aug 3 15:51:29 2018 +0700

----------------------------------------------------------------------
 .../james/domainlist/xml/XMLDomainList.java     |  6 +-
 .../james/domainlist/xml/XMLDomainListTest.java | 89 +++++++++-----------
 2 files changed, 43 insertions(+), 52 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/7063734f/server/data/data-file/src/main/java/org/apache/james/domainlist/xml/XMLDomainList.java
----------------------------------------------------------------------
diff --git a/server/data/data-file/src/main/java/org/apache/james/domainlist/xml/XMLDomainList.java b/server/data/data-file/src/main/java/org/apache/james/domainlist/xml/XMLDomainList.java
index 73b9b31..7c36e16 100644
--- a/server/data/data-file/src/main/java/org/apache/james/domainlist/xml/XMLDomainList.java
+++ b/server/data/data-file/src/main/java/org/apache/james/domainlist/xml/XMLDomainList.java
@@ -26,11 +26,11 @@ import javax.inject.Inject;
 import javax.inject.Singleton;
 
 import org.apache.commons.configuration.ConfigurationException;
-import org.apache.commons.configuration.HierarchicalConfiguration;
 import org.apache.james.core.Domain;
 import org.apache.james.dnsservice.api.DNSService;
 import org.apache.james.domainlist.api.DomainListException;
 import org.apache.james.domainlist.lib.AbstractDomainList;
+import org.apache.james.domainlist.lib.DomainListConfiguration;
 import org.apache.james.lifecycle.api.Configurable;
 
 /**
@@ -48,8 +48,8 @@ public class XMLDomainList extends AbstractDomainList implements Configurable {
     }
 
     @Override
-    public void configure(HierarchicalConfiguration config) throws ConfigurationException {
-        super.configure(config);
+    public void configure(DomainListConfiguration domainListConfiguration) throws ConfigurationException {
+        super.configure(domainListConfiguration);
         isConfigured = true;
     }
 

http://git-wip-us.apache.org/repos/asf/james-project/blob/7063734f/server/data/data-file/src/test/java/org/apache/james/domainlist/xml/XMLDomainListTest.java
----------------------------------------------------------------------
diff --git a/server/data/data-file/src/test/java/org/apache/james/domainlist/xml/XMLDomainListTest.java b/server/data/data-file/src/test/java/org/apache/james/domainlist/xml/XMLDomainListTest.java
index 7a99107..366dfe2 100644
--- a/server/data/data-file/src/test/java/org/apache/james/domainlist/xml/XMLDomainListTest.java
+++ b/server/data/data-file/src/test/java/org/apache/james/domainlist/xml/XMLDomainListTest.java
@@ -22,16 +22,13 @@ import static org.assertj.core.api.Assertions.assertThat;
 
 import java.net.InetAddress;
 import java.net.UnknownHostException;
-import java.util.ArrayList;
 import java.util.Collection;
-import java.util.List;
 
-import org.apache.commons.configuration.DefaultConfigurationBuilder;
-import org.apache.commons.configuration.HierarchicalConfiguration;
 import org.apache.james.core.Domain;
 import org.apache.james.dnsservice.api.DNSService;
 import org.apache.james.dnsservice.api.mock.MockDNSService;
 import org.apache.james.domainlist.api.DomainListException;
+import org.apache.james.domainlist.lib.DomainListConfiguration;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.ExpectedException;
@@ -41,21 +38,10 @@ import com.google.common.collect.ImmutableList;
 public class XMLDomainListTest {
 
     public static final Domain DEFAULT_DOMAIN = Domain.of("default.domain");
+    public static final Domain DOMAIN_1 = Domain.of("domain1");
 
     @Rule
     public ExpectedException expectedException = ExpectedException.none();
-    
-    private HierarchicalConfiguration setUpConfiguration(boolean auto, boolean autoIP, List<String> names) {
-        DefaultConfigurationBuilder configuration = new DefaultConfigurationBuilder();
-
-        configuration.addProperty("autodetect", auto);
-        configuration.addProperty("autodetectIP", autoIP);
-        for (String name : names) {
-            configuration.addProperty("domainnames.domainname", name);
-        }
-        configuration.addProperty("defaultDomain", DEFAULT_DOMAIN.asString());
-        return configuration;
-    }
 
     private DNSService setUpDNSServer(final String hostName) {
         return new MockDNSService() {
@@ -80,43 +66,49 @@ public class XMLDomainListTest {
     // See https://issues.apache.org/jira/browse/JAMES-998
     @Test
     public void testNoConfiguredDomains() throws Exception {
-        List<String> domains = new ArrayList<>();
         XMLDomainList dom = new XMLDomainList(setUpDNSServer("localhost"));
-        dom.configure(setUpConfiguration(false, false, domains));
+
+        dom.configure(DomainListConfiguration.builder()
+            .autoDetect(false)
+            .autoDetectIp(false)
+            .defaultDomain(DEFAULT_DOMAIN));
+
 
         assertThat(dom.getDomains()).containsOnly(DEFAULT_DOMAIN);
     }
 
     @Test
     public void testGetDomains() throws Exception {
-        List<String> domains = new ArrayList<>();
-        domains.add("domain1.");
-        domains.add("domain2.");
-
         XMLDomainList dom = new XMLDomainList(setUpDNSServer("localhost"));
-        dom.configure(setUpConfiguration(false, false, domains));
+        dom.configure(DomainListConfiguration.builder()
+            .autoDetect(false)
+            .autoDetectIp(false)
+            .addConfiguredDomains(Domain.of("domain1."), Domain.of("domain2."))
+            .defaultDomain(DEFAULT_DOMAIN));
 
         assertThat(dom.getDomains()).hasSize(3);
     }
 
     @Test
     public void testGetDomainsAutoDetectNotLocalHost() throws Exception {
-        List<String> domains = new ArrayList<>();
-        domains.add("domain1.");
-
         XMLDomainList dom = new XMLDomainList(setUpDNSServer("local"));
-        dom.configure(setUpConfiguration(true, false, domains));
+        dom.configure(DomainListConfiguration.builder()
+            .autoDetect(true)
+            .autoDetectIp(false)
+            .addConfiguredDomains(Domain.of("domain1."))
+            .defaultDomain(DEFAULT_DOMAIN));
 
         assertThat(dom.getDomains()).hasSize(3);
     }
 
     @Test
     public void testGetDomainsAutoDetectLocalHost() throws Exception {
-        List<String> domains = new ArrayList<>();
-        domains.add("domain1.");
-
         XMLDomainList dom = new XMLDomainList(setUpDNSServer("localhost"));
-        dom.configure(setUpConfiguration(true, false, domains));
+        dom.configure(DomainListConfiguration.builder()
+            .autoDetect(false)
+            .autoDetectIp(false)
+            .addConfiguredDomains(Domain.of("domain1."))
+            .defaultDomain(DEFAULT_DOMAIN));
 
         assertThat(dom.getDomains()).hasSize(2);
     }
@@ -125,11 +117,12 @@ public class XMLDomainListTest {
     public void addDomainShouldFailWhenAlreadyConfigured() throws Exception {
         expectedException.expect(DomainListException.class);
 
-        List<String> domains = new ArrayList<>();
-        domains.add("domain1");
-
         XMLDomainList testee = new XMLDomainList(setUpDNSServer("hostname"));
-        testee.configure(setUpConfiguration(true, false, domains));
+        testee.configure(DomainListConfiguration.builder()
+            .autoDetect(true)
+            .autoDetectIp(false)
+            .addConfiguredDomain(DOMAIN_1)
+            .defaultDomain(DEFAULT_DOMAIN));
 
         testee.addDomain(Domain.of("newDomain"));
     }
@@ -138,27 +131,25 @@ public class XMLDomainListTest {
     public void removeDomainShouldFailWhenAlreadyConfigured() throws Exception {
         expectedException.expect(DomainListException.class);
 
-        List<String> domains = new ArrayList<>();
-        domains.add("domain1");
-
         XMLDomainList testee = new XMLDomainList(setUpDNSServer("localhost"));
-        testee.configure(setUpConfiguration(true, false, domains));
+        testee.configure(DomainListConfiguration.builder()
+            .autoDetect(true)
+            .autoDetectIp(false)
+            .addConfiguredDomain(DOMAIN_1));
 
         testee.removeDomain(Domain.of("newDomain"));
     }
 
     @Test
     public void configureShouldNotFailWhenConfiguringDefaultDomain() throws Exception {
-        DefaultConfigurationBuilder configuration = new DefaultConfigurationBuilder();
-
-        configuration.addProperty("autodetect", false);
-        configuration.addProperty("autodetectIP", false);
-        configuration.addProperty("domainnames.domainname", "domain1");
-        configuration.addProperty("defaultDomain", "localhost");
-
         XMLDomainList testee = new XMLDomainList(setUpDNSServer("localhost"));
-        testee.configure(configuration);
-
-        assertThat(testee.getDomainListInternal()).hasSize(3);
+        testee.configure(DomainListConfiguration.builder()
+            .autoDetect(false)
+            .autoDetectIp(false)
+            .defaultDomain(Domain.LOCALHOST)
+            .addConfiguredDomain(DOMAIN_1));
+
+        assertThat(testee.getDomainListInternal())
+            .containsOnly(DOMAIN_1, Domain.LOCALHOST);
     }
 }


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


[14/20] james-project git commit: JAMES-2513 Enforce usage of DomainListConfiguration over XML in tests

Posted by bt...@apache.org.
JAMES-2513 Enforce usage of DomainListConfiguration over XML in tests


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

Branch: refs/heads/master
Commit: 33c809a8076d5fe1f9c7ffa8bdc5579b10dfaaba
Parents: 26b4081
Author: benwa <bt...@linagora.com>
Authored: Thu Aug 2 10:58:25 2018 +0700
Committer: Benoit Tellier <bt...@linagora.com>
Committed: Fri Aug 3 15:51:29 2018 +0700

----------------------------------------------------------------------
 .../test/java/org/apache/james/AbstractJamesServerTest.java | 9 +++++++++
 .../src/test/java/org/apache/james/JPAJamesServerTest.java  | 2 +-
 .../apache/james/JPAJamesServerWithSqlValidationTest.java   | 2 +-
 .../org/apache/james/webadmin/routes/ForwardRoutesTest.java | 7 ++++---
 .../james/webadmin/routes/ScanningQuotaSearchExtension.java | 6 ++++--
 5 files changed, 19 insertions(+), 7 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/33c809a8/server/container/guice/guice-common/src/test/java/org/apache/james/AbstractJamesServerTest.java
----------------------------------------------------------------------
diff --git a/server/container/guice/guice-common/src/test/java/org/apache/james/AbstractJamesServerTest.java b/server/container/guice/guice-common/src/test/java/org/apache/james/AbstractJamesServerTest.java
index c0ffb7b..f10d8d6 100644
--- a/server/container/guice/guice-common/src/test/java/org/apache/james/AbstractJamesServerTest.java
+++ b/server/container/guice/guice-common/src/test/java/org/apache/james/AbstractJamesServerTest.java
@@ -27,11 +27,14 @@ import java.nio.ByteBuffer;
 import java.nio.channels.SocketChannel;
 import java.nio.charset.Charset;
 
+import org.apache.james.domainlist.lib.DomainListConfiguration;
 import org.apache.james.utils.DataProbeImpl;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 
+import com.google.inject.Module;
+
 public abstract class AbstractJamesServerTest {
 
     private static final int IMAP_PORT = 1143; // You need to be root (superuser) to bind to ports under 1024.
@@ -40,6 +43,12 @@ public abstract class AbstractJamesServerTest {
     private static final int SMTP_PORT = 1025;
     private static final int LMTP_PORT = 1024;
 
+    public static final Module DOMAIN_LIST_CONFIGURATION_MODULE = binder -> binder.bind(DomainListConfiguration.class)
+        .toInstance(DomainListConfiguration.builder()
+            .autoDetect(true)
+            .autoDetectIp(false)
+            .build());
+
     protected GuiceJamesServer server;
     private SocketChannel socketChannel;
 

http://git-wip-us.apache.org/repos/asf/james-project/blob/33c809a8/server/container/guice/jpa-guice/src/test/java/org/apache/james/JPAJamesServerTest.java
----------------------------------------------------------------------
diff --git a/server/container/guice/jpa-guice/src/test/java/org/apache/james/JPAJamesServerTest.java b/server/container/guice/jpa-guice/src/test/java/org/apache/james/JPAJamesServerTest.java
index fac0a80..220bfe1 100644
--- a/server/container/guice/jpa-guice/src/test/java/org/apache/james/JPAJamesServerTest.java
+++ b/server/container/guice/jpa-guice/src/test/java/org/apache/james/JPAJamesServerTest.java
@@ -68,7 +68,7 @@ public class JPAJamesServerTest extends AbstractJamesServerTest {
 
         return new GuiceJamesServer(configuration)
             .combineWith(JPAJamesServerMain.JPA_SERVER_MODULE, JPAJamesServerMain.PROTOCOLS)
-            .overrideWith(new TestJPAConfigurationModule());
+            .overrideWith(new TestJPAConfigurationModule(), DOMAIN_LIST_CONFIGURATION_MODULE);
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/james-project/blob/33c809a8/server/container/guice/jpa-guice/src/test/java/org/apache/james/JPAJamesServerWithSqlValidationTest.java
----------------------------------------------------------------------
diff --git a/server/container/guice/jpa-guice/src/test/java/org/apache/james/JPAJamesServerWithSqlValidationTest.java b/server/container/guice/jpa-guice/src/test/java/org/apache/james/JPAJamesServerWithSqlValidationTest.java
index 5bdee09..7a86bbc 100644
--- a/server/container/guice/jpa-guice/src/test/java/org/apache/james/JPAJamesServerWithSqlValidationTest.java
+++ b/server/container/guice/jpa-guice/src/test/java/org/apache/james/JPAJamesServerWithSqlValidationTest.java
@@ -34,7 +34,7 @@ public class JPAJamesServerWithSqlValidationTest extends JPAJamesServerTest {
 
         return new GuiceJamesServer(configuration)
             .combineWith(JPAJamesServerMain.JPA_SERVER_MODULE, JPAJamesServerMain.PROTOCOLS)
-            .overrideWith(new TestJPAConfigurationModuleWithSqlValidation());
+            .overrideWith(new TestJPAConfigurationModuleWithSqlValidation(), DOMAIN_LIST_CONFIGURATION_MODULE);
     }
 
 }

http://git-wip-us.apache.org/repos/asf/james-project/blob/33c809a8/server/protocols/webadmin/webadmin-data/src/test/java/org/apache/james/webadmin/routes/ForwardRoutesTest.java
----------------------------------------------------------------------
diff --git a/server/protocols/webadmin/webadmin-data/src/test/java/org/apache/james/webadmin/routes/ForwardRoutesTest.java b/server/protocols/webadmin/webadmin-data/src/test/java/org/apache/james/webadmin/routes/ForwardRoutesTest.java
index c27bc00..80e4e45 100644
--- a/server/protocols/webadmin/webadmin-data/src/test/java/org/apache/james/webadmin/routes/ForwardRoutesTest.java
+++ b/server/protocols/webadmin/webadmin-data/src/test/java/org/apache/james/webadmin/routes/ForwardRoutesTest.java
@@ -40,6 +40,7 @@ import org.apache.commons.configuration.DefaultConfigurationBuilder;
 import org.apache.james.core.Domain;
 import org.apache.james.dnsservice.api.DNSService;
 import org.apache.james.domainlist.api.DomainList;
+import org.apache.james.domainlist.lib.DomainListConfiguration;
 import org.apache.james.domainlist.memory.MemoryDomainList;
 import org.apache.james.metrics.logger.DefaultMetricFactory;
 import org.apache.james.rrt.api.RecipientRewriteTable;
@@ -108,9 +109,9 @@ class ForwardRoutesTest {
             memoryRecipientRewriteTable = new MemoryRecipientRewriteTable();
             DNSService dnsService = mock(DNSService.class);
             domainList = new MemoryDomainList(dnsService);
-            domainList.setAutoDetectIP(false);
-            domainList.setAutoDetect(false);
-            domainList.configure(new DefaultConfigurationBuilder());
+            domainList.configure(DomainListConfiguration.builder()
+                .autoDetect(false)
+                .autoDetectIp(false));
             domainList.addDomain(DOMAIN);
 
             usersRepository = MemoryUsersRepository.withVirtualHosting();

http://git-wip-us.apache.org/repos/asf/james-project/blob/33c809a8/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/ScanningQuotaSearchExtension.java
----------------------------------------------------------------------
diff --git a/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/ScanningQuotaSearchExtension.java b/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/ScanningQuotaSearchExtension.java
index af69584..552f3d2 100644
--- a/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/ScanningQuotaSearchExtension.java
+++ b/server/protocols/webadmin/webadmin-mailbox/src/test/java/org/apache/james/webadmin/routes/ScanningQuotaSearchExtension.java
@@ -21,8 +21,8 @@ package org.apache.james.webadmin.routes;
 
 import static org.mockito.Mockito.mock;
 
-import org.apache.commons.configuration.DefaultConfigurationBuilder;
 import org.apache.james.dnsservice.api.DNSService;
+import org.apache.james.domainlist.lib.DomainListConfiguration;
 import org.apache.james.domainlist.memory.MemoryDomainList;
 import org.apache.james.mailbox.acl.SimpleGroupMembershipResolver;
 import org.apache.james.mailbox.inmemory.manager.InMemoryIntegrationResources;
@@ -51,7 +51,9 @@ public class ScanningQuotaSearchExtension implements ParameterResolver, BeforeEa
 
             DNSService dnsService = mock(DNSService.class);
             MemoryDomainList domainList = new MemoryDomainList(dnsService);
-            domainList.configure(new DefaultConfigurationBuilder());
+            domainList.configure(DomainListConfiguration.builder()
+                .autoDetect(false)
+                .autoDetectIp(false));
             usersRepository.setDomainList(domainList);
 
             QuotaSearchTestSystem quotaSearchTestSystem = new QuotaSearchTestSystem(


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


[03/20] james-project git commit: JAMES-2506 Remove jmock from root pom & mailetdoc-maven-plugin

Posted by bt...@apache.org.
JAMES-2506 Remove jmock from root pom & mailetdoc-maven-plugin


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

Branch: refs/heads/master
Commit: de033f3ee6b733919ed5c1d2f4d2a2e65187d89d
Parents: 6373f39
Author: duc <dt...@linagora.com>
Authored: Tue Jul 31 10:23:42 2018 +0700
Committer: Benoit Tellier <bt...@linagora.com>
Committed: Fri Aug 3 15:51:21 2018 +0700

----------------------------------------------------------------------
 .../appended-resources/supplemental-models.xml     | 17 -----------------
 pom.xml                                            | 16 ----------------
 2 files changed, 33 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/de033f3e/mailet/mailetdocs-maven-plugin/src/main/appended-resources/supplemental-models.xml
----------------------------------------------------------------------
diff --git a/mailet/mailetdocs-maven-plugin/src/main/appended-resources/supplemental-models.xml b/mailet/mailetdocs-maven-plugin/src/main/appended-resources/supplemental-models.xml
index 4cf9a46..f39d6dc 100644
--- a/mailet/mailetdocs-maven-plugin/src/main/appended-resources/supplemental-models.xml
+++ b/mailet/mailetdocs-maven-plugin/src/main/appended-resources/supplemental-models.xml
@@ -86,21 +86,4 @@
       </licenses>
     </project>
   </supplement>
-  <supplement>
-    <project>
-      <groupId>jmock</groupId>
-      <artifactId>jmock</artifactId>
-      <name>JMock</name>
-      <organization>
-        <name>jMock.org</name>
-        <url>http://jmock.org</url>
-      </organization>
-      <licenses>
-        <license>
-          <name>jMock Project License</name>
-          <url>http://www.jmock.org/license.html</url>
-        </license>
-      </licenses>
-    </project>
-  </supplement>
 </supplementalDataModels>

http://git-wip-us.apache.org/repos/asf/james-project/blob/de033f3e/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 3f87747..9486a92 100644
--- a/pom.xml
+++ b/pom.xml
@@ -613,7 +613,6 @@
         <junit.jupiter.version>5.0.2</junit.jupiter.version>
         <junit.plateform.version>1.0.2</junit.plateform.version>
         <junit.vintage.version>4.12.2</junit.vintage.version>
-        <jmock.version>2.6.0</jmock.version>
         <concurrent.version>1.3.4</concurrent.version>
         <jcr.version>2.0</jcr.version>
         <xbean-spring.version>4.9</xbean-spring.version>
@@ -1941,11 +1940,6 @@
                 <version>${servlet-api.version}</version>
             </dependency>
             <dependency>
-                <groupId>jmock</groupId>
-                <artifactId>jmock</artifactId>
-                <version>1.1.0</version>
-            </dependency>
-            <dependency>
                 <groupId>junit</groupId>
                 <artifactId>junit</artifactId>
                 <version>${junit.version}</version>
@@ -2357,16 +2351,6 @@
                 <version>${jasypt.version}</version>
             </dependency>
             <dependency>
-                <groupId>org.jmock</groupId>
-                <artifactId>jmock</artifactId>
-                <version>${jmock.version}</version>
-            </dependency>
-            <dependency>
-                <groupId>org.jmock</groupId>
-                <artifactId>jmock-junit4</artifactId>
-                <version>${jmock.version}</version>
-            </dependency>
-            <dependency>
                 <groupId>org.junit.jupiter</groupId>
                 <artifactId>junit-jupiter-engine</artifactId>
                 <version>${junit.jupiter.version}</version>


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


[18/20] james-project git commit: JAMES-2513 JPA Domain List configuration should rely on POJO

Posted by bt...@apache.org.
JAMES-2513 JPA Domain List configuration should rely on POJO


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

Branch: refs/heads/master
Commit: 8d33e65eb3ee15b16d57dee134df874802e2441a
Parents: 75097ea
Author: benwa <bt...@linagora.com>
Authored: Thu Aug 2 14:06:07 2018 +0700
Committer: Benoit Tellier <bt...@linagora.com>
Committed: Fri Aug 3 15:51:30 2018 +0700

----------------------------------------------------------------------
 .../james/modules/data/JPADomainListModule.java | 20 ++++++++++++++++----
 1 file changed, 16 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/james-project/blob/8d33e65e/server/container/guice/jpa-common-guice/src/main/java/org/apache/james/modules/data/JPADomainListModule.java
----------------------------------------------------------------------
diff --git a/server/container/guice/jpa-common-guice/src/main/java/org/apache/james/modules/data/JPADomainListModule.java b/server/container/guice/jpa-common-guice/src/main/java/org/apache/james/modules/data/JPADomainListModule.java
index 3aaa16f..01ff8e0 100644
--- a/server/container/guice/jpa-common-guice/src/main/java/org/apache/james/modules/data/JPADomainListModule.java
+++ b/server/container/guice/jpa-common-guice/src/main/java/org/apache/james/modules/data/JPADomainListModule.java
@@ -23,6 +23,7 @@ import java.util.List;
 import org.apache.commons.configuration.ConfigurationException;
 import org.apache.james.domainlist.api.DomainList;
 import org.apache.james.domainlist.jpa.JPADomainList;
+import org.apache.james.domainlist.lib.DomainListConfiguration;
 import org.apache.james.lifecycle.api.Configurable;
 import org.apache.james.server.core.configuration.ConfigurationProvider;
 import org.apache.james.utils.ConfigurationPerformer;
@@ -30,6 +31,7 @@ import org.apache.james.utils.ConfigurationPerformer;
 import com.google.common.collect.ImmutableList;
 import com.google.inject.AbstractModule;
 import com.google.inject.Inject;
+import com.google.inject.Provides;
 import com.google.inject.Scopes;
 import com.google.inject.Singleton;
 import com.google.inject.multibindings.Multibinder;
@@ -42,23 +44,33 @@ public class JPADomainListModule extends AbstractModule {
         bind(DomainList.class).to(JPADomainList.class);
         Multibinder.newSetBinder(binder(), ConfigurationPerformer.class).addBinding().to(JPADomainListConfigurationPerformer.class);
     }
+
+    @Provides
+    @Singleton
+    public DomainListConfiguration provideDomainListConfiguration(ConfigurationProvider configurationProvider) {
+        try {
+            return DomainListConfiguration.from(configurationProvider.getConfiguration("domainlist"));
+        } catch (ConfigurationException e) {
+            throw new RuntimeException(e);
+        }
+    }
     
     @Singleton
     public static class JPADomainListConfigurationPerformer implements ConfigurationPerformer {
 
-        private final ConfigurationProvider configurationProvider;
+        private final DomainListConfiguration configuration;
         private final JPADomainList jpaDomainList;
 
         @Inject
-        public JPADomainListConfigurationPerformer(ConfigurationProvider configurationProvider, JPADomainList jpaDomainList) {
-            this.configurationProvider = configurationProvider;
+        public JPADomainListConfigurationPerformer(DomainListConfiguration configuration, JPADomainList jpaDomainList) {
+            this.configuration = configuration;
             this.jpaDomainList = jpaDomainList;
         }
 
         @Override
         public void initModule() {
             try {
-                jpaDomainList.configure(configurationProvider.getConfiguration("domainlist"));
+                jpaDomainList.configure(configuration);
             } catch (ConfigurationException e) {
                 throw new RuntimeException(e);
             }


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


[07/20] james-project git commit: JAMES-2517 Use try-with-resource in more places

Posted by bt...@apache.org.
http://git-wip-us.apache.org/repos/asf/james-project/blob/3c275fe6/mailbox/maildir/src/main/java/org/apache/james/mailbox/maildir/user/MaildirSubscriptionMapper.java
----------------------------------------------------------------------
diff --git a/mailbox/maildir/src/main/java/org/apache/james/mailbox/maildir/user/MaildirSubscriptionMapper.java b/mailbox/maildir/src/main/java/org/apache/james/mailbox/maildir/user/MaildirSubscriptionMapper.java
index b235c89..aaf15bf 100644
--- a/mailbox/maildir/src/main/java/org/apache/james/mailbox/maildir/user/MaildirSubscriptionMapper.java
+++ b/mailbox/maildir/src/main/java/org/apache/james/mailbox/maildir/user/MaildirSubscriptionMapper.java
@@ -137,14 +137,13 @@ public class MaildirSubscriptionMapper extends NonTransactionalMapper implements
         if (!subscriptionFile.exists()) {
             return ImmutableSet.of();
         }
-        FileReader fileReader = new FileReader(subscriptionFile);
-        BufferedReader reader = new BufferedReader(fileReader);
-        Set<String> subscriptions = reader.lines()
-            .filter(subscription -> !subscription.equals(""))
-            .collect(Guavate.toImmutableSet());
-        reader.close();
-        fileReader.close();
-        return subscriptions;
+        try (FileReader fileReader = new FileReader(subscriptionFile)) {
+            try (BufferedReader reader = new BufferedReader(fileReader)) {
+                return reader.lines()
+                    .filter(subscription -> !subscription.equals(""))
+                    .collect(Guavate.toImmutableSet());
+            }
+        }
     }
     
     /**
@@ -161,21 +160,19 @@ public class MaildirSubscriptionMapper extends NonTransactionalMapper implements
                 throw new IOException("Could not create folder " + mailboxFolder);
             }
         }
-        
+
         File subscriptionFile = new File(mailboxFolder, FILE_SUBSCRIPTION);
         if (!subscriptionFile.exists()) {
             if (!subscriptionFile.createNewFile()) {
                 throw new IOException("Could not create file " + subscriptionFile);
             }
         }
-                
-        FileWriter fileWriter = new FileWriter(subscriptionFile);
-        PrintWriter writer = new PrintWriter(fileWriter);
-        for (String subscription : sortedSubscriptions) {
-            writer.println(subscription);
+
+        try (FileWriter fileWriter = new FileWriter(subscriptionFile)) {
+            try (PrintWriter writer = new PrintWriter(fileWriter)) {
+                sortedSubscriptions.forEach(writer::println);
+            }
         }
-        writer.close();
-        fileWriter.close();
     }
 
 }

http://git-wip-us.apache.org/repos/asf/james-project/blob/3c275fe6/mailet/base/src/main/java/org/apache/mailet/base/AutomaticallySentMailDetectorImpl.java
----------------------------------------------------------------------
diff --git a/mailet/base/src/main/java/org/apache/mailet/base/AutomaticallySentMailDetectorImpl.java b/mailet/base/src/main/java/org/apache/mailet/base/AutomaticallySentMailDetectorImpl.java
index eb19122..43645a3 100644
--- a/mailet/base/src/main/java/org/apache/mailet/base/AutomaticallySentMailDetectorImpl.java
+++ b/mailet/base/src/main/java/org/apache/mailet/base/AutomaticallySentMailDetectorImpl.java
@@ -110,12 +110,13 @@ public class AutomaticallySentMailDetectorImpl implements AutomaticallySentMailD
             @Override
             public void body(BodyDescriptor bodyDescriptor, InputStream inputStream) throws MimeException, IOException {
                 if (bodyDescriptor.getMimeType().equalsIgnoreCase("message/disposition-notification")) {
-                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
-                    String line;
-                    while ((line = reader.readLine()) != null) {
-                        if (line.startsWith("Disposition:")) {
-                            if (line.contains("MDN-sent-automatically") || line.contains("automatic-action")) {
-                                resultCollector.setResult(true);
+                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
+                        String line;
+                        while ((line = reader.readLine()) != null) {
+                            if (line.startsWith("Disposition:")) {
+                                if (line.contains("MDN-sent-automatically") || line.contains("automatic-action")) {
+                                    resultCollector.setResult(true);
+                                }
                             }
                         }
                     }

http://git-wip-us.apache.org/repos/asf/james-project/blob/3c275fe6/mailet/standard/src/main/java/org/apache/james/transport/mailets/LogMessage.java
----------------------------------------------------------------------
diff --git a/mailet/standard/src/main/java/org/apache/james/transport/mailets/LogMessage.java b/mailet/standard/src/main/java/org/apache/james/transport/mailets/LogMessage.java
index 0707359..72a6839 100644
--- a/mailet/standard/src/main/java/org/apache/james/transport/mailets/LogMessage.java
+++ b/mailet/standard/src/main/java/org/apache/james/transport/mailets/LogMessage.java
@@ -117,8 +117,9 @@ public class LogMessage extends GenericMailet {
 
     private void logBody(MimeMessage message) throws MessagingException, IOException {
         if (body && logger.isInfoEnabled()) {
-            InputStream inputStream = ByteStreams.limit(message.getDataHandler().getInputStream(), lengthToLog(message));
-            logger.info(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
+            try (InputStream inputStream = ByteStreams.limit(message.getDataHandler().getInputStream(), lengthToLog(message))) {
+                logger.info(IOUtils.toString(inputStream, StandardCharsets.UTF_8));
+            }
         }
     }
 

http://git-wip-us.apache.org/repos/asf/james-project/blob/3c275fe6/mpt/antlib/src/main/java/org/apache/james/mpt/ant/MailProtocolTestTask.java
----------------------------------------------------------------------
diff --git a/mpt/antlib/src/main/java/org/apache/james/mpt/ant/MailProtocolTestTask.java b/mpt/antlib/src/main/java/org/apache/james/mpt/ant/MailProtocolTestTask.java
index 6d3a08b..3fa1546 100644
--- a/mpt/antlib/src/main/java/org/apache/james/mpt/ant/MailProtocolTestTask.java
+++ b/mpt/antlib/src/main/java/org/apache/james/mpt/ant/MailProtocolTestTask.java
@@ -20,6 +20,7 @@
 package org.apache.james.mpt.ant;
 
 import java.io.File;
+import java.io.FileNotFoundException;
 import java.io.FileReader;
 import java.io.IOException;
 import java.io.InputStream;
@@ -387,19 +388,22 @@ public class MailProtocolTestTask extends Task implements Monitor {
             validate();
             try {
                 final File scriptFile = getScript();
-                final Reader reader;
-                if (scriptFile == null) {
-                    reader = new StringReader(scriptText);
-                } else {
-                    reader = new FileReader(scriptFile);
-                }
                 final ScriptedUserAdder adder = new ScriptedUserAdder(getHost(), port, MailProtocolTestTask.this);
-                adder.addUser(getUser(), getPasswd(), reader);
+                try (Reader reader = newReader(scriptFile)) {
+                    adder.addUser(getUser(), getPasswd(), reader);
+                }
             } catch (Exception e) {
                 log(e.getMessage(), Project.MSG_ERR);
                 throw new BuildException("User addition failed: \n" + e.getMessage(), e);
             }
-        } 
+        }
+
+        private Reader newReader(File scriptFile) throws FileNotFoundException {
+            if (scriptFile == null) {
+                return new StringReader(scriptText);
+            }
+            return new FileReader(scriptFile);
+        }
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/james-project/blob/3c275fe6/server/container/core/src/main/java/org/apache/james/server/core/MailImpl.java
----------------------------------------------------------------------
diff --git a/server/container/core/src/main/java/org/apache/james/server/core/MailImpl.java b/server/container/core/src/main/java/org/apache/james/server/core/MailImpl.java
index 816c9e6..af13b67 100644
--- a/server/container/core/src/main/java/org/apache/james/server/core/MailImpl.java
+++ b/server/container/core/src/main/java/org/apache/james/server/core/MailImpl.java
@@ -754,13 +754,14 @@ public class MailImpl implements Disposable, Mail {
      */
     private static Object cloneSerializableObject(Object o) throws IOException, ClassNotFoundException {
         ByteArrayOutputStream b = new ByteArrayOutputStream();
-        ObjectOutputStream out = new ObjectOutputStream(b);
-        out.writeObject(o);
-        out.flush();
-        out.close();
+        try (ObjectOutputStream out = new ObjectOutputStream(b)) {
+            out.writeObject(o);
+            out.flush();
+        }
         ByteArrayInputStream bi = new ByteArrayInputStream(b.toByteArray());
-        ObjectInputStream in = new ObjectInputStream(bi);
-        return in.readObject();
+        try (ObjectInputStream in = new ObjectInputStream(bi)) {
+            return in.readObject();
+        }
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/james-project/blob/3c275fe6/server/data/data-hbase/src/main/java/org/apache/james/system/hbase/TablePool.java
----------------------------------------------------------------------
diff --git a/server/data/data-hbase/src/main/java/org/apache/james/system/hbase/TablePool.java b/server/data/data-hbase/src/main/java/org/apache/james/system/hbase/TablePool.java
index c83a90d..b1ca529 100644
--- a/server/data/data-hbase/src/main/java/org/apache/james/system/hbase/TablePool.java
+++ b/server/data/data-hbase/src/main/java/org/apache/james/system/hbase/TablePool.java
@@ -116,8 +116,7 @@ public class TablePool {
      * @throws IOException
      */
     private static void ensureTable(byte[] tableName, byte[] columnFamilyName) throws IOException {
-        HBaseAdmin hbaseAdmin = new HBaseAdmin(configuration);
-        try {
+        try (HBaseAdmin hbaseAdmin = new HBaseAdmin(configuration)) {
             if (!hbaseAdmin.tableExists(tableName)) {
                 HTableDescriptor desc = new HTableDescriptor(tableName);
                 HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(columnFamilyName);
@@ -125,8 +124,6 @@ public class TablePool {
                 desc.addFamily(hColumnDescriptor);
                 hbaseAdmin.createTable(desc);
             }
-        } finally {
-            hbaseAdmin.close();
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/james-project/blob/3c275fe6/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/JDBCRecipientRewriteTable.java
----------------------------------------------------------------------
diff --git a/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/JDBCRecipientRewriteTable.java b/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/JDBCRecipientRewriteTable.java
index 3cdf57f..5e62058 100644
--- a/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/JDBCRecipientRewriteTable.java
+++ b/server/mailet/mailets/src/main/java/org/apache/james/transport/mailets/JDBCRecipientRewriteTable.java
@@ -144,10 +144,8 @@ public class JDBCRecipientRewriteTable extends AbstractRecipientRewriteTable {
         int pos = datasourceName.indexOf("/");
         String tableName = datasourceName.substring(pos + 1);
         datasourceName = datasourceName.substring(0, pos);
-        Connection conn = null;
 
-        try {
-            conn = datasource.getConnection();
+        try (Connection conn = datasource.getConnection()) {
 
             // Check if the required table exists. If not, complain.
             DatabaseMetaData dbMetaData = conn.getMetaData();
@@ -165,8 +163,6 @@ public class JDBCRecipientRewriteTable extends AbstractRecipientRewriteTable {
             throw me;
         } catch (Exception e) {
             throw new MessagingException("Error initializing JDBCRecipientRewriteTable", e);
-        } finally {
-            theJDBCUtil.closeJDBCConnection(conn);
         }
     }
 
@@ -179,35 +175,25 @@ public class JDBCRecipientRewriteTable extends AbstractRecipientRewriteTable {
      */
     @Override
     protected void mapRecipients(Map<MailAddress, String> recipientsMap) throws MessagingException {
-        Connection conn = null;
-        PreparedStatement mappingStmt = null;
 
         Collection<MailAddress> recipients = recipientsMap.keySet();
 
-        try {
-            conn = datasource.getConnection();
-            mappingStmt = conn.prepareStatement(query);
-
-            for (MailAddress recipient : recipients) {
-                ResultSet mappingRS = null;
-                try {
+        try (Connection conn = datasource.getConnection()) {
+            try (PreparedStatement mappingStmt = conn.prepareStatement(query)) {
+                for (MailAddress recipient : recipients) {
                     mappingStmt.setString(1, recipient.getLocalPart());
                     mappingStmt.setString(2, recipient.getDomain().asString());
                     mappingStmt.setString(3, recipient.getDomain().asString());
-                    mappingRS = mappingStmt.executeQuery();
-                    if (mappingRS.next()) {
-                        String targetString = mappingRS.getString(1);
-                        recipientsMap.put(recipient, targetString);
+                    try (ResultSet mappingRS = mappingStmt.executeQuery()) {
+                        if (mappingRS.next()) {
+                            String targetString = mappingRS.getString(1);
+                            recipientsMap.put(recipient, targetString);
+                        }
                     }
-                } finally {
-                    theJDBCUtil.closeJDBCResultSet(mappingRS);
                 }
             }
         } catch (SQLException sqle) {
             throw new MessagingException("Error accessing database", sqle);
-        } finally {
-            theJDBCUtil.closeJDBCStatement(mappingStmt);
-            theJDBCUtil.closeJDBCConnection(conn);
         }
     }
 

http://git-wip-us.apache.org/repos/asf/james-project/blob/3c275fe6/server/queue/queue-jms/src/main/java/org/apache/james/queue/jms/JMSMailQueue.java
----------------------------------------------------------------------
diff --git a/server/queue/queue-jms/src/main/java/org/apache/james/queue/jms/JMSMailQueue.java b/server/queue/queue-jms/src/main/java/org/apache/james/queue/jms/JMSMailQueue.java
index 0517d59..f6f9838 100644
--- a/server/queue/queue-jms/src/main/java/org/apache/james/queue/jms/JMSMailQueue.java
+++ b/server/queue/queue-jms/src/main/java/org/apache/james/queue/jms/JMSMailQueue.java
@@ -476,60 +476,48 @@ public class JMSMailQueue implements ManageableMailQueue, JMSSupport, MailPriori
 
     @Override
     public long getSize() throws MailQueueException {
-        QueueBrowser browser = null;
-        try {
-            browser = session.createBrowser(queue);
+        try (QueueBrowser browser = session.createBrowser(queue)) {
             Enumeration<?> enumeration = browser.getEnumeration();
             return Iterators.size(new EnumerationIterator(enumeration));
         } catch (Exception e) {
             LOGGER.error("Unable to get size of queue {}", queueName, e);
             throw new MailQueueException("Unable to get size of queue " + queueName, e);
-        } finally {
-            closeBrowser(browser);
         }
     }
 
     @Override
     public long flush() throws MailQueueException {
-        Session session = null;
-        Message message = null;
-        MessageConsumer consumer = null;
-        MessageProducer producer = null;
         boolean first = true;
         long count = 0;
-        try {
-
-            session = connection.createSession(true, Session.SESSION_TRANSACTED);
+        try (Session session = connection.createSession(true, Session.SESSION_TRANSACTED)) {
             Queue queue = session.createQueue(queueName);
-            consumer = session.createConsumer(queue);
-            producer = session.createProducer(queue);
-
-            while (first || message != null) {
-                if (first) {
-                    // give the consumer 2000 ms to receive messages
-                    message = consumer.receive(2000);
-                } else {
-                    message = consumer.receiveNoWait();
-                }
-                first = false;
+            try (MessageConsumer consumer = session.createConsumer(queue)) {
+                try (MessageProducer producer = session.createProducer(queue)) {
+
+                    Message message = null;
+                    while (first || message != null) {
+                        if (first) {
+                            // give the consumer 2000 ms to receive messages
+                            message = consumer.receive(2000);
+                        } else {
+                            message = consumer.receiveNoWait();
+                        }
+                        first = false;
 
-                if (message != null) {
-                    Message m = copy(session, message);
-                    m.setBooleanProperty(FORCE_DELIVERY, true);
-                    producer.send(m, message.getJMSDeliveryMode(), message.getJMSPriority(), message.getJMSExpiration());
-                    count++;
+                        if (message != null) {
+                            Message m = copy(session, message);
+                            m.setBooleanProperty(FORCE_DELIVERY, true);
+                            producer.send(m, message.getJMSDeliveryMode(), message.getJMSPriority(), message.getJMSExpiration());
+                            count++;
+                        }
+                    }
+                    session.commit();
+                    return count;
                 }
             }
-            session.commit();
-            return count;
         } catch (Exception e) {
             LOGGER.error("Unable to flush mail", e);
-            rollback(session);
             throw new MailQueueException("Unable to get size of queue " + queueName, e);
-        } finally {
-            closeConsumer(consumer);
-            closeProducer(producer);
-            closeSession(session);
         }
     }
 
@@ -553,37 +541,32 @@ public class JMSMailQueue implements ManageableMailQueue, JMSSupport, MailPriori
      * @return messages
      */
     public List<Message> removeWithSelector(String selector) throws MailQueueException {
-        Session session = null;
-        Message message = null;
-        MessageConsumer consumer = null;
         boolean first = true;
         List<Message> messages = new ArrayList<>();
 
         try {
-            session = connection.createSession(true, Session.SESSION_TRANSACTED);
-            Queue queue = session.createQueue(queueName);
-            consumer = session.createConsumer(queue, selector);
-            while (first || message != null) {
-                if (first) {
-                    // give the consumer 2000 ms to receive messages
-                    message = consumer.receive(2000);
-                } else {
-                    message = consumer.receiveNoWait();
-                }
-                first = false;
-                if (message != null) {
-                    messages.add(message);
+            try (Session session = connection.createSession(true, Session.SESSION_TRANSACTED)) {
+                Queue queue = session.createQueue(queueName);
+                try (MessageConsumer consumer = session.createConsumer(queue, selector)) {
+                    Message message = null;
+                    while (first || message != null) {
+                        if (first) {
+                            // give the consumer 2000 ms to receive messages
+                            message = consumer.receive(2000);
+                        } else {
+                            message = consumer.receiveNoWait();
+                        }
+                        first = false;
+                        if (message != null) {
+                            messages.add(message);
+                        }
+                    }
                 }
+                session.commit();
             }
-            session.commit();
             return messages;
         } catch (Exception e) {
-            rollback(session);
             throw new MailQueueException("Unable to remove mails", e);
-
-        } finally {
-            closeConsumer(consumer);
-            closeSession(session);
         }
     }
 


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