Java Code Examples for com.sun.mail.imap.IMAPFolder#open()

The following examples show how to use com.sun.mail.imap.IMAPFolder#open() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StoreCopier.java    From mnIMAPSync with Apache License 2.0 6 votes vote down vote up
/**
 * Once the folder structure has been created it copies messages recursively from the root
 * folder.
 */
private void copySourceMessages(IMAPFolder sourceFolder) throws MessagingException {
    if (sourceFolder != null) {
        final String sourceFolderName = sourceFolder.getFullName();
        final String targetFolderName = sourceFolderNameToTarget(sourceFolderName, sourceIndex,
            targetIndex);
        if ((sourceFolder.getType() & Folder.HOLDS_MESSAGES) == Folder.HOLDS_MESSAGES) {
            //Manage Servers with public/read only folders.
            try {
                sourceFolder.open(Folder.READ_WRITE);
            } catch (ReadOnlyFolderException ex) {
                sourceFolder.open(Folder.READ_ONLY);
            }
            if (sourceFolder.getMode() != Folder.READ_ONLY) {
                sourceFolder.expunge();
            }
            ///////////////////////
            final int messageCount = sourceFolder.getMessageCount();
            sourceFolder.close(false);
            int pos = 1;
            while (pos + MNIMAPSync.BATCH_SIZE <= messageCount) {
                //Copy messages
                service.execute(new MessageCopier(this, sourceFolderName, targetFolderName, pos,
                        pos + MNIMAPSync.BATCH_SIZE, targetIndex.getFolderMessages(
                                targetFolderName)));
                pos = pos + MNIMAPSync.BATCH_SIZE;
            }
            service.execute(new MessageCopier(this, sourceFolderName, targetFolderName, pos,
                    messageCount,
                    targetIndex.getFolderMessages(targetFolderName)));
        }
        //Folder recursion. Get all children
        if ((sourceFolder.getType() & Folder.HOLDS_FOLDERS) == Folder.HOLDS_FOLDERS) {
            for (Folder child : sourceFolder.list()) {
                copySourceMessages((IMAPFolder) child);
            }
        }
    }
}
 
Example 2
Source File: ImapProtocolTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Test
public void testListAndStatusWithNonExistingFolder() throws MessagingException {
    store.connect("foo@localhost", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);
        assertFalse(folder.getFolder("non existent folder").exists());
        for (final String cmd : new String[]{
                "STATUS \"non existent folder\" (MESSAGES UIDNEXT UIDVALIDITY UNSEEN)",
                "SELECT \"non existent folder\""
        }) {
            Response[] ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
                @Override
                public Object doCommand(IMAPProtocol protocol) {
                    return protocol.command(cmd, null);
                }
            });

            IMAPResponse response = (IMAPResponse) ret[0];
            assertTrue(response.isNO());
        }
    } finally {
        store.close();
    }
}
 
Example 3
Source File: ImapProtocolTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Test
public void testSearchNotFlags() throws MessagingException {
    store.connect("foo@localhost", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_WRITE);
        folder.setFlags(new int[]{2, 3}, new Flags(Flags.Flag.ANSWERED), true);
        Response[] ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("SEARCH NOT (ANSWERED) NOT (DELETED) NOT (SEEN) NOT (FLAGGED) ALL", null);
            }
        });
        IMAPResponse response = (IMAPResponse) ret[0];
        assertFalse(response.isBAD());
        assertEquals("1 4 5 6 7 8 9 10" /* 2 and 3 set to answered */, response.getRest());
    } finally {
        store.close();
    }
}
 
Example 4
Source File: ImapProtocolTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetMessageByUnknownUidInEmptyINBOX() throws MessagingException, FolderException {
    greenMail.getManagers()
            .getImapHostManager()
            .getInbox(user)
            .deleteAllMessages();
    store.connect("foo@localhost", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);
        Message message = folder.getMessageByUID(666);
        assertNull(message);
    } finally {
        store.close();
    }
}
 
Example 5
Source File: ImapProtocolTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testFetchUidsAndSize() throws MessagingException {
    store.connect("foo@localhost", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);
        Response[] ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("UID FETCH 1:* RFC822.SIZE", null);
            }
        });

        FetchResponse fetchResponse = (FetchResponse) ret[0];
        assertFalse(fetchResponse.isBAD());
        assertEquals(2, fetchResponse.getItemCount()); // UID and SIZE

        RFC822SIZE size = fetchResponse.getItem(RFC822SIZE.class);
        assertNotNull(size);
        assertTrue(size.size > 0);

        UID uid = fetchResponse.getItem(UID.class);
        assertEquals(folder.getUID(folder.getMessage(1)), uid.uid);
    } finally {
        store.close();
    }
}
 
Example 6
Source File: SenderRecipientTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendAndReceiveWithQuotedAddress() throws MessagingException, IOException {
    // See https://en.wikipedia.org/wiki/Email_address#Local-part
    String[] toList = {"\"John..Doe\"@localhost",
            "abc.\"defghi\".xyz@localhost",
            "\"abcdefghixyz\"@localhost",
            "\"Foo Bar\"admin@localhost"
    };
    for(String to: toList) {
        greenMail.setUser(to, "pwd");
        InternetAddress[] toAddress = InternetAddress.parse(to);
        String from = to; // Same from and to address for testing correct escaping of both

        final String subject = "testSendAndReceiveWithQuotedAddress";
        final String content = "some body";
        GreenMailUtil.sendTextEmailTest(to, from,
                subject, content);

        assertTrue(greenMail.waitForIncomingEmail(5000, 1));

        final IMAPStore store = greenMail.getImap().createStore();
        store.connect(to, "pwd");
        try {
            IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);
            Message[] msgs = folder.getMessages();
            assertTrue(null != msgs && msgs.length == 1);
            final Message msg = msgs[0];
            assertEquals(to, ((InternetAddress)msg.getRecipients(Message.RecipientType.TO)[0]).getAddress());
            assertEquals(from, ((InternetAddress)msg.getFrom()[0]).getAddress());
            assertEquals(subject, msg.getSubject());
            assertEquals(content, msg.getContent().toString());
            assertArrayEquals(toAddress, msg.getRecipients(Message.RecipientType.TO));
        } finally {
            store.close();
        }
    }
}
 
Example 7
Source File: ImapProtocolTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testRenameFolder() throws MessagingException {
    store.connect("foo@localhost", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_WRITE);
        Response[] ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("CREATE foo", null);
            }
        });

        IMAPResponse response = (IMAPResponse) ret[0];
        assertFalse(response.isBAD());

        ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("RENAME foo bar", null);
            }
        });

        Response response2 = ret[0];
        assertTrue(response2.isOK());

        final Folder bar = store.getFolder("bar");
        bar.open(Folder.READ_ONLY);
        assertTrue(bar.exists());
    } finally {
        store.close();
    }
}
 
Example 8
Source File: ImapProtocolTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testUidSearchTextWithCharset() throws MessagingException, IOException {
    greenMail.setUser("foo2@localhost", "pwd");
    store.connect("foo2@localhost", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);

        final MimeMessage email = GreenMailUtil.createTextEmail("foo2@localhost", "foo@localhost",
                "some subject", "some content",
                greenMail.getSmtp().getServerSetup());

        String[][] s = {
                {"US-ASCII", "ABC", "1"},
                {"ISO-8859-15", "\u00c4\u00e4\u20AC", "2"},
                {"UTF-8", "\u00c4\u00e4\u03A0", "3"}
        };

        for (String[] charsetAndQuery : s) {
            final String charset = charsetAndQuery[0];
            final String search = charsetAndQuery[1];

            email.setSubject("subject " + search, charset);
            GreenMailUtil.sendMimeMessage(email);

            // messages[2] contains content with search text, match must be case insensitive
            final byte[] searchBytes = search.getBytes(charset);
            final Argument arg = new Argument();
            arg.writeBytes(searchBytes);
            // Try with and without quotes
            searchAndValidateWithCharset(folder, charsetAndQuery[2], charset, arg);
            searchAndValidateWithCharset(folder, charsetAndQuery[2], '"' + charset + '"', arg);
        }
    } finally {
        store.close();
    }
}
 
Example 9
Source File: ImapProtocolTest.java    From greenmail with Apache License 2.0 5 votes vote down vote up
@Test
public void testUidSearchAll() throws MessagingException, IOException {
    greenMail.setUser("foo2@localhost", "pwd");
    store.connect("foo2@localhost", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);

        final MimeMessage email = GreenMailUtil.createTextEmail("foo2@localhost", "foo@localhost",
                "some subject", "some content",
                greenMail.getSmtp().getServerSetup());


        final IMAPFolder.ProtocolCommand uid_search_all = new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("UID SEARCH ALL", null);
            }
        };

        // Search empty
        Response[] ret = (Response[]) folder.doCommand(uid_search_all);
        IMAPResponse response = (IMAPResponse) ret[0];
        assertFalse(response.isBAD());
        assertEquals("* SEARCH", response.toString());
    } finally {
        store.close();
    }
}
 
Example 10
Source File: ImapProtocolTest.java    From greenmail with Apache License 2.0 4 votes vote down vote up
@Test
public void testUidSearchText() throws MessagingException {
    store.connect("foo@localhost", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);

        final Message[] messages = folder.getMessages();
        Map<Integer, String> uids = new HashMap<>();
        for (Message msg : messages) {
            uids.put(msg.getMessageNumber(), Long.toString(folder.getUID(msg)));
        }

        // messages[2] contains content with search text, match must be case insensitive
        final String searchText1 = "conTEnt2";
        Response[] ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("UID SEARCH TEXT " + searchText1, null);
            }
        });
        IMAPResponse response = (IMAPResponse) ret[0];
        assertFalse(response.isBAD());
        assertEquals(uids.get(messages[2].getMessageNumber()), response.getRest());

        // messages[2] contains search text in CC, with different upper case
        final String searchText2 = "foo@localHOST";
        ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("UID SEARCH TEXT " + searchText2, null);
            }
        });
        response = (IMAPResponse) ret[0];
        assertFalse(response.isBAD());
        // Match all
        assertArrayEquals(uids.values().toArray(), response.getRest().split(" "));
    } finally {
        store.close();
    }
}
 
Example 11
Source File: ImapServerTest.java    From greenmail with Apache License 2.0 4 votes vote down vote up
@Test
public void testAppend() throws MessagingException {
    greenMail.setUser("foo@localhost", "pwd");

    GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost", "Test Append",
            "Test message", greenMail.getSmtp().getServerSetup());

    final IMAPStore store = greenMail.getImap().createStore();
    store.connect("foo@localhost", "pwd");
    try {
        IMAPFolder inboxFolder = (IMAPFolder) store.getFolder("INBOX");
        inboxFolder.open(Folder.READ_WRITE);

        Message[] messages = inboxFolder.getMessages();
        assertEquals(1, messages.length);
        Message message = messages[0];

        Message[] toBeAppended = new Message[]{
                new MimeMessage((MimeMessage) message) // Copy
        };
        toBeAppended[0].setSubject("testAppend#1");

        inboxFolder.appendMessages(toBeAppended);
        messages = inboxFolder.getMessages();
        assertEquals(2, messages.length);

        // UIDPLUS
        toBeAppended[0] = new MimeMessage((MimeMessage) message);
        toBeAppended[0].setSubject("testAppend#2");

        final AppendUID[] appendUIDs = inboxFolder.appendUIDMessages(toBeAppended); // Copy again
        long uid = appendUIDs[0].uid;
        Message newMsg = inboxFolder.getMessageByUID(uid);
        assertEquals(toBeAppended[0].getSubject(), newMsg.getSubject());
        assertEquals(appendUIDs[0].uidvalidity, inboxFolder.getUIDValidity());
        messages = inboxFolder.getMessages();
        assertEquals(3, messages.length);
    } finally {
        store.close();
    }
}
 
Example 12
Source File: ImapServerTest.java    From greenmail with Apache License 2.0 4 votes vote down vote up
@Test
public void testUIDExpunge() throws MessagingException {
    greenMail.setUser("foo@localhost", "pwd");

    // Create some test emails
    int numberOfEmails = 10;
    long[] uids = new long[numberOfEmails];
    for (int i = 0; i < numberOfEmails; i++) {
        GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost", "Test UID expunge #" + i,
                "Test message", greenMail.getSmtp().getServerSetup());
    }

    final IMAPStore store = greenMail.getImap().createStore();
    store.connect("foo@localhost", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_WRITE);

        Message[] messages = folder.getMessages();
        assertEquals(numberOfEmails, messages.length);

        // Mark even as deleted ...
        Message[] msgsForDeletion = new Message[uids.length / 2];
        for (int i = 0; i < messages.length; i++) {
            assertFalse(messages[i].getFlags().contains(Flags.Flag.DELETED));
            uids[i] = folder.getUID(messages[i]);
            if (i % 2 == 0) { // Deleted
                messages[i].setFlag(Flags.Flag.DELETED, true);
                msgsForDeletion[i / 2] = messages[i];
            }
        }

        // ... and expunge (with UID)
        folder.expunge(msgsForDeletion);

        // Check
        for (int i = 0; i < uids.length; i++) {
            final Message message = folder.getMessageByUID(uids[i]);
            if (i % 2 == 0) { // Deleted
                assertNull(message);
            } else {
                assertFalse("" + i, message.isExpunged());
                assertFalse("" + i, message.getFlags().contains(DELETED));
            }
        }
    } finally {
        store.close();
    }
}
 
Example 13
Source File: ImapSortTest.java    From greenmail with Apache License 2.0 4 votes vote down vote up
@Test
public void testSort() throws Exception {
    GreenMailUser user = greenMail.setUser("to1@localhost", "pwd");
    assertNotNull(greenMail.getImap());

    MailFolder folder = greenMail.getManagers().getImapHostManager().getFolder(user, "INBOX");
    Flags fooFlags = new Flags();
    fooFlags.add("foo");
    storeSortTestMessages(greenMail.getImap().createSession(), folder, fooFlags);

    greenMail.waitForIncomingEmail(2);

    final Store store = greenMail.getImap().createStore();
    store.connect("to1@localhost", "pwd");
    try {
        IMAPFolder imapFolder = (IMAPFolder) store.getFolder("INBOX");
        imapFolder.open(Folder.READ_WRITE);

        Message[] imapMessages = imapFolder.getMessages();
        assertTrue(null != imapMessages && imapMessages.length == 2);
        Message m0 = imapMessages[0];
        Message m1 = imapMessages[1];
        assertTrue(m0.getFlags().contains(Flags.Flag.ANSWERED));

        imapMessages = imapFolder.getSortedMessages(new SortTerm[]{SortTerm.TO});
        assertEquals(2, imapMessages.length);
        assertSame(imapMessages[0], m0);
        assertSame(imapMessages[1], m1);

        imapMessages = imapFolder.getSortedMessages(new SortTerm[]{SortTerm.REVERSE, SortTerm.TO});
        assertEquals(2, imapMessages.length);
        assertSame(imapMessages[0], m1);
        assertSame(imapMessages[1], m0);

        imapMessages = imapFolder.getSortedMessages(new SortTerm[]{SortTerm.TO}, new FlagTerm(new Flags(Flags.Flag.ANSWERED), true));
        assertEquals(1, imapMessages.length);
        assertSame(imapMessages[0], m0);

    } finally {
        store.close();
    }
}
 
Example 14
Source File: Main.java    From javamail-mock2 with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws Exception {

        final Session session = Session.getInstance(getProperties());

        final MockMailbox mb = MockMailbox.get("[email protected]");
        final MailboxFolder mf = mb.getInbox();

        final MimeMessage msg = new MimeMessage((Session) null);
        msg.setSubject("Test");
        msg.setFrom("[email protected]");
        msg.setText("Some text here ...");
        msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
        mf.add(msg); // 11
        mf.add(msg); // 12
        mf.add(msg); // 13
        mb.getRoot().getOrAddSubFolder("test").create().add(msg);

        final Store store = session.getStore("mock_imap");
        store.connect("[email protected]", null);
        final Folder defaultFolder = store.getDefaultFolder();
        final IMAPFolder test = (IMAPFolder) defaultFolder.getFolder("test");

        final IdleMessageCountListener mcl = new IdleMessageCountListener();
        test.addMessageCountListener(mcl);

        test.open(Folder.READ_WRITE);

        final IdleThread it = new IdleThread(test);
        it.start();

        final IdleThread it2 = new IdleThread(test);
        it2.start();

        test.addMessages(new Message[] { msg });
        test.addMessages(new Message[] { msg });
        test.addMessages(new Message[] { msg });

        // test.close(true);

        System.out.println(it.getException());
        System.out.println(mcl.getAddedCount());
        System.out.println(mcl.getRemovedCount());
        System.out.println(test.getMessageCount());
        System.out.println(it.getIdleCount());

        // System.exit(1);

    }
 
Example 15
Source File: ImapProtocolTest.java    From greenmail with Apache License 2.0 4 votes vote down vote up
@Test
public void testUidSearchSequenceSet() throws MessagingException {
    store.connect("foo@localhost", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);

        final Message[] messages = folder.getMessages();
        Map<Integer, Long> uids = new HashMap<>();
        for (Message msg : messages) {
            uids.put(msg.getMessageNumber(), folder.getUID(msg));
        }

        Response[] ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("UID SEARCH 1", null);
            }
        });
        IMAPResponse response = (IMAPResponse) ret[0];
        assertFalse(response.isBAD());
        assertEquals(uids.get(1).toString(), response.getRest());

        ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("UID SEARCH 2:2", null);
            }
        });
        response = (IMAPResponse) ret[0];
        assertFalse(response.isBAD());
        assertTrue(ret[1].isOK());
        assertEquals(uids.get(2).toString(), response.getRest());

        ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("UID SEARCH 2:4", null);
            }
        });
        response = (IMAPResponse) ret[0];
        assertFalse(response.isBAD());
        assertEquals(msnListToUidString(uids, 2, 3, 4), response.getRest());
        assertTrue(ret[1].isOK());

        ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("UID SEARCH 1,2:4,8", null);
            }
        });
        response = (IMAPResponse) ret[0];
        assertFalse(response.isBAD());
        assertEquals(msnListToUidString(uids, 1, 2, 3, 4, 8), response.getRest());
        assertTrue(ret[1].isOK());
    } finally {
        store.close();
    }
}
 
Example 16
Source File: ImapProtocolTest.java    From greenmail with Apache License 2.0 4 votes vote down vote up
@Test
public void testSearchSequenceSet() throws MessagingException {
    store.connect("foo@localhost", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);

        Response[] ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("SEARCH 1", null);
            }
        });
        IMAPResponse response = (IMAPResponse) ret[0];
        assertFalse(response.isBAD());
        assertEquals("1", response.getRest());

        ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("SEARCH 2:2", null);
            }
        });
        response = (IMAPResponse) ret[0];
        assertFalse(response.isBAD());
        assertTrue(ret[1].isOK());
        assertEquals("2", response.getRest());

        ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("SEARCH 2:4", null);
            }
        });
        response = (IMAPResponse) ret[0];
        assertFalse(response.isBAD());
        assertEquals("2 3 4", response.getRest());
        assertTrue(ret[1].isOK());

        ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("SEARCH 1,2:4,8", null);
            }
        });
        response = (IMAPResponse) ret[0];
        assertFalse(response.isBAD());
        assertEquals("1 2 3 4 8", response.getRest());
        assertTrue(ret[1].isOK());

        ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("SEARCH 1,2:4 3,8", null);
            }
        });
        response = (IMAPResponse) ret[0];
        assertFalse(response.isBAD());
        assertEquals("3", response.getRest());
        assertTrue(ret[1].isOK());
    } finally {
        store.close();
    }
}
 
Example 17
Source File: ImapProtocolTest.java    From greenmail with Apache License 2.0 4 votes vote down vote up
@Test
public void testFetchSpaceBeforeSize() throws MessagingException {
    store.connect("foo@localhost", "pwd");
    try {
        IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);

        // Fetch without partial as reference
        Response[] ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) {
                return protocol.command("UID FETCH 1 (BODY[HEADER])", null);
            }
        });
        FetchResponse fetchResponse = (FetchResponse) ret[0];
        assertFalse(fetchResponse.isBAD());
        assertEquals(3, fetchResponse.getItemCount()); // UID, BODY, FLAGS

        BODY body = fetchResponse.getItem(BODY.class);
        assertTrue(body.isHeader());
        final String content = new String(body.getByteArray().getNewBytes());

        UID uid = fetchResponse.getItem(UID.class);
        assertEquals(folder.getUID(folder.getMessage(1)), uid.uid);

        // partial size only
        ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) throws ProtocolException {
                return protocol.command("UID FETCH 1 (BODY[HEADER]<50>)", null);
            }
        });
        fetchResponse = (FetchResponse) ret[0];
        assertFalse(fetchResponse.isBAD());
        assertEquals(2, fetchResponse.getItemCount()); // UID, BODY

        body = fetchResponse.getItem(BODY.class);
        assertTrue(body.isHeader());
        assertEquals(50, body.getByteArray().getCount());

        uid = fetchResponse.getItem(UID.class);
        assertEquals(folder.getUID(folder.getMessage(1)), uid.uid);

        // partial size and zero offset
        ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) throws ProtocolException {
                return protocol.command("UID FETCH 1 (BODY[HEADER]<0.30>)", null);
            }
        });
        fetchResponse = (FetchResponse) ret[0];
        assertFalse(fetchResponse.isBAD());
        assertEquals(2, fetchResponse.getItemCount()); // UID , BODY

        body = fetchResponse.getItem(BODY.class);
        assertTrue(body.isHeader());
        assertEquals(30, body.getByteArray().getCount());

        uid = fetchResponse.getItem(UID.class);
        assertEquals(folder.getUID(folder.getMessage(1)), uid.uid);

        // partial size and non zero offset
        ret = (Response[]) folder.doCommand(new IMAPFolder.ProtocolCommand() {
            @Override
            public Object doCommand(IMAPProtocol protocol) throws ProtocolException {
                return protocol.command("UID FETCH 1 (BODY[HEADER]<10.30>)", null);
            }
        });
        fetchResponse = (FetchResponse) ret[0];
        assertFalse(fetchResponse.isBAD());
        assertEquals(2, fetchResponse.getItemCount()); // UID and SIZE

        body = fetchResponse.getItem(BODY.class);
        assertTrue(body.isHeader());
        final ByteArray byteArray = body.getByteArray();
        assertEquals(30, byteArray.getCount());
        assertEquals(content.substring(10, 10 + 30), new String(byteArray.getNewBytes()));

        uid = fetchResponse.getItem(UID.class);
        assertEquals(folder.getUID(folder.getMessage(1)), uid.uid);
    } finally {
        store.close();
    }
}
 
Example 18
Source File: IMAPTestCase.java    From javamail-mock2 with Apache License 2.0 4 votes vote down vote up
@Test
public void testIDLESupported() throws Exception {

    final MockMailbox mb = MockMailbox.get("[email protected]");
    final MailboxFolder mf = mb.getInbox();

    final MimeMessage msg = new MimeMessage((Session) null);
    msg.setSubject("Test");
    msg.setFrom("[email protected]");
    msg.setText("Some text here ...");
    msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
    mf.add(msg); // 11
    mf.add(msg); // 12
    mf.add(msg); // 13
    mb.getRoot().getOrAddSubFolder("test").create().add(msg);

    final Store store = session.getStore("mock_imap");
    store.connect("[email protected]", null);
    final Folder defaultFolder = store.getDefaultFolder();
    final IMAPFolder test = (IMAPFolder) defaultFolder.getFolder("test");

    final IdleMessageCountListener mcl = new IdleMessageCountListener();
    test.addMessageCountListener(mcl);

    test.open(Folder.READ_WRITE);

    final IdleThread it = new IdleThread(test);
    it.start();

    test.addMessages(new Message[] { msg });
    test.addMessages(new Message[] { msg });
    test.addMessages(new Message[] { msg });

    Thread.sleep(500);

    it.interrupt();
    it.join();

    test.close(true);

    Assert.assertNull(it.getException());
    Assert.assertEquals(3, mcl.getAddedCount());
    Assert.assertEquals(0, mcl.getRemovedCount());
    Assert.assertEquals(4, test.getMessageCount());

}