Example usage for javax.mail.util SharedByteArrayInputStream SharedByteArrayInputStream

List of usage examples for javax.mail.util SharedByteArrayInputStream SharedByteArrayInputStream

Introduction

In this page you can find the example usage for javax.mail.util SharedByteArrayInputStream SharedByteArrayInputStream.

Prototype

public SharedByteArrayInputStream(byte[] buf) 

Source Link

Document

Create a SharedByteArrayInputStream representing the entire byte array.

Usage

From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java

@Test(timeout = 3000)
public void multilineGreeting() throws Exception {
    server = MockTcpServer.scenario().sendLine("220-first line").sendLine("220 second line").recvLine() // EHLO
            .sendLine("250 OK").recvLine() // MAIL FROM
            .sendLine("250 OK").recvLine() // RCPT TO
            .sendLine("250 OK").recvLine() // DATA
            .sendLine("354 OK").swallowUntil("\r\n.\r\n").sendLine("250 OK").recvLine() // QUIT
            .sendLine("221 bye").build().start(PORT);

    Session session = JMSession.getSession();
    Transport transport = session.getTransport("smtp");
    transport.connect("localhost", PORT, null, null);
    String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest";
    MimeMessage msg = new ZMimeMessage(session,
            new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1)));
    transport.sendMessage(msg, msg.getAllRecipients());
    transport.close();// ww w . j av  a2  s.  c  o  m

    server.shutdown(1000);
    Assert.assertEquals("EHLO localhost\r\n", server.replay());
    Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay());
    Assert.assertEquals("DATA\r\n", server.replay());
    Assert.assertEquals("QUIT\r\n", server.replay());
    Assert.assertNull(server.replay());
}

From source file:davmail.imap.ImapConnection.java

@Override
public void run() {
    final String capabilities;
    int imapIdleDelay = Settings.getIntProperty("davmail.imapIdleDelay") * 60;
    if (imapIdleDelay > 0) {
        capabilities = "CAPABILITY IMAP4REV1 AUTH=LOGIN IDLE MOVE";
    } else {/*from  w  ww.j  ava2s. c  o m*/
        capabilities = "CAPABILITY IMAP4REV1 AUTH=LOGIN MOVE";
    }

    String line;
    String commandId = null;
    IMAPTokenizer tokens;
    try {
        //            ExchangeSessionFactory.checkConfig();
        sendClient("* OK [" + capabilities + "] IMAP4rev1 DavMail " + DavGateway.getCurrentVersion()
                + " server ready");
        for (;;) {
            line = readClient();
            // unable to read line, connection closed ?
            if (line == null) {
                break;
            }

            tokens = new IMAPTokenizer(line);
            if (tokens.hasMoreTokens()) {
                commandId = tokens.nextToken();

                checkInfiniteLoop(line);

                if (tokens.hasMoreTokens()) {
                    String command = tokens.nextToken();

                    if ("LOGOUT".equalsIgnoreCase(command)) {
                        sendClient("* BYE Closing connection");
                        sendClient(commandId + " OK LOGOUT completed");
                        break;
                    }
                    if ("capability".equalsIgnoreCase(command)) {
                        sendClient("* " + capabilities);
                        sendClient(commandId + " OK CAPABILITY completed");
                    } else if ("login".equalsIgnoreCase(command)) {
                        parseCredentials(tokens);
                        // detect shared mailbox access
                        splitUserName();
                        try {
                            session = ExchangeSessionFactory.getInstance(userName, password);
                            sendClient(commandId + " OK Authenticated");
                            state = State.AUTHENTICATED;
                        } catch (Exception e) {
                            DavGatewayTray.error(e);
                            sendClient(commandId + " NO LOGIN failed");
                            state = State.INITIAL;
                        }
                    } else if ("AUTHENTICATE".equalsIgnoreCase(command)) {
                        if (tokens.hasMoreTokens()) {
                            String authenticationMethod = tokens.nextToken();
                            if ("LOGIN".equalsIgnoreCase(authenticationMethod)) {
                                try {
                                    sendClient("+ " + base64Encode("Username:"));
                                    state = State.LOGIN;
                                    userName = base64Decode(readClient());
                                    // detect shared mailbox access
                                    splitUserName();
                                    sendClient("+ " + base64Encode("Password:"));
                                    state = State.PASSWORD;
                                    password = base64Decode(readClient());
                                    session = ExchangeSessionFactory.getInstance(userName, password);
                                    sendClient(commandId + " OK Authenticated");
                                    state = State.AUTHENTICATED;
                                } catch (Exception e) {
                                    DavGatewayTray.error(e);
                                    sendClient(commandId + " NO LOGIN failed");
                                    state = State.INITIAL;
                                }
                            } else {
                                sendClient(commandId + " NO unsupported authentication method");
                            }
                        } else {
                            sendClient(commandId + " BAD authentication method required");
                        }
                    } else {
                        if (state != State.AUTHENTICATED) {
                            sendClient(commandId + " BAD command authentication required");
                        } else {
                            // check for expired session
                            session = ExchangeSessionFactory.getInstance(session, userName, password);
                            if ("lsub".equalsIgnoreCase(command) || "list".equalsIgnoreCase(command)) {
                                if (tokens.hasMoreTokens()) {
                                    String folderContext;
                                    if (baseMailboxPath == null) {
                                        folderContext = BASE64MailboxDecoder.decode(tokens.nextToken());
                                    } else {
                                        folderContext = baseMailboxPath
                                                + BASE64MailboxDecoder.decode(tokens.nextToken());
                                    }
                                    if (tokens.hasMoreTokens()) {
                                        String folderQuery = folderContext
                                                + BASE64MailboxDecoder.decode(tokens.nextToken());
                                        if (folderQuery.endsWith("%/%") && !"/%/%".equals(folderQuery)) {
                                            List<ExchangeSession.Folder> folders = session.getSubFolders(
                                                    folderQuery.substring(0, folderQuery.length() - 3), false);
                                            for (ExchangeSession.Folder folder : folders) {
                                                sendClient(
                                                        "* " + command + " (" + folder.getFlags() + ") \"/\" \""
                                                                + BASE64MailboxEncoder.encode(folder.folderPath)
                                                                + '\"');
                                                sendSubFolders(command, folder.folderPath, false);
                                            }
                                            sendClient(commandId + " OK " + command + " completed");
                                        } else if (folderQuery.endsWith("%") || folderQuery.endsWith("*")) {
                                            if ("/*".equals(folderQuery) || "/%".equals(folderQuery)
                                                    || "/%/%".equals(folderQuery)) {
                                                folderQuery = folderQuery.substring(1);
                                                if ("%/%".equals(folderQuery)) {
                                                    folderQuery = folderQuery.substring(0,
                                                            folderQuery.length() - 2);
                                                }
                                                sendClient(
                                                        "* " + command + " (\\HasChildren) \"/\" \"/public\"");
                                            }
                                            if ("*%".equals(folderQuery)) {
                                                folderQuery = "*";
                                            }
                                            boolean recursive = folderQuery.endsWith("*")
                                                    && !folderQuery.startsWith("/public");
                                            sendSubFolders(command,
                                                    folderQuery.substring(0, folderQuery.length() - 1),
                                                    recursive);
                                            sendClient(commandId + " OK " + command + " completed");
                                        } else {
                                            ExchangeSession.Folder folder = null;
                                            try {
                                                folder = session.getFolder(folderQuery);
                                            } catch (HttpForbiddenException e) {
                                                // access forbidden, ignore
                                                DavGatewayTray.debug(new BundleMessage(
                                                        "LOG_FOLDER_ACCESS_FORBIDDEN", folderQuery));
                                            } catch (HttpNotFoundException e) {
                                                // not found, ignore
                                                DavGatewayTray.debug(
                                                        new BundleMessage("LOG_FOLDER_NOT_FOUND", folderQuery));
                                            } catch (HttpException e) {
                                                // other errors, ignore
                                                DavGatewayTray
                                                        .debug(new BundleMessage("LOG_FOLDER_ACCESS_ERROR",
                                                                folderQuery, e.getMessage()));
                                            }
                                            if (folder != null) {
                                                sendClient(
                                                        "* " + command + " (" + folder.getFlags() + ") \"/\" \""
                                                                + BASE64MailboxEncoder.encode(folder.folderPath)
                                                                + '\"');
                                                sendClient(commandId + " OK " + command + " completed");
                                            } else {
                                                sendClient(commandId + " NO Folder not found");
                                            }
                                        }
                                    } else {
                                        sendClient(commandId + " BAD missing folder argument");
                                    }
                                } else {
                                    sendClient(commandId + " BAD missing folder argument");
                                }
                            } else if ("select".equalsIgnoreCase(command)
                                    || "examine".equalsIgnoreCase(command)) {
                                if (tokens.hasMoreTokens()) {
                                    @SuppressWarnings({ "NonConstantStringShouldBeStringBuffer" })
                                    String folderName = BASE64MailboxDecoder.decode(tokens.nextToken());
                                    if (baseMailboxPath != null && !folderName.startsWith("/")) {
                                        folderName = baseMailboxPath + folderName;
                                    }
                                    try {
                                        currentFolder = session.getFolder(folderName);
                                        currentFolder.loadMessages();
                                        sendClient("* " + currentFolder.count() + " EXISTS");
                                        sendClient("* " + currentFolder.recent + " RECENT");
                                        sendClient("* OK [UIDVALIDITY 1]");
                                        if (currentFolder.count() == 0) {
                                            sendClient("* OK [UIDNEXT 1]");
                                        } else {
                                            sendClient("* OK [UIDNEXT " + currentFolder.getUidNext() + ']');
                                        }
                                        sendClient(
                                                "* FLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk)");
                                        sendClient(
                                                "* OK [PERMANENTFLAGS (\\Answered \\Deleted \\Draft \\Flagged \\Seen $Forwarded Junk \\*)]");
                                        if ("select".equalsIgnoreCase(command)) {
                                            sendClient(
                                                    commandId + " OK [READ-WRITE] " + command + " completed");
                                        } else {
                                            sendClient(commandId + " OK [READ-ONLY] " + command + " completed");
                                        }
                                    } catch (HttpNotFoundException e) {
                                        sendClient(commandId + " NO Not found");
                                    } catch (HttpForbiddenException e) {
                                        sendClient(commandId + " NO Forbidden");
                                    }
                                } else {
                                    sendClient(commandId + " BAD command unrecognized");
                                }
                            } else if ("expunge".equalsIgnoreCase(command)) {
                                if (expunge(false)) {
                                    // need to refresh folder to avoid 404 errors
                                    session.refreshFolder(currentFolder);
                                }
                                sendClient(commandId + " OK " + command + " completed");
                            } else if ("close".equalsIgnoreCase(command)) {
                                expunge(true);
                                // deselect folder
                                currentFolder = null;
                                sendClient(commandId + " OK " + command + " completed");
                            } else if ("create".equalsIgnoreCase(command)) {
                                if (tokens.hasMoreTokens()) {
                                    String folderName = BASE64MailboxDecoder.decode(tokens.nextToken());
                                    session.createMessageFolder(folderName);
                                    sendClient(commandId + " OK folder created");
                                } else {
                                    sendClient(commandId + " BAD missing create argument");
                                }
                            } else if ("rename".equalsIgnoreCase(command)) {
                                String folderName = BASE64MailboxDecoder.decode(tokens.nextToken());
                                String targetName = BASE64MailboxDecoder.decode(tokens.nextToken());
                                try {
                                    session.moveFolder(folderName, targetName);
                                    sendClient(commandId + " OK rename completed");
                                } catch (HttpException e) {
                                    sendClient(commandId + " NO " + e.getMessage());
                                }
                            } else if ("delete".equalsIgnoreCase(command)) {
                                String folderName = BASE64MailboxDecoder.decode(tokens.nextToken());
                                try {
                                    session.deleteFolder(folderName);
                                    sendClient(commandId + " OK folder deleted");
                                } catch (HttpException e) {
                                    sendClient(commandId + " NO " + e.getMessage());
                                }
                            } else if ("uid".equalsIgnoreCase(command)) {
                                if (tokens.hasMoreTokens()) {
                                    String subcommand = tokens.nextToken();
                                    if ("fetch".equalsIgnoreCase(subcommand)) {
                                        if (currentFolder == null) {
                                            sendClient(commandId + " NO no folder selected");
                                        } else {
                                            String ranges = tokens.nextToken();
                                            if (ranges == null) {
                                                sendClient(commandId + " BAD missing range parameter");
                                            } else {
                                                String parameters = null;
                                                if (tokens.hasMoreTokens()) {
                                                    parameters = tokens.nextToken();
                                                }
                                                UIDRangeIterator uidRangeIterator = new UIDRangeIterator(
                                                        currentFolder.messages, ranges);
                                                while (uidRangeIterator.hasNext()) {
                                                    DavGatewayTray.switchIcon();
                                                    ExchangeSession.Message message = uidRangeIterator.next();
                                                    try {
                                                        handleFetch(message, uidRangeIterator.currentIndex,
                                                                parameters);
                                                    } catch (HttpNotFoundException e) {
                                                        LOGGER.warn("Ignore missing message "
                                                                + uidRangeIterator.currentIndex);
                                                    } catch (SocketException e) {
                                                        // client closed connection
                                                        throw e;
                                                    } catch (IOException e) {
                                                        DavGatewayTray.log(e);
                                                        sendClient(
                                                                commandId + " NO Unable to retrieve message: "
                                                                        + e.getMessage());
                                                    }
                                                }
                                                sendClient(commandId + " OK UID FETCH completed");
                                            }
                                        }

                                    } else if ("search".equalsIgnoreCase(subcommand)) {
                                        List<Long> uidList = handleSearch(tokens);
                                        StringBuilder buffer = new StringBuilder("* SEARCH");
                                        for (long uid : uidList) {
                                            buffer.append(' ');
                                            buffer.append(uid);
                                        }
                                        sendClient(buffer.toString());
                                        sendClient(commandId + " OK SEARCH completed");

                                    } else if ("store".equalsIgnoreCase(subcommand)) {
                                        UIDRangeIterator uidRangeIterator = new UIDRangeIterator(
                                                currentFolder.messages, tokens.nextToken());
                                        String action = tokens.nextToken();
                                        String flags = tokens.nextToken();
                                        handleStore(commandId, uidRangeIterator, action, flags);
                                    } else if ("copy".equalsIgnoreCase(subcommand)
                                            || "move".equalsIgnoreCase(subcommand)) {
                                        try {
                                            UIDRangeIterator uidRangeIterator = new UIDRangeIterator(
                                                    currentFolder.messages, tokens.nextToken());
                                            String targetName = BASE64MailboxDecoder.decode(tokens.nextToken());
                                            if (!uidRangeIterator.hasNext()) {
                                                sendClient(commandId + " NO " + "No message found");
                                            } else {
                                                while (uidRangeIterator.hasNext()) {
                                                    DavGatewayTray.switchIcon();
                                                    ExchangeSession.Message message = uidRangeIterator.next();
                                                    if ("copy".equalsIgnoreCase(subcommand)) {
                                                        session.copyMessage(message, targetName);
                                                    } else {
                                                        session.moveMessage(message, targetName);
                                                    }
                                                }
                                                sendClient(commandId + " OK " + subcommand + " completed");
                                            }
                                        } catch (HttpException e) {
                                            sendClient(commandId + " NO " + e.getMessage());
                                        }
                                    }
                                } else {
                                    sendClient(commandId + " BAD command unrecognized");
                                }
                            } else if ("search".equalsIgnoreCase(command)) {
                                if (currentFolder == null) {
                                    sendClient(commandId + " NO no folder selected");
                                } else {
                                    List<Long> uidList = handleSearch(tokens);
                                    if (uidList.isEmpty()) {
                                        sendClient("* SEARCH");
                                    } else {
                                        int currentIndex = 0;
                                        for (ExchangeSession.Message message : currentFolder.messages) {
                                            currentIndex++;
                                            if (uidList.contains(message.getImapUid())) {
                                                sendClient("* SEARCH " + currentIndex);
                                            }
                                        }
                                    }
                                    sendClient(commandId + " OK SEARCH completed");
                                }
                            } else if ("fetch".equalsIgnoreCase(command)) {
                                if (currentFolder == null) {
                                    sendClient(commandId + " NO no folder selected");
                                } else {
                                    RangeIterator rangeIterator = new RangeIterator(currentFolder.messages,
                                            tokens.nextToken());
                                    String parameters = null;
                                    if (tokens.hasMoreTokens()) {
                                        parameters = tokens.nextToken();
                                    }
                                    while (rangeIterator.hasNext()) {
                                        DavGatewayTray.switchIcon();
                                        ExchangeSession.Message message = rangeIterator.next();
                                        try {
                                            handleFetch(message, rangeIterator.currentIndex, parameters);
                                        } catch (HttpNotFoundException e) {
                                            LOGGER.warn("Ignore missing message " + rangeIterator.currentIndex);
                                        } catch (SocketException e) {
                                            // client closed connection, rethrow exception
                                            throw e;
                                        } catch (IOException e) {
                                            DavGatewayTray.log(e);
                                            sendClient(commandId + " NO Unable to retrieve message: "
                                                    + e.getMessage());
                                        }

                                    }
                                    sendClient(commandId + " OK FETCH completed");
                                }

                            } else if ("store".equalsIgnoreCase(command)) {
                                RangeIterator rangeIterator = new RangeIterator(currentFolder.messages,
                                        tokens.nextToken());
                                String action = tokens.nextToken();
                                String flags = tokens.nextToken();
                                handleStore(commandId, rangeIterator, action, flags);

                            } else if ("copy".equalsIgnoreCase(command) || "move".equalsIgnoreCase(command)) {
                                try {
                                    RangeIterator rangeIterator = new RangeIterator(currentFolder.messages,
                                            tokens.nextToken());
                                    String targetName = BASE64MailboxDecoder.decode(tokens.nextToken());
                                    if (!rangeIterator.hasNext()) {
                                        sendClient(commandId + " NO " + "No message found");
                                    } else {
                                        while (rangeIterator.hasNext()) {
                                            DavGatewayTray.switchIcon();
                                            ExchangeSession.Message message = rangeIterator.next();
                                            if ("copy".equalsIgnoreCase(command)) {
                                                session.copyMessage(message, targetName);
                                            } else {
                                                session.moveMessage(message, targetName);
                                            }
                                        }
                                        sendClient(commandId + " OK " + command + " completed");
                                    }
                                } catch (HttpException e) {
                                    sendClient(commandId + " NO " + e.getMessage());
                                }
                            } else if ("append".equalsIgnoreCase(command)) {
                                String folderName = BASE64MailboxDecoder.decode(tokens.nextToken());
                                HashMap<String, String> properties = new HashMap<String, String>();
                                String flags = null;
                                String date = null;
                                // handle optional flags
                                String nextToken = tokens.nextQuotedToken();
                                if (nextToken.startsWith("(")) {
                                    flags = StringUtil.removeQuotes(nextToken);
                                    if (tokens.hasMoreTokens()) {
                                        nextToken = tokens.nextToken();
                                        if (tokens.hasMoreTokens()) {
                                            date = nextToken;
                                            nextToken = tokens.nextToken();
                                        }
                                    }
                                } else if (tokens.hasMoreTokens()) {
                                    date = StringUtil.removeQuotes(nextToken);
                                    nextToken = tokens.nextToken();
                                }

                                if (flags != null) {
                                    // parse flags, on create read and draft flags are on the
                                    // same messageFlags property, 8 means draft and 1 means read
                                    StringTokenizer flagtokenizer = new StringTokenizer(flags);
                                    while (flagtokenizer.hasMoreTokens()) {
                                        String flag = flagtokenizer.nextToken();
                                        if ("\\Seen".equals(flag)) {
                                            if (properties.containsKey("draft")) {
                                                // draft message, add read flag
                                                properties.put("draft", "9");
                                            } else {
                                                // not (yet) draft, set read flag
                                                properties.put("draft", "1");
                                            }
                                        } else if ("\\Flagged".equals(flag)) {
                                            properties.put("flagged", "2");
                                        } else if ("\\Answered".equals(flag)) {
                                            properties.put("answered", "102");
                                        } else if ("$Forwarded".equals(flag)) {
                                            properties.put("forwarded", "104");
                                        } else if ("\\Draft".equals(flag)) {
                                            if (properties.containsKey("draft")) {
                                                // read message, add draft flag
                                                properties.put("draft", "9");
                                            } else {
                                                // not (yet) read, set draft flag
                                                properties.put("draft", "8");
                                            }
                                        } else if ("Junk".equals(flag)) {
                                            properties.put("junk", "1");
                                        }
                                    }
                                } else {
                                    // no flags, force not draft and unread
                                    properties.put("draft", "0");
                                }
                                // handle optional date
                                if (date != null) {
                                    SimpleDateFormat dateParser = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss Z",
                                            Locale.ENGLISH);
                                    Date dateReceived = dateParser.parse(date);
                                    SimpleDateFormat dateFormatter = new SimpleDateFormat(
                                            "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                                    dateFormatter.setTimeZone(ExchangeSession.GMT_TIMEZONE);

                                    properties.put("datereceived", dateFormatter.format(dateReceived));
                                }
                                int size = Integer.parseInt(StringUtil.removeQuotes(nextToken));
                                sendClient("+ send literal data");
                                byte[] buffer = in.readContent(size);
                                // empty line
                                readClient();
                                MimeMessage mimeMessage = new MimeMessage(null,
                                        new SharedByteArrayInputStream(buffer));

                                String messageName = UUID.randomUUID().toString() + ".EML";
                                try {
                                    session.createMessage(folderName, messageName, properties, mimeMessage);
                                    sendClient(commandId + " OK APPEND completed");
                                } catch (InsufficientStorageException e) {
                                    sendClient(commandId + " NO " + e.getMessage());
                                }
                            } else if ("idle".equalsIgnoreCase(command) && imapIdleDelay > 0) {
                                if (currentFolder != null) {
                                    sendClient("+ idling ");
                                    // clear cache before going to idle mode
                                    currentFolder.clearCache();
                                    DavGatewayTray.resetIcon();
                                    try {
                                        int count = 0;
                                        while (in.available() == 0) {
                                            if (++count >= imapIdleDelay) {
                                                count = 0;
                                                TreeMap<Long, String> previousImapFlagMap = currentFolder
                                                        .getImapFlagMap();
                                                if (session.refreshFolder(currentFolder)) {
                                                    handleRefresh(previousImapFlagMap,
                                                            currentFolder.getImapFlagMap());
                                                }
                                            }
                                            // sleep 1 second
                                            Thread.sleep(1000);
                                        }
                                        // read DONE line
                                        line = readClient();
                                        if ("DONE".equals(line)) {
                                            sendClient(commandId + " OK " + command + " terminated");
                                        } else {
                                            sendClient(commandId + " BAD command unrecognized");
                                        }
                                    } catch (IOException e) {
                                        // client connection closed
                                        throw new SocketException(e.getMessage());
                                    }
                                } else {
                                    sendClient(commandId + " NO no folder selected");
                                }
                            } else if ("noop".equalsIgnoreCase(command) || "check".equalsIgnoreCase(command)) {
                                if (currentFolder != null) {
                                    DavGatewayTray.debug(new BundleMessage("LOG_IMAP_COMMAND", command,
                                            currentFolder.folderPath));
                                    TreeMap<Long, String> previousImapFlagMap = currentFolder.getImapFlagMap();
                                    if (session.refreshFolder(currentFolder)) {
                                        handleRefresh(previousImapFlagMap, currentFolder.getImapFlagMap());
                                    }
                                }
                                sendClient(commandId + " OK " + command + " completed");
                            } else if ("subscribe".equalsIgnoreCase(command)
                                    || "unsubscribe".equalsIgnoreCase(command)) {
                                sendClient(commandId + " OK " + command + " completed");
                            } else if ("status".equalsIgnoreCase(command)) {
                                try {
                                    String encodedFolderName = tokens.nextToken();
                                    String folderName = BASE64MailboxDecoder.decode(encodedFolderName);
                                    ExchangeSession.Folder folder = session.getFolder(folderName);
                                    // must retrieve messages
                                    folder.loadMessages();
                                    String parameters = tokens.nextToken();
                                    StringBuilder answer = new StringBuilder();
                                    StringTokenizer parametersTokens = new StringTokenizer(parameters);
                                    while (parametersTokens.hasMoreTokens()) {
                                        String token = parametersTokens.nextToken();
                                        if ("MESSAGES".equalsIgnoreCase(token)) {
                                            answer.append("MESSAGES ").append(folder.count()).append(' ');
                                        }
                                        if ("RECENT".equalsIgnoreCase(token)) {
                                            answer.append("RECENT ").append(folder.recent).append(' ');
                                        }
                                        if ("UIDNEXT".equalsIgnoreCase(token)) {
                                            if (folder.count() == 0) {
                                                answer.append("UIDNEXT 1 ");
                                            } else {
                                                if (folder.count() == 0) {
                                                    answer.append("UIDNEXT 1 ");
                                                } else {
                                                    answer.append("UIDNEXT ").append(folder.getUidNext())
                                                            .append(' ');
                                                }
                                            }

                                        }
                                        if ("UIDVALIDITY".equalsIgnoreCase(token)) {
                                            answer.append("UIDVALIDITY 1 ");
                                        }
                                        if ("UNSEEN".equalsIgnoreCase(token)) {
                                            answer.append("UNSEEN ").append(folder.unreadCount).append(' ');
                                        }
                                    }
                                    sendClient("* STATUS \"" + encodedFolderName + "\" ("
                                            + answer.toString().trim() + ')');
                                    sendClient(commandId + " OK " + command + " completed");
                                } catch (HttpException e) {
                                    sendClient(commandId + " NO folder not found");
                                }
                            } else {
                                sendClient(commandId + " BAD command unrecognized");
                            }
                        }
                    }

                } else {
                    sendClient(commandId + " BAD missing command");
                }
            } else {
                sendClient("BAD Null command");
            }
            DavGatewayTray.resetIcon();
        }

        os.flush();
    } catch (SocketTimeoutException e) {
        DavGatewayTray.debug(new BundleMessage("LOG_CLOSE_CONNECTION_ON_TIMEOUT"));
        try {
            sendClient("* BYE Closing connection");
        } catch (IOException e1) {
            DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_CLOSING_CONNECTION_ON_TIMEOUT"));
        }
    } catch (SocketException e) {
        LOGGER.warn(BundleMessage.formatLog("LOG_CLIENT_CLOSED_CONNECTION"));
    } catch (Exception e) {
        DavGatewayTray.log(e);
        try {
            String message = ((e.getMessage() == null) ? e.toString() : e.getMessage()).replaceAll("\\n", " ");
            if (commandId != null) {
                sendClient(commandId + " BAD unable to handle request: " + message);
            } else {
                sendClient("* BAD unable to handle request: " + message);
            }
        } catch (IOException e2) {
            DavGatewayTray.warn(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2);
        }
    } finally {
        close();
    }
    DavGatewayTray.resetIcon();
}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * Send message./*from   www . jav  a  2  s. co  m*/
 *
 * @param messageBody MIME message body
 * @throws IOException on error
 */
public void sendMessage(byte[] messageBody) throws IOException {
    try {
        sendMessage(new MimeMessage(null, new SharedByteArrayInputStream(messageBody)));
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:com.zimbra.cs.zclient.ZMailboxUtil.java

private void addMessage(String folderId, String flags, String tags, long date, File file, boolean validate)
        throws ServiceException, IOException {
    //String aid = mMbox.uploadAttachments(new File[] {file}, 5000);

    InputStream in = new BufferedInputStream(new FileInputStream(file)); // Buffering required for gzip check
    long sizeHint = -1;
    if (ByteUtil.isGzipped(in)) {
        in = new GZIPInputStream(in);
    } else {/*from  w w  w . j a v  a2s  .c  om*/
        sizeHint = file.length();
    }

    byte[] data = ByteUtil.getContent(in, (int) sizeHint);
    if (validate && !EmailUtil.isRfc822Message(new ByteArrayInputStream(data))) {
        throw ZClientException.CLIENT_ERROR(file.getPath() + " does not contain a valid RFC 822 message", null);
    }

    try {
        if (date == -1) {
            MimeMessage mm = new ZMimeMessage(mSession, new SharedByteArrayInputStream(data));
            Date d = mm.getSentDate();
            if (d != null)
                date = d.getTime();
            else
                date = 0;
        }
    } catch (MessagingException e) {
        date = 0;
    }
    String id = mMbox.addMessage(folderId, flags, tags, date, data, false);
    stdout.format("%s (%s)%n", id, file.getPath());
}

From source file:org.apache.james.core.MimeMessageInputStreamSource.java

/**
 * Get an input stream to retrieve the data stored in the temporary file
 *
 * @return a <code>BufferedInputStream</code> containing the data
 *///ww w  . java2  s.co  m
public synchronized InputStream getInputStream() throws IOException {
    InputStream in;
    if (out.isInMemory()) {
        in = new SharedByteArrayInputStream(out.getData());
    } else {
        in = new SharedFileInputStream(out.getFile());
    }
    streams.add(in);
    return in;
}

From source file:org.apache.james.core.MimeMessageWrapper.java

public MimeMessageWrapper(MimeMessage original) throws MessagingException {
    this(Session.getDefaultInstance(System.getProperties()));
    flags = original.getFlags();/*from w ww.  j ava  2 s  .  co m*/

    if (source == null) {
        InputStream in;

        boolean useMemoryCopy = false;
        String memoryCopy = System.getProperty(USE_MEMORY_COPY);
        if (memoryCopy != null) {
            useMemoryCopy = Boolean.valueOf(memoryCopy);
        }
        try {

            if (useMemoryCopy) {
                ByteArrayOutputStream bos;
                int size = original.getSize();
                if (size > 0) {
                    bos = new ByteArrayOutputStream(size);
                } else {
                    bos = new ByteArrayOutputStream();
                }
                original.writeTo(bos);
                bos.close();
                in = new SharedByteArrayInputStream(bos.toByteArray());
                parse(in);
                in.close();
                saved = true;
            } else {
                MimeMessageInputStreamSource src = new MimeMessageInputStreamSource(
                        "MailCopy-" + UUID.randomUUID().toString());
                OutputStream out = src.getWritableOutputStream();
                original.writeTo(out);
                out.close();
                source = src;
            }

        } catch (IOException ex) {
            // should never happen, but just in case...
            throw new MessagingException("IOException while copying message", ex);
        }
    }
}

From source file:org.apache.james.jmap.model.MailboxMessageTest.java

@Test
public void emptyMailShouldBeLoadedIntoMessage() throws Exception {
    MailboxMessage testMail = new SimpleMailboxMessage(INTERNAL_DATE, 0, 0,
            new SharedByteArrayInputStream("".getBytes()), new Flags(Flag.SEEN), new PropertyBuilder(),
            MAILBOX_ID);/*  w w w  . j  av a2s . c om*/
    testMail.setModSeq(MOD_SEQ);
    Message testee = messageFactory.fromMailboxMessage(testMail, ImmutableList.of(),
            x -> MessageId.of("user|box|" + x));
    assertThat(testee).extracting(Message::getPreview, Message::getSize, Message::getSubject,
            Message::getHeaders, Message::getDate)
            .containsExactly("(Empty)", 0L, "", ImmutableMap.of(), ZONED_DATE);
}

From source file:org.apache.james.jmap.model.MailboxMessageTest.java

@Test
public void flagsShouldBeSetIntoMessage() throws Exception {
    Flags flags = new Flags();
    flags.add(Flag.ANSWERED);/*from  w  w  w.  j a  v a2 s.c o m*/
    flags.add(Flag.FLAGGED);
    flags.add(Flag.DRAFT);
    MailboxMessage testMail = new SimpleMailboxMessage(INTERNAL_DATE, 0, 0,
            new SharedByteArrayInputStream("".getBytes()), flags, new PropertyBuilder(), MAILBOX_ID);
    testMail.setModSeq(MOD_SEQ);
    Message testee = messageFactory.fromMailboxMessage(testMail, ImmutableList.of(),
            x -> MessageId.of("user|box|" + x));
    assertThat(testee)
            .extracting(Message::isIsUnread, Message::isIsFlagged, Message::isIsAnswered, Message::isIsDraft)
            .containsExactly(true, true, true, true);
}

From source file:org.apache.james.jmap.model.MailboxMessageTest.java

@Test
public void headersShouldBeSetIntoMessage() throws Exception {
    String headers = "From: user <user@domain>\n" + "Subject: test subject\n"
            + "To: user1 <user1@domain>, user2 <user2@domain>\n" + "Cc: usercc <usercc@domain>\n"
            + "Bcc: userbcc <userbcc@domain>\n" + "Reply-To: \"user to reply to\" <user.reply.to@domain>\n"
            + "In-Reply-To: <SNT124-W2664003139C1E520CF4F6787D30@phx.gbl>\n"
            + "Other-header: other header value";
    MailboxMessage testMail = new SimpleMailboxMessage(INTERNAL_DATE, headers.length(), headers.length(),
            new SharedByteArrayInputStream(headers.getBytes()), new Flags(Flag.SEEN), new PropertyBuilder(),
            MAILBOX_ID);/*from w  ww . j av a 2  s . c  o m*/
    testMail.setModSeq(MOD_SEQ);

    Emailer user = Emailer.builder().name("user").email("user@domain").build();
    Emailer user1 = Emailer.builder().name("user1").email("user1@domain").build();
    Emailer user2 = Emailer.builder().name("user2").email("user2@domain").build();
    Emailer usercc = Emailer.builder().name("usercc").email("usercc@domain").build();
    Emailer userbcc = Emailer.builder().name("userbcc").email("userbcc@domain").build();
    Emailer userRT = Emailer.builder().name("user to reply to").email("user.reply.to@domain").build();
    ImmutableMap<String, String> headersMap = ImmutableMap.<String, String>builder()
            .put("cc", "usercc <usercc@domain>").put("bcc", "userbcc <userbcc@domain>")
            .put("subject", "test subject").put("from", "user <user@domain>")
            .put("to", "user1 <user1@domain>, user2 <user2@domain>")
            .put("reply-to", "\"user to reply to\" <user.reply.to@domain>")
            .put("in-reply-to", "<SNT124-W2664003139C1E520CF4F6787D30@phx.gbl>")
            .put("other-header", "other header value").build();
    Message testee = messageFactory.fromMailboxMessage(testMail, ImmutableList.of(),
            x -> MessageId.of("user|box|" + x));
    Message expected = Message.builder().id(MessageId.of("user|box|0")).blobId(BlobId.of("0"))
            .threadId("user|box|0").mailboxIds(ImmutableList.of(MAILBOX_ID.serialize()))
            .inReplyToMessageId("<SNT124-W2664003139C1E520CF4F6787D30@phx.gbl>").headers(headersMap).from(user)
            .to(ImmutableList.of(user1, user2)).cc(ImmutableList.of(usercc)).bcc(ImmutableList.of(userbcc))
            .replyTo(ImmutableList.of(userRT)).subject("test subject").date(ZONED_DATE).size(headers.length())
            .preview("(Empty)").build();
    assertThat(testee).isEqualToComparingFieldByField(expected);
}

From source file:org.apache.james.jmap.model.MailboxMessageTest.java

@Test
public void textBodyShouldBeSetIntoMessage() throws Exception {
    String headers = "Subject: test subject\n";
    String body = "Mail body";
    String mail = headers + "\n" + body;
    MailboxMessage testMail = new SimpleMailboxMessage(INTERNAL_DATE, mail.length(), headers.length(),
            new SharedByteArrayInputStream(mail.getBytes()), new Flags(Flag.SEEN), new PropertyBuilder(),
            MAILBOX_ID);/*from   w  w w  .j av a 2  s  .  c o  m*/
    testMail.setModSeq(MOD_SEQ);
    Message testee = messageFactory.fromMailboxMessage(testMail, ImmutableList.of(),
            x -> MessageId.of("user|box|" + x));
    assertThat(testee.getTextBody()).hasValue("Mail body");
}