geronimo-scm mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From a..@apache.org
Subject svn commit: r1743397 [16/17] - in /geronimo/javamail/trunk/geronimo-javamail_1.5: ./ geronimo-javamail_1.5_mail/ geronimo-javamail_1.5_mail/src/ geronimo-javamail_1.5_mail/src/site/ geronimo-javamail_1.5_mail/src/site/apt/ geronimo-javamail_1.5_provide...
Date Wed, 11 May 2016 16:49:39 GMT
Added: geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/handlers/TextHtmlTest.java
URL: http://svn.apache.org/viewvc/geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/handlers/TextHtmlTest.java?rev=1743397&view=auto
==============================================================================
--- geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/handlers/TextHtmlTest.java (added)
+++ geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/handlers/TextHtmlTest.java Wed May 11 16:49:36 2016
@@ -0,0 +1,40 @@
+/**
+ *  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.geronimo.javamail.handlers;
+
+import java.awt.datatransfer.DataFlavor;
+
+/**
+ * @version $Rev: 669902 $ $Date: 2008-06-20 10:04:41 -0400 (Fri, 20 Jun 2008) $
+ */
+public class TextHtmlTest extends AbstractHandler {
+    public void testDataFlavor() {
+        DataFlavor[] flavours = dch.getTransferDataFlavors();
+        assertEquals(1, flavours.length);
+        DataFlavor flavor = flavours[0];
+        assertEquals(String.class, flavor.getRepresentationClass());
+        assertEquals("text/html", flavor.getMimeType());
+        assertEquals("HTML Text", flavor.getHumanPresentableName());
+    }
+    
+    protected void setUp() throws Exception {
+        super.setUp();
+        
+        dch = new TextHtmlHandler();
+        mimeType = "text/html"; 
+    }
+}

Added: geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/handlers/TextPlainTest.java
URL: http://svn.apache.org/viewvc/geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/handlers/TextPlainTest.java?rev=1743397&view=auto
==============================================================================
--- geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/handlers/TextPlainTest.java (added)
+++ geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/handlers/TextPlainTest.java Wed May 11 16:49:36 2016
@@ -0,0 +1,40 @@
+/**
+ *  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.geronimo.javamail.handlers;
+
+import java.awt.datatransfer.DataFlavor;
+
+/**
+ * @version $Rev: 669902 $ $Date: 2008-06-20 10:04:41 -0400 (Fri, 20 Jun 2008) $
+ */
+public class TextPlainTest extends AbstractHandler {
+    public void testDataFlavor() {
+        DataFlavor[] flavours = dch.getTransferDataFlavors();
+        assertEquals(1, flavours.length);
+        DataFlavor flavor = flavours[0];
+        assertEquals(String.class, flavor.getRepresentationClass());
+        assertEquals("text/plain", flavor.getMimeType());
+        assertEquals("Plain Text", flavor.getHumanPresentableName());
+    }
+    
+    protected void setUp() throws Exception {
+        super.setUp();
+        
+        dch = new TextPlainHandler();
+        mimeType = "text/plain"; 
+    }
+}

Added: geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/handlers/TextXmlTest.java
URL: http://svn.apache.org/viewvc/geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/handlers/TextXmlTest.java?rev=1743397&view=auto
==============================================================================
--- geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/handlers/TextXmlTest.java (added)
+++ geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/handlers/TextXmlTest.java Wed May 11 16:49:36 2016
@@ -0,0 +1,40 @@
+/**
+ *  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.geronimo.javamail.handlers;
+
+import java.awt.datatransfer.DataFlavor;
+
+/**
+ * @version $Rev: 669902 $ $Date: 2008-06-20 10:04:41 -0400 (Fri, 20 Jun 2008) $
+ */
+public class TextXmlTest extends AbstractHandler {
+    public void testDataFlavor() {
+        DataFlavor[] flavours = dch.getTransferDataFlavors();
+        assertEquals(1, flavours.length);
+        DataFlavor flavor = flavours[0];
+        assertEquals(String.class, flavor.getRepresentationClass());
+        assertEquals("text/xml", flavor.getMimeType());
+        assertEquals("XML Text", flavor.getHumanPresentableName());
+    }
+    
+    protected void setUp() throws Exception {
+        super.setUp();
+        
+        dch = new TextXmlHandler();
+        mimeType = "text/xml"; 
+    }
+}

Added: geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/issues/GERONIMO6480Test.java
URL: http://svn.apache.org/viewvc/geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/issues/GERONIMO6480Test.java?rev=1743397&view=auto
==============================================================================
--- geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/issues/GERONIMO6480Test.java (added)
+++ geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/issues/GERONIMO6480Test.java Wed May 11 16:49:36 2016
@@ -0,0 +1,139 @@
+/**
+ *  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.geronimo.javamail.issues;
+
+import java.io.File;
+import java.util.Properties;
+
+import javax.activation.DataHandler;
+import javax.activation.FileDataSource;
+import javax.mail.BodyPart;
+import javax.mail.Folder;
+import javax.mail.Message;
+import javax.mail.Session;
+import javax.mail.Store;
+import javax.mail.Transport;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeBodyPart;
+import javax.mail.internet.MimeMessage;
+import javax.mail.internet.MimeMultipart;
+
+import junit.framework.Assert;
+
+import org.apache.geronimo.javamail.testserver.AbstractProtocolTest;
+
+public class GERONIMO6480Test extends AbstractProtocolTest {
+
+    public void testGERONIMO6480_0() throws Exception {
+        BodyPart attachmentPart = new MimeBodyPart();
+        attachmentPart.setDataHandler(new DataHandler(new FileDataSource(getAbsoluteFilePathFromClassPath("pdf-test.pdf"))));
+        attachmentPart.setFileName("test.pdf");
+        String contentType = getSendedAttachmentContentType(attachmentPart);
+        Assert.assertEquals("application/octet-stream; name=test.pdf".toLowerCase(), contentType.toLowerCase());
+        // "text/plain; name=test.pdf" with Geronimo because setFileName force it to 'text/plain' when adding the 'name=' part instead of keeping it null
+    }
+
+    public void testGERONIMO6480_1() throws Exception {
+        BodyPart attachmentPart = new MimeBodyPart();
+        attachmentPart.addHeader("Content-Type", "aplication/pdf");
+        // setDataHandler reset "Content-Type" so equivalent to previous test
+        attachmentPart.setDataHandler(new DataHandler(new FileDataSource(getAbsoluteFilePathFromClassPath("pdf-test.pdf"))));
+        attachmentPart.setFileName("test.pdf");
+        String contentType = getSendedAttachmentContentType(attachmentPart);
+        Assert.assertEquals("application/octet-stream; name=test.pdf".toLowerCase(), contentType.toLowerCase());
+        // "text/plain; name=test.pdf" with Geronimo because setFileName force it to 'text/plain' when adding the 'name=' part instead of keeping it null
+    }
+
+    public void testGERONIMO6480_2() throws Exception {
+        BodyPart attachmentPart = new MimeBodyPart();
+        attachmentPart.setDataHandler(new DataHandler(new FileDataSource(getAbsoluteFilePathFromClassPath("pdf-test.pdf"))));
+        attachmentPart.addHeader("Content-Type", "aplication/pdf");
+        attachmentPart.setFileName("test.pdf");
+        String contentType = getSendedAttachmentContentType(attachmentPart);
+        Assert.assertEquals("aplication/pdf; name=test.pdf".toLowerCase(), contentType.toLowerCase());
+    }
+
+    public void testGERONIMO6480_3() throws Exception {
+        System.setProperty("mail.mime.setcontenttypefilename", Boolean.FALSE.toString());
+        try {
+            BodyPart attachmentPart = new MimeBodyPart();
+            attachmentPart.setDataHandler(new DataHandler(new FileDataSource(getAbsoluteFilePathFromClassPath("pdf-test.pdf"))));
+            attachmentPart.setFileName("test.pdf");
+            String contentType = getSendedAttachmentContentType(attachmentPart);
+            Assert.assertEquals("application/octet-stream; name=test.pdf".toLowerCase(), contentType.toLowerCase());
+        } finally {
+            System.setProperty("mail.mime.setcontenttypefilename", Boolean.TRUE.toString());
+        }
+    }
+
+    public void testGERONIMO6480_4() throws Exception {
+        BodyPart attachmentPart = new MimeBodyPart();
+        attachmentPart.setFileName("test.pdf");
+        attachmentPart.setDataHandler(new DataHandler(new FileDataSource(getAbsoluteFilePathFromClassPath("pdf-test.pdf"))));
+        String contentType = getSendedAttachmentContentType(attachmentPart);
+        Assert.assertEquals("application/octet-stream; name=test.pdf".toLowerCase(), contentType.toLowerCase());
+    }
+
+    private File getAbsoluteFilePathFromClassPath(String filename) throws Exception {
+        return new File(GERONIMO6480Test.class.getClassLoader().getResource(filename).toURI());
+    }
+
+    private String getSendedAttachmentContentType(BodyPart attachmentPart) throws Exception {
+
+        start();
+        Properties props = new Properties();
+        props.setProperty("mail.transport.protocol", "smtp");
+        props.setProperty("mail.store.protocol", "imap");
+        props.setProperty("mail.imap.port", String.valueOf(imapConf.getListenerPort()));
+        props.setProperty("mail.smtp.port", String.valueOf(smtpConf.getListenerPort()));
+        //props.setProperty("mail.debug", "true");
+        Session session = Session.getInstance(props);
+
+        BodyPart messageBodyPart = new MimeBodyPart();
+        messageBodyPart.setText("See attachment.");
+
+        MimeMultipart multipart = new MimeMultipart();
+        multipart.addBodyPart(messageBodyPart);
+        multipart.addBodyPart(attachmentPart);
+
+        Message message = new MimeMessage(session);
+        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("test@mockserver.com"));
+        message.setSubject("Test attachment content-type");
+        message.setContent(multipart);
+
+        Transport.send(message);
+
+        return getAttachmentContentType(session);
+    }
+
+    private String getAttachmentContentType(Session session) throws Exception {
+        Store store = session.getStore();
+        store.connect("127.0.0.1", "serveruser", "serverpass");
+
+        Folder folder = store.getDefaultFolder();
+        folder = folder.getFolder("inbox");
+        folder.open(Folder.READ_ONLY);
+
+        server.ensureMsgCount(1);
+
+        Message message = folder.getMessage(1);
+        MimeMultipart multipart = (MimeMultipart) message.getContent();
+        BodyPart attachmentPart = multipart.getBodyPart(1);
+        return attachmentPart.getContentType();
+    }
+
+}

Propchange: geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/issues/GERONIMO6480Test.java
------------------------------------------------------------------------------
    svn:executable = *

Added: geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/issues/IssuesTest.java
URL: http://svn.apache.org/viewvc/geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/issues/IssuesTest.java?rev=1743397&view=auto
==============================================================================
--- geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/issues/IssuesTest.java (added)
+++ geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/issues/IssuesTest.java Wed May 11 16:49:36 2016
@@ -0,0 +1,149 @@
+/**
+ *  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.geronimo.javamail.issues;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.PrintStream;
+import java.util.Properties;
+
+import javax.activation.DataHandler;
+import javax.activation.DataSource;
+import javax.activation.FileDataSource;
+import javax.mail.Folder;
+import javax.mail.Message;
+import javax.mail.Multipart;
+import javax.mail.Session;
+import javax.mail.Store;
+import javax.mail.Transport;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeBodyPart;
+import javax.mail.internet.MimeMessage;
+import javax.mail.internet.MimeMultipart;
+
+import junit.framework.Assert;
+
+import org.apache.geronimo.javamail.testserver.AbstractProtocolTest;
+import org.apache.geronimo.javamail.testserver.MailServer;
+
+public class IssuesTest extends AbstractProtocolTest {
+
+    public void testGERONIMO6519() throws Exception {
+
+        PrintStream original = System.out;
+
+        try {
+
+            start();
+            // Setup JavaMail session
+            Properties props = new Properties();
+            props.setProperty("mail.debug", "true");
+            props.setProperty("mail.smtp.port", String.valueOf(smtpConf.getListenerPort()));
+            props.setProperty("mail.smtp.localhost", "some.full.qualified.name.com");
+
+            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+            System.setOut(new PrintStream(baos, true));
+
+            Session session = Session.getInstance(props);
+            MimeMessage message = new MimeMessage(session);
+            message.setFrom(new InternetAddress("test@localhost"));
+            message.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress("test@localhost"));
+            message.setText("test");
+
+            Transport.send(message);
+            Assert.assertTrue(baos.toString().contains("EHLO some.full.qualified.name.com"));
+
+        } finally {
+            System.setOut(original);
+        }
+
+    }
+    
+    public void testGERONIMO4594() throws Exception {
+        Assert.assertTrue(doGERONIMO4594(true, true));
+    }
+    
+    public void testGERONIMO4594Fail0() throws Exception {
+        Assert.assertFalse(doGERONIMO4594(false, true));
+    }
+    
+    public void testGERONIMO4594Fail1() throws Exception {
+        Assert.assertFalse(doGERONIMO4594(false, false));
+    }
+    
+    public void testGERONIMO4594Fail2() throws Exception {
+        Assert.assertFalse(doGERONIMO4594(true, false));
+    }
+        
+    private boolean doGERONIMO4594(boolean decode, boolean encode) throws Exception {
+
+        final String specialFileName = "encoded_filename_\u00C4\u00DC\u00D6\u0226(test).pdf";
+        
+        System.setProperty("mail.mime.decodefilename", String.valueOf(decode));
+        System.setProperty("mail.mime.encodefilename", String.valueOf(encode));
+        try {
+
+            start();
+
+            // Setup JavaMail session
+            Properties props = new Properties();
+            props.setProperty("mail.transport.protocol", "smtp");
+            props.setProperty("mail.smtp.port", String.valueOf(smtpConf.getListenerPort()));
+            props.setProperty("mail.store.protocol", "imap");
+            props.setProperty("mail.imap.port", String.valueOf(imapConf.getListenerPort()));
+            //props.setProperty("mail.debug","true");
+            Session session = Session.getInstance(props);
+
+            MimeMessage msg = new MimeMessage(session);
+            msg.setSubject("a file for you");
+            msg.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress("serveruser@localhost"));
+            msg.setFrom(new InternetAddress("serveruser@localhost"));
+
+            MimeBodyPart messageBodyPart = new MimeBodyPart();
+            Multipart multipart = new MimeMultipart();
+            messageBodyPart.setText("This is message body");
+            File file = MailServer.getAbsoluteFilePathFromClassPath("pdf-test.pdf");
+            Assert.assertTrue(file.exists());
+            DataSource source = new FileDataSource(file.getAbsoluteFile());
+            messageBodyPart.setDataHandler(new DataHandler(source));
+            messageBodyPart.setFileName(specialFileName);
+            multipart.addBodyPart(messageBodyPart);
+            msg.setContent(multipart);
+            sendMessage(msg);
+            server.ensureMsgCount(1);
+
+            Session jmsession = Session.getInstance(props);
+            Store store = jmsession.getStore();
+            store.connect("127.0.0.1", "serveruser", "serverpass");
+            Folder f = store.getFolder("INBOX");
+            f.open(Folder.READ_ONLY); //TODO STAT only when folder open???
+            Assert.assertEquals(1, f.getMessageCount());
+            Message[] messages = new Message[2];
+            messages[0] = f.getMessage(1);
+            boolean match = specialFileName.equals(((Multipart) messages[0].getContent()).getBodyPart(0).getFileName());
+            f.close(false);
+            store.close();
+            return match;
+
+        } finally {
+            System.setProperty("mail.mime.decodefilename", "false");
+            System.setProperty("mail.mime.encodefilename", "false");
+        }
+
+    }
+
+}

Added: geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/store/imap/AuthenticationTest.java
URL: http://svn.apache.org/viewvc/geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/store/imap/AuthenticationTest.java?rev=1743397&view=auto
==============================================================================
--- geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/store/imap/AuthenticationTest.java (added)
+++ geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/store/imap/AuthenticationTest.java Wed May 11 16:49:36 2016
@@ -0,0 +1,208 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.geronimo.javamail.store.imap;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.Properties;
+
+import javax.mail.MessagingException;
+import javax.mail.Session;
+import javax.mail.Store;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+import org.apache.geronimo.mail.util.Base64;
+import org.apache.james.protocols.lib.PortUtil;
+
+public class AuthenticationTest extends TestCase {
+
+    public void testImplUsage() throws Exception {
+
+        //check that we load our mail impl
+        Properties props = new Properties();
+        props.setProperty("mail.store.protocol", "imap");
+        Session jmsession = Session.getInstance(props);
+        Assert.assertEquals(org.apache.geronimo.javamail.store.imap.IMAPStore.class, jmsession.getStore().getClass());
+        
+    }
+    
+    public void testAuthenticatePlain() throws Exception {
+
+        final int listenerPort = PortUtil.getNonPrivilegedPort();
+        //greenmail does not have AUTHENTICATE "PLAIN" support
+        FakeImapAuthPlainServer fs = new FakeImapAuthPlainServer(null, "user", "pass");
+        fs.startServer(listenerPort);
+        // Setup JavaMail session
+        Properties props = new Properties();
+        props.setProperty("mail.imap.port", String.valueOf(listenerPort));
+        props.setProperty("mail.debug", String.valueOf(true));
+        props.setProperty("mail.debug.auth", String.valueOf(true));
+
+        Session session = Session.getInstance(props);
+        Store store = session.getStore("imap");
+        store.connect("localhost", "user", "pass");
+        assertTrue(store.isConnected());
+        fs.join();
+        assertNull(fs.exception);
+    }
+
+    public void testAuthenticatePlainFail() throws Exception {
+
+        final int listenerPort = PortUtil.getNonPrivilegedPort();
+        //greenmail does not have AUTHENTICATE "PLAIN" support
+        FakeImapAuthPlainServer fs = new FakeImapAuthPlainServer(null, "user", "pass");
+        fs.startServer(listenerPort);
+        // Setup JavaMail session
+        Properties props = new Properties();
+        props.setProperty("mail.imap.port", String.valueOf(listenerPort));
+        props.setProperty("mail.debug", String.valueOf(true));
+        props.setProperty("mail.debug.auth", String.valueOf(true));
+        Session session = Session.getInstance(props);
+        Store store = session.getStore("imap");
+
+        try {
+
+            store.connect("localhost", "userXXX", "passXXX");
+            fail();
+        } catch (MessagingException e) {
+            //expected
+        }
+    }
+
+    public void testAuthenticatePlainAuthzid() throws Exception {
+
+        final int listenerPort = PortUtil.getNonPrivilegedPort();
+        //greenmail does not have AUTHENTICATE "PLAIN" support
+        FakeImapAuthPlainServer fs = new FakeImapAuthPlainServer("authzid", "user", "pass");
+        fs.startServer(listenerPort);
+        // Setup JavaMail session
+        Properties props = new Properties();
+        props.setProperty("mail.imap.port", String.valueOf(listenerPort));
+        props.setProperty("mail.debug", String.valueOf(true));
+        props.setProperty("mail.debug.auth", String.valueOf(true));
+        props.setProperty("mail.imap.sasl.authorizationid", "authzid");
+
+        Session session = Session.getInstance(props);
+        Store store = session.getStore("imap");
+        store.connect("localhost", "user", "pass");
+        assertTrue(store.isConnected());
+        fs.join();
+        assertNull(fs.exception);
+    }
+
+
+    private class FakeImapAuthPlainServer extends Thread{
+
+        private ServerSocket serverSocket;
+        private Socket socket;
+        private String authzid;
+        private String username;
+        private String password;
+        Exception exception;
+
+        private FakeImapAuthPlainServer(String authzid, String username, String password) {
+            this.password = password;
+            this.username = username;
+            this.authzid = authzid==null?"":authzid;
+        }
+
+        void startServer(int port) throws IOException {
+
+            serverSocket = new ServerSocket(port);
+            this.setDaemon(false);
+            this.start();
+
+        }
+
+
+        public void run() {
+            try {
+                socket = serverSocket.accept();
+                BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
+                PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
+                pw.write("* OK ready\r\n");
+                pw.flush();
+                String tag = br.readLine().split(" ")[0];
+                pw.write("* OK IMAP4rev1 Server ready\r\n");
+                pw.write("* CAPABILITY IMAP4rev1 AUTH=PLAIN\r\n");
+                pw.write(tag+" OK CAPABILITY completed.\r\n");
+                pw.flush();
+                tag = br.readLine().split(" ")[0];
+                pw.write("+ \r\n");
+                pw.flush();
+                String authline = new String(Base64.decode(br.readLine()));
+                System.out.println("authline : "+authline );
+
+                if(!"".equals(authzid) && !(authzid+"\0"+username+"\0"+password).equals(authline)) {
+                    pw.write(tag+" BAD username password invalid.\r\n");
+                    pw.flush();
+                    return;
+                }
+
+                if("".equals(authzid) && !(username+"\0"+username+"\0"+password).equals(authline) && !("\0"+username+"\0"+password).equals(authline)) {
+                    pw.write(tag+" BAD username password invalid.\r\n");
+                    pw.flush();
+                    return;
+                }
+
+                pw.write(tag + " OK Authenticated.\r\n");
+                pw.flush();
+
+                String fin = br.readLine();
+                tag = fin.split(" ")[0];
+
+                if(fin.contains("CAPA")) {
+                    pw.write("* CAPABILITY IMAP4rev1 AUTH=PLAIN\r\n");
+                    pw.write(tag+" OK CAPABILITY completed.\r\n");
+                    pw.flush();
+                    tag = br.readLine().split(" ")[0];
+                    pw.write(tag+" OK NOOP.\r\n");
+                }
+                else {
+                    pw.write(tag+" OK NOOP.\r\n");
+                }
+
+                pw.flush();
+
+            } catch (Exception e) {
+                exception = e;
+            }finally {
+
+                try {
+                    socket.close();
+                } catch (Exception e) {
+                    //ignore
+                }
+
+                try {
+                    serverSocket.close();
+                } catch (Exception e) {
+                    //ignore
+                }
+
+            }
+        }
+    }
+
+}

Added: geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/store/imap/IMAPStoreTest.java
URL: http://svn.apache.org/viewvc/geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/store/imap/IMAPStoreTest.java?rev=1743397&view=auto
==============================================================================
--- geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/store/imap/IMAPStoreTest.java (added)
+++ geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/store/imap/IMAPStoreTest.java Wed May 11 16:49:36 2016
@@ -0,0 +1,89 @@
+/**
+ *  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.geronimo.javamail.store.imap;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.util.Properties;
+
+import javax.mail.Folder;
+import javax.mail.Message;
+import javax.mail.Session;
+import javax.mail.Store;
+import javax.mail.internet.MimeMessage;
+import javax.mail.internet.MimeMultipart;
+
+import org.apache.geronimo.javamail.testserver.AbstractProtocolTest;
+
+
+public class IMAPStoreTest extends AbstractProtocolTest {
+    
+    public void testSimple() throws Exception {
+       
+        start();
+        sendTestMsgs();
+        
+        Properties props = new Properties();
+        props.setProperty("mail.imap.port", String.valueOf(imapConf.getListenerPort()));
+        props.setProperty("mail.debug", "true");
+        Session session = Session.getInstance(props);
+        
+        // Load the message from IMAP
+        Store store = session.getStore("imap");
+        store.connect("127.0.0.1", "serveruser", "serverpass");
+        Folder folder = store.getFolder("INBOX");
+        folder.open(Folder.READ_ONLY);
+        Message[] messages = new Message[2];
+        messages[0] = folder.getMessage(1);
+        messages[1] = folder.getMessage(2);
+        checkMessages(messages);
+        folder.close(false);
+        store.close();
+    }
+    
+    
+    private void checkMessages(Message[] messages) throws Exception {
+        MimeMessage msg1 = (MimeMessage)messages[0];
+        Object content = msg1.getContent();
+        assertTrue(content instanceof MimeMultipart);
+        MimeMultipart multipart = (MimeMultipart)content;
+        assertEquals("First part", multipart.getBodyPart(0).getContent());
+        assertEquals("Second part", multipart.getBodyPart(1).getContent());        
+        checkMessage(msg1);
+        
+        MimeMessage msg2 = (MimeMessage)messages[1];
+        assertEquals("Foo Bar", msg2.getContent().toString().trim());
+        checkMessage(msg2);
+    }
+    
+    private void checkMessage(MimeMessage input) throws Exception {
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        input.writeTo(out);
+        
+        Properties props = new Properties();
+        Session s = Session.getInstance(props);
+        
+        byte [] inputData = out.toByteArray();
+        System.out.println(new String(inputData, 0, inputData.length));
+        
+        MimeMessage output = new MimeMessage(s, new ByteArrayInputStream(inputData));
+        
+        assertEquals(input.getContentType().toLowerCase(), output.getContentType().toLowerCase());        
+    }
+    
+ 
+}

Added: geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/store/imap/connection/IMAPBodyStructureTest.java
URL: http://svn.apache.org/viewvc/geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/store/imap/connection/IMAPBodyStructureTest.java?rev=1743397&view=auto
==============================================================================
--- geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/store/imap/connection/IMAPBodyStructureTest.java (added)
+++ geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/store/imap/connection/IMAPBodyStructureTest.java Wed May 11 16:49:36 2016
@@ -0,0 +1,42 @@
+/**
+ *  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.geronimo.javamail.store.imap.connection;
+
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.BufferedReader;
+
+import javax.mail.internet.MimeMessage;
+
+import junit.framework.TestCase;
+import org.apache.geronimo.javamail.store.imap.IMAPStoreTest;
+
+public class IMAPBodyStructureTest extends TestCase {
+
+    public void testMultipart() throws Exception {
+        InputStream in = IMAPStoreTest.class.getResourceAsStream("/imap/multipart.bodystructure");
+        BufferedReader r = new BufferedReader(new InputStreamReader(in));
+        try {
+            IMAPResponseTokenizer tokenizer = new IMAPResponseTokenizer(r.readLine().getBytes("ISO8859-1"));
+            IMAPBodyStructure s = new IMAPBodyStructure(tokenizer);
+            assertNull(s.disposition.getDisposition());
+            assertNull(s.md5Hash);
+        } finally {
+            in.close();
+        }
+    }
+}

Added: geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/store/pop3/POP3StoreTest.java
URL: http://svn.apache.org/viewvc/geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/store/pop3/POP3StoreTest.java?rev=1743397&view=auto
==============================================================================
--- geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/store/pop3/POP3StoreTest.java (added)
+++ geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/store/pop3/POP3StoreTest.java Wed May 11 16:49:36 2016
@@ -0,0 +1,449 @@
+/**
+ *  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.geronimo.javamail.store.pop3;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.util.Properties;
+
+import javax.mail.Address;
+import javax.mail.FetchProfile;
+import javax.mail.Flags;
+import javax.mail.Flags.Flag;
+import javax.mail.Folder;
+import javax.mail.Message;
+import javax.mail.MessagingException;
+import javax.mail.Session;
+import javax.mail.Store;
+import javax.mail.Transport;
+import javax.mail.UIDFolder;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeMessage;
+import javax.mail.internet.MimeMultipart;
+
+import junit.framework.Assert;
+
+import org.apache.geronimo.javamail.testserver.AbstractProtocolTest;
+import org.apache.geronimo.javamail.testserver.MailServer.DummySocketFactory;
+
+public class POP3StoreTest extends AbstractProtocolTest {
+
+    
+    
+    
+    public void testSendRetrieve() throws Exception {
+        
+        start();
+        
+        // Setup JavaMail session
+        Properties props = new Properties();
+        props.setProperty("mail.smtp.port", String.valueOf(smtpConf.getListenerPort()));
+        props.setProperty("mail.debug","true");
+        Session session = Session.getInstance(props);
+        // Send messages for the current test to James
+        sendMessage(session, "/messages/multipart.msg");
+        sendMessage(session, "/messages/simple.msg");
+        server.ensureMsgCount(2);
+        
+        props = new Properties();
+        props.setProperty("mail.store.protocol", "pop3");
+        props.setProperty("mail.pop3.port", String.valueOf(pop3Conf.getListenerPort()));
+        props.setProperty("mail.debug", "true");
+
+        Session jmsession = Session.getInstance(props);
+        Store store = jmsession.getStore();
+        store.connect("127.0.0.1", "serveruser", "serverpass");
+        Folder f = store.getFolder("INBOX");
+        f.open(Folder.READ_ONLY); //TODO STAT only when folder open???
+        Assert.assertEquals(2, f.getMessageCount());
+        Message[] messages = new Message[2];
+        messages[0] = f.getMessage(1);
+        messages[1] = f.getMessage(2);
+        checkMessages(messages);
+        f.close(false);
+        store.close();
+    }
+    
+
+    
+    
+    private void checkMessages(Message[] messages) throws Exception {
+        MimeMessage msg1 = (MimeMessage)messages[0];
+        Object content = msg1.getContent();
+        assertTrue(content instanceof MimeMultipart);
+        MimeMultipart multipart = (MimeMultipart)content;
+        assertEquals("First part", multipart.getBodyPart(0).getContent());
+        assertEquals("Second part", multipart.getBodyPart(1).getContent());        
+        checkMessage(msg1);
+        
+        MimeMessage msg2 = (MimeMessage)messages[1];
+        assertEquals("Foo Bar", msg2.getContent().toString().trim());
+        checkMessage(msg2);
+    }
+    
+    private void checkMessage(MimeMessage input) throws Exception {
+        ByteArrayOutputStream out = new ByteArrayOutputStream();
+        input.writeTo(out);
+        
+        Properties props = new Properties();
+        Session s = Session.getInstance(props);
+        
+        byte [] inputData = out.toByteArray();
+        System.out.println(new String(inputData, 0, inputData.length));
+        
+        MimeMessage output = new MimeMessage(s, new ByteArrayInputStream(inputData));
+        
+        assertEquals(input.getContentType().toLowerCase(), output.getContentType().toLowerCase());        
+    }
+    
+
+    public void testStartTLS() throws Exception {
+
+        pop3Conf.enableSSL(true, false);
+
+        start();
+
+        sendTestMsgs();
+        
+        Properties props = new Properties();
+        props.setProperty("mail.store.protocol", "pop3");
+        props.setProperty("mail.pop3.port", String.valueOf(pop3Conf.getListenerPort()));
+        props.setProperty("mail.debug", "true");
+        props.setProperty("mail.pop3.starttls.required", "true");
+        props.setProperty("mail.pop3.ssl.trust", "*");
+
+        Session jmsession = Session.getInstance(props);
+        Store store = jmsession.getStore();
+        store.connect("127.0.0.1", "serveruser", "serverpass");
+        Folder f = store.getFolder("INBOX");
+        f.open(Folder.READ_ONLY); //TODO STAT only when folder open???
+        Assert.assertEquals(2, f.getMessageCount());
+        f.close(false);
+        store.close();
+
+    }
+
+    public void testAPOP() throws Exception {
+
+        pop3Conf.enableSSL(true, false);
+
+        start();
+        sendTestMsgs();
+        
+        Properties props = new Properties();
+        props.setProperty("mail.store.protocol", "pop3");
+        props.setProperty("mail.pop3.port", String.valueOf(pop3Conf.getListenerPort()));
+        props.setProperty("mail.debug", "true");
+        props.setProperty("mail.pop3.apop.enable", "true");
+
+        Session jmsession = Session.getInstance(props);
+        Store store = jmsession.getStore();
+        store.connect("127.0.0.1", "serveruser", "serverpass");
+        Folder f = store.getFolder("INBOX");
+        f.open(Folder.READ_ONLY); //TODO STAT only when folder open???
+        Assert.assertEquals(2, f.getMessageCount());
+        f.close(false);
+        store.close();
+
+    }
+
+    public void testFetch() throws Exception {
+
+        
+        pop3Conf.enableSSL(true, false);
+
+        start();
+        sendTestMsgs();
+        
+        Properties props = new Properties();
+        props.setProperty("mail.store.protocol", "pop3");
+        props.setProperty("mail.pop3.port", String.valueOf(pop3Conf.getListenerPort()));
+        props.setProperty("mail.debug", "true");
+
+        Session jmsession = Session.getInstance(props);
+        Store store = jmsession.getStore();
+        store.connect("127.0.0.1", "serveruser", "serverpass");
+        Folder f = store.getFolder("INBOX");
+        f.open(Folder.READ_ONLY); //TODO STAT only when folder open???
+        FetchProfile fp = new FetchProfile();
+        fp.add(UIDFolder.FetchProfileItem.UID);
+        fp.add(FetchProfile.Item.CONTENT_INFO);
+        
+        Message[] msgs = f.getMessages();
+        ByteArrayOutputStream bout = new ByteArrayOutputStream();
+        Assert.assertEquals(2, msgs.length);
+        
+        f.fetch(msgs, fp);
+        Assert.assertEquals(2, f.getMessageCount());
+        
+        for (int i = 0; i < msgs.length; i++) {
+            Message message = msgs[i];
+            message.writeTo(bout);
+            String msg = bout.toString();
+            Assert.assertNotNull(msg);
+            int num = message.getMessageNumber();
+            Assert.assertTrue(num > 0);
+            String uid = ((POP3Folder) f).getUID(message);
+            Assert.assertNotNull(uid);
+            Assert.assertTrue(!uid.isEmpty());
+        }
+        
+        f.close(false);
+        store.close();
+
+    }
+    
+    
+    
+    public void testDelete() throws Exception {
+
+        
+        pop3Conf.enableSSL(true, false);
+
+        start();
+        sendTestMsgs();
+        
+        Properties props = new Properties();
+        props.setProperty("mail.store.protocol", "pop3");
+        props.setProperty("mail.pop3.port", String.valueOf(pop3Conf.getListenerPort()));
+        props.setProperty("mail.debug", "true");
+
+        Session jmsession = Session.getInstance(props);
+        Store store = jmsession.getStore();
+        store.connect("127.0.0.1", "serveruser", "serverpass");
+        Folder f = store.getFolder("INBOX");
+        f.open(Folder.READ_WRITE); //TODO STAT only when folder open???
+        Assert.assertEquals(2, f.getMessageCount());
+        Message[] msgs =  f.getMessages();
+        f.setFlags(msgs, new Flags(Flag.DELETED), true);
+        Assert.assertEquals(2, f.getMessageCount());
+        f.getMessage(1).getSubject(); //should fail
+        //Assert.assertEquals(2, f.expunge());
+        f.close(false);
+        f.open(Folder.READ_ONLY); //TODO STAT only when folder open???
+        Assert.assertEquals(0, f.getMessageCount());
+        store.close();
+
+    }
+    
+    
+    
+    public void testStartTLSFail() throws Exception {
+
+        
+        pop3Conf.enableSSL(false, false);
+
+        start();
+        sendTestMsgs();
+        
+        Properties props = new Properties();
+        props.setProperty("mail.store.protocol", "pop3");
+        props.setProperty("mail.pop3.port", String.valueOf(pop3Conf.getListenerPort()));
+        props.setProperty("mail.debug", "true");
+        props.setProperty("mail.pop3.starttls.required", "true");
+        props.setProperty("mail.pop3.ssl.trust", "*");
+
+        Session jmsession = Session.getInstance(props);
+        Store store = jmsession.getStore();
+        try {
+            store.connect("127.0.0.1", "serveruser", "serverpass");
+            fail();
+        } catch (MessagingException e) {
+            //Expected
+        }
+    }
+
+    public void testSSLEnable() throws Exception {
+
+        
+        pop3Conf.enableSSL(false, true);
+
+        start();
+        sendTestMsgs();
+
+        Properties props = new Properties();
+        props.setProperty("mail.store.protocol", "pop3");
+        props.setProperty("mail.pop3.port", String.valueOf(pop3Conf.getListenerPort()));
+        props.setProperty("mail.debug", "true");
+        props.setProperty("mail.pop3.ssl.enable", "true");
+        props.setProperty("mail.pop3.ssl.trust", "*");
+
+        Session jmsession = Session.getInstance(props);
+        Store store = jmsession.getStore();
+        store.connect("127.0.0.1", "serveruser", "serverpass");
+        Folder f = store.getFolder("INBOX");
+        f.open(Folder.READ_ONLY); //TODO STAT only when folder open???
+        Assert.assertEquals(2, f.getMessageCount());
+        f.close(false);
+        store.close();
+
+    }
+
+    public void testSSLPop3s() throws Exception {
+
+        
+        pop3Conf.enableSSL(false, true);
+
+        start();
+        sendTestMsgs();
+
+        Properties props = new Properties();
+        props.setProperty("mail.store.protocol", "pop3s");
+        props.setProperty("mail.pop3s.port", String.valueOf(pop3Conf.getListenerPort()));
+        props.setProperty("mail.debug", "true");
+        props.setProperty("mail.pop3s.ssl.trust", "*");
+
+        Session jmsession = Session.getInstance(props);
+        Store store = jmsession.getStore();
+        store.connect("127.0.0.1", "serveruser", "serverpass");
+        Folder f = store.getFolder("INBOX");
+        f.open(Folder.READ_ONLY); //TODO STAT only when folder open???
+        Assert.assertEquals(2, f.getMessageCount());
+        f.close(false);
+        store.close();
+
+    }
+    
+    public void testSSLPop3sFactoryClass() throws Exception {
+
+        
+        pop3Conf.enableSSL(false, true);
+
+        start();
+        sendTestMsgs();
+
+        Properties props = new Properties();
+        props.setProperty("mail.store.protocol", "pop3s");
+        props.setProperty("mail.pop3s.port", String.valueOf(pop3Conf.getListenerPort()));
+        props.setProperty("mail.debug", "true");
+        props.setProperty("mail.pop3s.ssl.trust", "*");
+        props.setProperty("mail.pop3s.ssl.socketFactory.class", DummySocketFactory.class.getName());
+       
+
+        Session jmsession = Session.getInstance(props);
+        Store store = jmsession.getStore();
+        try {
+            store.connect("127.0.0.1", "serveruser", "serverpass");
+            fail();
+        } catch (MessagingException e) {
+            Assert.assertEquals("dummy socket factory", e.getCause().getCause().getMessage());
+            
+            //Expected
+        }
+
+        
+        
+    }
+
+    public void testSSLPop3sFactoryInstance() throws Exception {
+
+        
+        pop3Conf.enableSSL(false, true);
+
+        start();
+        sendTestMsgs();
+
+        Properties props = new Properties();
+        props.setProperty("mail.store.protocol", "pop3s");
+        props.setProperty("mail.pop3s.port", String.valueOf(pop3Conf.getListenerPort()));
+        props.setProperty("mail.debug", "true");
+        props.setProperty("mail.pop3s.ssl.trust", "*");
+        props.put("mail.pop3s.ssl.socketFactory", new DummySocketFactory());
+       
+
+        Session jmsession = Session.getInstance(props);
+        Store store = jmsession.getStore();
+        try {
+            store.connect("127.0.0.1", "serveruser", "serverpass");
+            fail();
+        } catch (MessagingException e) {
+            Assert.assertEquals("dummy socket factory", e.getCause().getMessage());
+            
+            //Expected
+        }
+
+    }
+    
+    public void testSSLPop3sNotEnabled() throws Exception {
+
+        
+        pop3Conf.enableSSL(false, false);
+
+        start();
+        sendTestMsgs();
+
+        Properties props = new Properties();
+        props.setProperty("mail.store.protocol", "pop3s");
+        props.setProperty("mail.pop3s.port", String.valueOf(pop3Conf.getListenerPort()));
+        props.setProperty("mail.debug", "true");
+        props.setProperty("mail.pop3s.ssl.trust", "*");
+        props.setProperty("mail.pop3s.ssl.enable", "false");
+
+        Session jmsession = Session.getInstance(props);
+        Store store = jmsession.getStore();
+        store.connect("127.0.0.1", "serveruser", "serverpass");
+        Folder f = store.getFolder("INBOX");
+        f.open(Folder.READ_ONLY); //TODO STAT only when folder open???
+        Assert.assertEquals(2, f.getMessageCount());
+        f.close(false);
+        store.close();
+
+    }
+    
+    public void testPop3GetMsgs() throws Exception {
+
+        
+        pop3Conf.enableSSL(false, false);
+
+        start();
+        sendTestMsgs();
+
+        Properties props = new Properties();
+        props.setProperty("mail.store.protocol", "pop3");
+        props.setProperty("mail.pop3.port", String.valueOf(pop3Conf.getListenerPort()));
+        props.setProperty("mail.debug", "true");
+
+        Session jmsession = Session.getInstance(props);
+        Store store = jmsession.getStore();
+        store.connect("127.0.0.1", "serveruser", "serverpass");
+        Folder f = store.getFolder("INBOX");
+        f.open(Folder.READ_ONLY); //TODO STAT only when folder open???
+        
+        
+        Message[] msgs =  f.getMessages();
+        ByteArrayOutputStream bout = new ByteArrayOutputStream();
+        Assert.assertEquals(2, msgs.length);
+        
+        for (int i = 0; i < msgs.length; i++) {
+            Message message = msgs[i];
+            message.writeTo(bout);
+            String msg = bout.toString();
+            Assert.assertNotNull(msg);
+            int num = message.getMessageNumber();
+            Assert.assertTrue(num > 0);
+            String uid = ((POP3Folder) f).getUID(message);
+            Assert.assertNotNull(uid);
+            Assert.assertTrue(!uid.isEmpty());
+        }
+        
+        f.close(false);
+        store.close();
+
+    }
+
+}

Added: geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/testserver/AbstractProtocolTest.java
URL: http://svn.apache.org/viewvc/geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/testserver/AbstractProtocolTest.java?rev=1743397&view=auto
==============================================================================
--- geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/testserver/AbstractProtocolTest.java (added)
+++ geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/testserver/AbstractProtocolTest.java Wed May 11 16:49:36 2016
@@ -0,0 +1,115 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.geronimo.javamail.testserver;
+
+import java.io.InputStream;
+import java.util.Properties;
+
+import javax.mail.Address;
+import javax.mail.Session;
+import javax.mail.Transport;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeMessage;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+import org.apache.geronimo.javamail.store.pop3.POP3StoreTest;
+
+public abstract class AbstractProtocolTest extends TestCase {
+
+    protected MailServer server = new MailServer();
+    protected MailServer.Pop3TestConfiguration pop3Conf;
+    protected MailServer.SmtpTestConfiguration smtpConf;
+    protected MailServer.ImapTestConfiguration imapConf;
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        pop3Conf = new MailServer.Pop3TestConfiguration();
+        smtpConf = new MailServer.SmtpTestConfiguration();
+        imapConf = new MailServer.ImapTestConfiguration();
+
+    }
+
+    protected void start() throws Exception {
+
+        server.start(smtpConf, pop3Conf, imapConf);
+
+    }
+
+    public void testImplUsageImap() throws Exception {
+
+        //check that we load our mail impl
+        final Properties props = new Properties();
+        props.setProperty("mail.store.protocol", "imap");
+        final Session jmsession = Session.getInstance(props);
+        Assert.assertEquals(org.apache.geronimo.javamail.store.imap.IMAPStore.class, jmsession.getStore().getClass());
+
+    }
+
+    public void testImplUsagePop3() throws Exception {
+
+        //check that we load our mail impl
+        final Properties props = new Properties();
+        props.setProperty("mail.store.protocol", "pop3");
+        final Session jmsession = Session.getInstance(props);
+        Assert.assertEquals(org.apache.geronimo.javamail.store.pop3.POP3Store.class, jmsession.getStore().getClass());
+
+    }
+
+    public void testImplUsageSmtp() throws Exception {
+
+        //check that we load our mail impl
+        final Properties props = new Properties();
+        props.setProperty("mail.transport.protocol", "smtp");
+        final Session jmsession = Session.getInstance(props);
+        Assert.assertEquals(org.apache.geronimo.javamail.transport.smtp.SMTPTransport.class, jmsession.getTransport().getClass());
+
+    }
+
+    protected void sendTestMsgs() throws Exception {
+        final Properties props = new Properties();
+        props.setProperty("mail.smtp.port", String.valueOf(smtpConf.getListenerPort()));
+        props.setProperty("mail.debug", "true");
+        final Session session = Session.getInstance(props);
+        sendMessage(session, "/messages/multipart.msg");
+        sendMessage(session, "/messages/simple.msg");
+        server.ensureMsgCount(2);
+    }
+
+    protected void sendMessage(final Session session, final String msgFile) throws Exception {
+        MimeMessage message;
+        final InputStream in = POP3StoreTest.class.getResourceAsStream(msgFile);
+        try {
+            message = new MimeMessage(session, in);
+        } finally {
+            in.close();
+        }
+        Transport.send(message, new Address[] { new InternetAddress("serveruser@localhost") });
+    }
+    
+    protected void sendMessage(final MimeMessage message) throws Exception {
+        Transport.send(message, new Address[] { new InternetAddress("serveruser@localhost") });
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        server.stop();
+    }
+
+}

Added: geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/testserver/ApopCmdHandler.java
URL: http://svn.apache.org/viewvc/geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/testserver/ApopCmdHandler.java?rev=1743397&view=auto
==============================================================================
--- geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/testserver/ApopCmdHandler.java (added)
+++ geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/testserver/ApopCmdHandler.java Wed May 11 16:49:36 2016
@@ -0,0 +1,119 @@
+/**
+ *  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.geronimo.javamail.testserver;
+
+import java.io.IOException;
+import java.math.BigInteger;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+
+import javax.annotation.Resource;
+
+import org.apache.james.mailbox.MailboxManager;
+import org.apache.james.mailbox.MailboxSession;
+import org.apache.james.mailbox.MessageManager;
+import org.apache.james.mailbox.exception.BadCredentialsException;
+import org.apache.james.mailbox.exception.MailboxException;
+import org.apache.james.mailbox.model.MailboxPath;
+import org.apache.james.pop3server.mailbox.MailboxAdapter;
+import org.apache.james.protocols.api.Request;
+import org.apache.james.protocols.api.Response;
+import org.apache.james.protocols.lib.POP3BeforeSMTPHelper;
+import org.apache.james.protocols.lib.Slf4jLoggerAdapter;
+import org.apache.james.protocols.pop3.POP3Response;
+import org.apache.james.protocols.pop3.POP3Session;
+import org.apache.james.protocols.pop3.core.AbstractApopCmdHandler;
+import org.apache.james.protocols.pop3.mailbox.Mailbox;
+
+public class ApopCmdHandler extends AbstractApopCmdHandler  {
+
+    private MailboxManager manager;
+
+
+    @Resource(name = "mailboxmanager")
+    public void setMailboxManager(MailboxManager manager) {
+        this.manager = manager;
+    }
+
+    @Override
+    public Response onCommand(POP3Session session, Request request) {
+        Response response =  super.onCommand(session, request);
+        if (POP3Response.OK_RESPONSE.equals(response.getRetCode())) {
+            POP3BeforeSMTPHelper.addIPAddress(session.getRemoteAddress().getAddress().getHostAddress());
+        }
+        return response;
+    }
+
+    @Override
+    protected Mailbox auth(POP3Session session, String apopTimestamp, String user, String digest) throws Exception {
+        MailboxSession mSession = null;
+        
+        String plaintextpassword = "serverpass";
+        
+        try {
+            final String toHash = apopTimestamp.trim()+plaintextpassword;
+            
+            if(!getMD5(toHash).equals(digest))
+            {
+                System.out.println("Digests does not match");
+                return null;
+            }
+            
+            
+            session.setUser(user);
+            
+            mSession = manager.createSystemSession(session.getUser(), new Slf4jLoggerAdapter(session.getLogger()));
+            manager.startProcessingRequest(mSession);
+            MailboxPath inbox = MailboxPath.inbox(mSession);
+            
+            // check if the mailbox exists, if not create it
+            if (!manager.mailboxExists(inbox, mSession)) {
+                manager.createMailbox(inbox, mSession);
+            }
+            MessageManager mailbox = manager.getMailbox(MailboxPath.inbox(mSession), mSession);
+            return new MailboxAdapter(manager, mailbox, mSession);
+        } catch (BadCredentialsException e) {
+            return null;
+        } catch (MailboxException e) {
+            throw new IOException("Unable to access mailbox for user " + session.getUser(), e);
+        } finally {
+            if (mSession != null) {
+                manager.endProcessingRequest(mSession);
+            }
+        }
+
+    }
+    
+    private static String getMD5(final String input) {
+        try {
+            final MessageDigest md = MessageDigest.getInstance("MD5");
+            final byte[] messageDigest = md.digest(input.getBytes());
+            final BigInteger number = new BigInteger(1, messageDigest);
+            String hashtext = number.toString(16);
+            // Now we need to zero pad it if you actually want the full 32 chars.
+            while (hashtext.length() < 32) {
+                hashtext = "0" + hashtext;
+            }
+            return hashtext;
+        }
+        catch (final NoSuchAlgorithmException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+}
+

Added: geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/testserver/MailServer.java
URL: http://svn.apache.org/viewvc/geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/testserver/MailServer.java?rev=1743397&view=auto
==============================================================================
--- geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/testserver/MailServer.java (added)
+++ geronimo/javamail/trunk/geronimo-javamail_1.5/geronimo-javamail_1.5_provider/src/test/java/org/apache/geronimo/javamail/testserver/MailServer.java Wed May 11 16:49:36 2016
@@ -0,0 +1,590 @@
+/**
+ *  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.geronimo.javamail.testserver;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Semaphore;
+
+import javax.mail.Flags;
+import javax.mail.internet.MimeMessage;
+import javax.net.ssl.SSLSocketFactory;
+
+import org.apache.commons.configuration.DefaultConfigurationBuilder;
+import org.apache.james.dnsservice.api.DNSService;
+import org.apache.james.domainlist.api.DomainListException;
+import org.apache.james.domainlist.api.mock.SimpleDomainList;
+import org.apache.james.filesystem.api.mock.MockFileSystem;
+import org.apache.james.imap.encode.main.DefaultImapEncoderFactory;
+import org.apache.james.imap.encode.main.DefaultLocalizer;
+import org.apache.james.imap.main.DefaultImapDecoderFactory;
+import org.apache.james.imap.processor.main.DefaultImapProcessorFactory;
+import org.apache.james.imapserver.netty.IMAPServer;
+import org.apache.james.mailbox.MailboxSession;
+import org.apache.james.mailbox.MessageManager;
+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.inmemory.InMemoryMailboxSessionMapperFactory;
+import org.apache.james.mailbox.model.MailboxConstants;
+import org.apache.james.mailbox.model.MailboxPath;
+import org.apache.james.mailbox.store.Authenticator;
+import org.apache.james.mailbox.store.StoreMailboxManager;
+import org.apache.james.mailrepository.mock.MockMailRepositoryStore;
+import org.apache.james.pop3server.netty.POP3Server;
+import org.apache.james.protocols.lib.PortUtil;
+import org.apache.james.protocols.lib.mock.MockProtocolHandlerLoader;
+import org.apache.james.queue.api.MailQueue;
+import org.apache.james.queue.api.MailQueue.MailQueueItem;
+import org.apache.james.queue.api.MailQueueFactory;
+import org.apache.james.queue.file.FileMailQueueFactory;
+import org.apache.james.rrt.api.RecipientRewriteTable;
+import org.apache.james.rrt.api.RecipientRewriteTableException;
+import org.apache.james.smtpserver.netty.SMTPServer;
+import org.apache.james.user.api.UsersRepositoryException;
+import org.apache.james.user.lib.mock.MockUsersRepository;
+import org.apache.mailet.HostAddress;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+//James based POP3 or IMAP or SMTP server (for unittesting only)
+public class MailServer {
+
+    private POP3Server pop3Server;
+    private IMAPServer imapServer;
+    private SMTPServer smtpServer;
+    private AlterableDNSServer dnsServer;
+    private final MockUsersRepository usersRepository = new MockUsersRepository();
+    private final MockFileSystem fileSystem = new MockFileSystem();
+    private MockProtocolHandlerLoader protocolHandlerChain;
+    private StoreMailboxManager<Long> mailboxManager;
+
+    private MockMailRepositoryStore store;
+    private DNSService dnsService;
+    private MailQueueFactory queueFactory;
+    private MailQueue queue;
+    private final Semaphore sem = new Semaphore(0);
+    private final Logger log = LoggerFactory.getLogger("Mock");
+
+    public void ensureMsgCount(final int count) throws InterruptedException {
+        sem.acquire(count);
+    }
+
+    private class Fetcher extends Thread {
+
+        private final MailQueue queue;
+        private final MessageManager mailbox;
+        private final MailboxSession session;
+
+        Fetcher(final MailQueue queue, final MessageManager mailbox, final MailboxSession session) {
+            super();
+            this.queue = queue;
+            this.mailbox = mailbox;
+            this.session = session;
+        }
+
+        @Override
+        public void run() {
+            while (true) {
+                try {
+                    System.out.println("Await new mail ...");
+                    final MailQueueItem item = queue.deQueue();
+                    System.out.println("got it");
+                    final MimeMessage msg = item.getMail().getMessage();
+                    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
+                    msg.writeTo(bout);
+                    mailbox.appendMessage(new ByteArrayInputStream(bout.toByteArray()), new Date(), session, true, new Flags());
+                    item.done(true);
+                    sem.release();
+                    System.out.println("mail copied over");
+                } catch (final Exception e) {
+                    e.printStackTrace();
+                    return;
+                }
+            }
+        }
+
+    }
+
+    public MailServer() {
+        super();
+        try {
+            usersRepository.addUser("serveruser", "serverpass");
+        } catch (final UsersRepositoryException e) {
+            throw new RuntimeException(e);
+        }
+
+    }
+
+    public void start(final SmtpTestConfiguration smtpConfig, final Pop3TestConfiguration pop3Config, final ImapTestConfiguration imapConfig)
+            throws Exception {
+        setUpServiceManager();
+
+        imapServer = new IMAPServer();
+
+        imapServer.setImapEncoder(DefaultImapEncoderFactory.createDefaultEncoder(new DefaultLocalizer(), false));
+        imapServer.setImapDecoder(DefaultImapDecoderFactory.createDecoder());
+
+        pop3Server = new POP3Server();
+        pop3Server.setProtocolHandlerLoader(protocolHandlerChain);
+
+        smtpServer = new SMTPServer() {
+            @Override
+            protected java.lang.Class<? extends org.apache.james.protocols.lib.handler.HandlersPackage> getJMXHandlersPackage() {
+                return RefinedJMXHandlersLoader.class;
+            };
+
+        };
+        smtpServer.setProtocolHandlerLoader(protocolHandlerChain);
+        smtpServer.setDNSService(dnsServer);
+
+        imapServer.setFileSystem(fileSystem);
+        pop3Server.setFileSystem(fileSystem);
+        smtpServer.setFileSystem(fileSystem);
+
+        imapServer.setLog(log);
+        pop3Server.setLog(log);
+        smtpServer.setLog(log);
+
+        final MailboxPath mailboxPath = new MailboxPath(MailboxConstants.USER_NAMESPACE, "serveruser", "INBOX");
+        final MailboxSession session = mailboxManager.login("serveruser", "serverpass", LoggerFactory.getLogger("Test"));
+
+        if (!mailboxManager.mailboxExists(mailboxPath, session)) {
+            mailboxManager.createMailbox(mailboxPath, session);
+        }
+
+        imapServer.setImapProcessor(DefaultImapProcessorFactory.createXListSupportingProcessor(mailboxManager, null, null));//new StoreSubscriptionManager(new InMemoryMailboxSessionMapperFactory()), null));
+
+        //setupTestMails(session, mailboxManager.getMailbox(mailboxPath, session));
+
+        new Fetcher(queue, mailboxManager.getMailbox(mailboxPath, session), session).start();
+
+        smtpConfig.init();
+        pop3Config.init();
+        imapConfig.init();
+
+        smtpServer.configure(smtpConfig);
+        pop3Server.configure(pop3Config);
+        imapServer.configure(imapConfig);
+
+        smtpServer.init();
+        pop3Server.init();
+        imapServer.init();
+
+    }
+
+    public void stop() throws Exception {
+
+        if (protocolHandlerChain != null) {
+            protocolHandlerChain.dispose();
+        }
+
+        if (imapServer != null) {
+            imapServer.destroy();
+        }
+
+        if (pop3Server != null) {
+            pop3Server.destroy();
+        }
+
+        if (smtpServer != null) {
+            smtpServer.destroy();
+        }
+
+    }
+
+    /* protected void setupTestMailsx(MailboxSession session, MessageManager mailbox) throws MailboxException {
+         mailbox.appendMessage(new ByteArrayInputStream(content), new Date(), session, true, new Flags());
+         byte[] content2 = ("EMPTY").getBytes();
+         mailbox.appendMessage(new ByteArrayInputStream(content2), new Date(), session, true, new Flags());
+     }*/
+
+    protected void setUpServiceManager() throws Exception {
+        protocolHandlerChain = new MockProtocolHandlerLoader();
+        protocolHandlerChain.put("usersrepository", usersRepository);
+
+        final InMemoryMailboxSessionMapperFactory factory = new InMemoryMailboxSessionMapperFactory();
+        final MailboxACLResolver aclResolver = new UnionMailboxACLResolver();
+        final GroupMembershipResolver groupMembershipResolver = new SimpleGroupMembershipResolver();
+        mailboxManager = new StoreMailboxManager<Long>(factory, new Authenticator() {
+
+            public boolean isAuthentic(final String userid, final CharSequence passwd) {
+                try {
+                    return usersRepository.test(userid, passwd.toString());
+                } catch (final UsersRepositoryException e) {
+                    e.printStackTrace();
+                    return false;
+                }
+            }
+        }, aclResolver, groupMembershipResolver);
+        mailboxManager.init();
+
+        protocolHandlerChain.put("mailboxmanager", mailboxManager);
+
+        protocolHandlerChain.put("fileSystem", fileSystem);
+
+        //smtp
+        dnsServer = new AlterableDNSServer();
+        store = new MockMailRepositoryStore();
+        protocolHandlerChain.put("mailStore", store);
+        protocolHandlerChain.put("dnsservice", dnsServer);
+        protocolHandlerChain.put("org.apache.james.smtpserver.protocol.DNSService", dnsService);
+
+        protocolHandlerChain.put("recipientrewritetable", new RecipientRewriteTable() {
+
+            public void addRegexMapping(final String user, final String domain, final String regex) throws RecipientRewriteTableException {
+                throw new UnsupportedOperationException("Not implemented");
+            }
+
+            public void removeRegexMapping(final String user, final String domain, final String regex)
+                    throws RecipientRewriteTableException {
+                throw new UnsupportedOperationException("Not implemented");
+            }
+
+            public void addAddressMapping(final String user, final String domain, final String address)
+                    throws RecipientRewriteTableException {
+                throw new UnsupportedOperationException("Not implemented");
+            }
+
+            public void removeAddressMapping(final String user, final String domain, final String address)
+                    throws RecipientRewriteTableException {
+                throw new UnsupportedOperationException("Not implemented");
+            }
+
+            public void addErrorMapping(final String user, final String domain, final String error) throws RecipientRewriteTableException {
+                throw new UnsupportedOperationException("Not implemented");
+            }
+
+            public void removeErrorMapping(final String user, final String domain, final String error)
+                    throws RecipientRewriteTableException {
+                throw new UnsupportedOperationException("Not implemented");
+            }
+
+            public Collection<String> getUserDomainMappings(final String user, final String domain) throws RecipientRewriteTableException {
+                throw new UnsupportedOperationException("Not implemented");
+            }
+
+            public void addMapping(final String user, final String domain, final String mapping) throws RecipientRewriteTableException {
+                throw new UnsupportedOperationException("Not implemented");
+            }
+
+            public void removeMapping(final String user, final String domain, final String mapping) throws RecipientRewriteTableException {
+                throw new UnsupportedOperationException("Not implemented");
+            }
+
+            public Map<String, Collection<String>> getAllMappings() throws RecipientRewriteTableException {
+                throw new UnsupportedOperationException("Not implemented");
+            }
+
+            public void addAliasDomainMapping(final String aliasDomain, final String realDomain) throws RecipientRewriteTableException {
+                throw new UnsupportedOperationException("Not implemented");
+            }
+
+            public void removeAliasDomainMapping(final String aliasDomain, final String realDomain) throws RecipientRewriteTableException {
+                throw new UnsupportedOperationException("Not implemented");
+            }
+
+            public Collection<String> getMappings(final String user, final String domain) throws ErrorMappingException,
+            RecipientRewriteTableException {
+                throw new UnsupportedOperationException("Not implemented");
+            }
+        });
+
+        protocolHandlerChain.put("org.apache.james.smtpserver.protocol.DNSService", dnsService);
+
+        final FileMailQueueFactory ff = new FileMailQueueFactory();// MockMailQueueFactory();
+        ff.setLog(log);
+        ff.setFileSystem(fileSystem);
+        queueFactory = ff;
+
+        queue = queueFactory.getQueue(MailQueueFactory.SPOOL);
+        protocolHandlerChain.put("mailqueuefactory", queueFactory);
+        protocolHandlerChain.put("domainlist", new SimpleDomainList() {
+
+            @Override
+            public String getDefaultDomain() {
+                return "localhost";
+            }
+
+            @Override
+            public String[] getDomains() throws DomainListException {
+                return new String[] { "localhost" };
+            }
+
+            @Override
+            public boolean containsDomain(final String serverName) {
+                return "localhost".equals(serverName);
+            }
+        });
+
+    }
+
+    /**
+     * @return the queue
+     */
+    public MailQueue getQueue() {
+        return queue;
+    }
+
+    public static File getAbsoluteFilePathFromClassPath(final String fileNameFromClasspath) throws FileNotFoundException {
+
+        File configFile = null;
+        final URL configURL = MailServer.class.getClassLoader().getResource(fileNameFromClasspath);
+        if (configURL != null) {
+            try {
+                configFile = new File(configURL.toURI());
+            } catch (URISyntaxException e) {
+                configFile = new File(configURL.getPath());
+            }
+
+            //Java 7 only
+            /*if(!configFile.exists()) {
+                try {
+                    configFile = Paths.get(configURL.toURI()).toFile();
+                } catch (URISyntaxException e) {
+                    throw new FileNotFoundException("Failed to load " + fileNameFromClasspath+ " due to "+e);
+                }
+            }*/
+
+            if (configFile.exists()) {
+                return configFile;
+            } else {
+                throw new FileNotFoundException("Cannot read from "+configFile.getAbsolutePath()+" (original resource was "+fileNameFromClasspath+", URL: "+configURL+"), because the file does not exist");
+            }
+            
+        } else {
+            throw new FileNotFoundException("Failed to load " + fileNameFromClasspath+", because resource cannot be found within the classpath");
+        }
+
+    }
+
+    public static abstract class AbstractTestConfiguration extends DefaultConfigurationBuilder {
+
+        private final int listenerPort = PortUtil.getNonPrivilegedPort();
+
+        /**
+         * @return the listenerPort
+         */
+        public int getListenerPort() {
+            return listenerPort;
+        }
+
+        public AbstractTestConfiguration enableSSL(final boolean enableStartTLS, final boolean enableSSL) throws FileNotFoundException {
+            addProperty("tls.[@startTLS]", enableStartTLS);
+            addProperty("tls.[@socketTLS]", enableSSL);
+            addProperty("tls.keystore", "file://" + getAbsoluteFilePathFromClassPath("dummykeystore.jks").getAbsolutePath());
+            addProperty("tls.secret", "123456");
+            addProperty("tls.provider", "org.bouncycastle.jce.provider.BouncyCastleProvider");
+            return this;
+        }
+
+        public void init() {
+            addProperty("[@enabled]", true);
+            addProperty("bind", "127.0.0.1:" + this.listenerPort);
+            addProperty("connectiontimeout", "360000");
+            //addProperty("jmxName", getServertype().name()+"on"+this.listenerPort);
+            addProperty("helloName", "jamesserver");
+            addProperty("helloName.[@autodetect]", false);
+        }
+
+    }
+
+    public static class Pop3TestConfiguration extends AbstractTestConfiguration {
+
+        @Override
+        public void init() {
+            super.init();
+
+            addProperty("helloName", "pop3 on port " + getListenerPort());
+
+            addProperty("handlerchain.[@coreHandlersPackage]", RefinedCoreCmdHandlerLoader.class.getName());
+
+        }
+
+    }
+
+    public static class ImapTestConfiguration extends AbstractTestConfiguration {
+
+        @Override
+        public void init() {
+            super.init();
+
+            addProperty("helloName", "imap on port " + getListenerPort());
+
+        }
+
+    }
+
+    public static class SmtpTestConfiguration extends AbstractTestConfiguration {
+
+        @Override
+        public void init() {
+            super.init();
+            addProperty("handlerchain.handler[@class]", RefinedSmtpCoreCmdHandlerLoader.class.getName());
+
+        }
+
+        public SmtpTestConfiguration setRequireAuth(final boolean requireAuth) {
+
+            addProperty("authRequired", requireAuth);
+            return this;
+        }
+
+        public SmtpTestConfiguration setHeloEhloEnforcement(final boolean heloEhloEnforcement) {
+
+            addProperty("heloEhloEnforcement", heloEhloEnforcement);
+            return this;
+        }
+
+    }
+
+    public static class DummySocketFactory extends SSLSocketFactory {
+
+        @Override
+        public Socket createSocket(final String host, final int port) throws IOException, UnknownHostException {
+            throw new IOException("dummy socket factory");
+        }
+
+        @Override
+        public Socket createSocket(final InetAddress host, final int port) throws IOException {
+            throw new IOException("dummy socket factory");
+        }
+
+        @Override
+        public Socket createSocket(final String host, final int port, final InetAddress localHost, final int localPort) throws IOException,
+                UnknownHostException {
+            throw new IOException("dummy socket factory");
+        }
+
+        @Override
+        public Socket createSocket(final InetAddress address, final int port, final InetAddress localAddress, final int localPort)
+                throws IOException {
+            throw new IOException("dummy socket factory");
+        }
+
+        @Override
+        public Socket createSocket(final Socket arg0, final String arg1, final int arg2, final boolean arg3) throws IOException {
+            throw new IOException("dummy socket factory");
+        }
+
+        @Override
+        public String[] getDefaultCipherSuites() {
+            return new String[0];
+        }
+
+        @Override
+        public String[] getSupportedCipherSuites() {
+            return new String[0];
+        }
+
+    }
+
+    private final class AlterableDNSServer implements DNSService {
+
+        private InetAddress localhostByName = null;
+
+        public Collection<String> findMXRecords(final String hostname) {
+            final List<String> res = new ArrayList<String>();
+            if (hostname == null) {
+                return res;
+            }
+            if ("james.apache.org".equals(hostname)) {
+                res.add("nagoya.apache.org");
+            }
+            return res;
+        }
+
+        public Iterator<HostAddress> getSMTPHostAddresses(final String domainName) {
+            throw new UnsupportedOperationException("Unimplemented mock service");
+        }
+
+        public InetAddress[] getAllByName(final String host) throws UnknownHostException {
+            return new InetAddress[] { getByName(host) };
+        }
+
+        public InetAddress getByName(final String host) throws UnknownHostException {
+            if (getLocalhostByName() != null) {
+                if ("127.0.0.1".equals(host)) {
+                    return getLocalhostByName();
+                }
+            }
+
+            if ("0.0.0.0".equals(host)) {
+                return InetAddress.getByName("0.0.0.0");
+            }
+
+            if ("james.apache.org".equals(host)) {
+                return InetAddress.getByName("james.apache.org");
+            }
+
+            if ("abgsfe3rsf.de".equals(host)) {
+                throw new UnknownHostException();
+            }
+
+            if ("128.0.0.1".equals(host) || "192.168.0.1".equals(host) || "127.0.0.1".equals(host) || "127.0.0.0".equals(host)
+                    || "255.0.0.0".equals(host) || "255.255.255.255".equals(host)) {
+                return InetAddress.getByName(host);
+            }
+
+            throw new UnsupportedOperationException("getByName not implemented in mock for host: " + host);
+        }
+
+        public Collection<String> findTXTRecords(final String hostname) {
+            final List<String> res = new ArrayList<String>();
+            if (hostname == null) {
+                return res;
+            }
+
+            if ("2.0.0.127.bl.spamcop.net.".equals(hostname)) {
+                res.add("Blocked - see http://www.spamcop.net/bl.shtml?127.0.0.2");
+            }
+            return res;
+        }
+
+        public InetAddress getLocalhostByName() {
+            return localhostByName;
+        }
+
+        public void setLocalhostByName(final InetAddress localhostByName) {
+            this.localhostByName = localhostByName;
+        }
+
+        public String getHostName(final InetAddress addr) {
+            return addr.getHostName();
+        }
+
+        public InetAddress getLocalHost() throws UnknownHostException {
+            return InetAddress.getLocalHost();
+        }
+    }
+
+}




Mime
View raw message