⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mboxmailrepository.java

📁 邮件服务器系统 支持SMTP POP3 是著名的Apache写 有一定的参考价值
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
                }            }            } else {            StringBuffer line = new StringBuffer();            while ((c = ins.read()) != -1) {                if (c == 10) {                    foundSep = sepMatch.contains(line.toString(), sepMatchPattern);                    if (foundSep && inMessage) {//                        if ((DEEP_DEBUG) && (getLogger().isDebugEnabled())) {//                            getLogger().debug(this.getClass().getName() + " Invoking " + messAct.getClass() + " at " + prevMessageStart);//                        }                        MimeMessage endResult = messAct.messageAction(previousMessageSeparator, messageBuffer.toString(), prevMessageStart);                        if (messAct.isComplete()) {                            // I've got what I want so just exit                            return endResult;                        }                        previousMessageSeparator = line.toString();                        prevMessageStart = ins.getFilePointer() - line.length();                        messageBuffer = new StringBuffer();                        inMessage = true;                    }                    // Only done at the start (first header)                    if (foundSep && inMessage == false) {                        previousMessageSeparator = line.toString();                        inMessage = true;                    }                    if (!foundSep) {                        messageBuffer.append(line).append((char) c);                    }                    line = new StringBuffer(); // Reset buffer                } else {                    line.append((char) c);                }            }            }            if (messageBuffer.length() != 0) {                // process last message                return messAct.messageAction(previousMessageSeparator, messageBuffer.toString(), prevMessageStart);            }        } catch (IOException ioEx) {            getLogger().error("Unable to write file (General I/O problem) " + mboxFile, ioEx);        } catch (MalformedPatternException e) {            getLogger().error("Bad regex passed " + mboxFile, e);        } finally {            if ((DEEP_DEBUG) && (getLogger().isDebugEnabled())) {                StringBuffer logBuffer =                        new StringBuffer(128)                        .append(this.getClass().getName())                        .append(" Finished parsing ")                        .append(mboxFile);                getLogger().debug(logBuffer.toString());            }        }        return null;    }    /**     * Find a given message     * This method will first use selectMessage(key) to see if the key/offset combination allows us to skip     * parts of the file and only load the message we are interested in     *     * @param key The key of the message to find     */    private MimeMessage findMessage(String key) {        MimeMessage foundMessage = null;        final String keyValue = key;        // See if we can get the message by using the cache position first        foundMessage = selectMessage(key);        if (foundMessage == null) {            // If the message is not found something has changed from            // the cache.  The cache may have been invalidated by            // another method, or the file may have been replaced from            // underneath us.  Reload the cache, and try again.            mList = null;            loadKeys();            foundMessage = selectMessage(key);        }        return foundMessage;    }    /**     * Quickly find a message by using the stored message offsets     * @param key  The key of the message to find     */    private MimeMessage selectMessage(final String key) {        MimeMessage foundMessage = null;        // Can we find the key first        if (mList == null || !mList.containsKey(key)) {            // Not initiailised so no point looking            if ((DEEP_DEBUG) && (getLogger().isDebugEnabled())) {                StringBuffer logBuffer =                        new StringBuffer(128)                        .append(this.getClass().getName())                        .append(" mList - key not found ")                        .append(mboxFile);                getLogger().debug(logBuffer.toString());            }            return foundMessage;        }        long messageStart = ((Long) mList.get(key)).longValue();        if ((DEEP_DEBUG) && (getLogger().isDebugEnabled())) {            StringBuffer logBuffer =                    new StringBuffer(128)                    .append(this.getClass().getName())                    .append(" Load message starting at offset ")                    .append(messageStart)                    .append(" from file ")                    .append(mboxFile);            getLogger().debug(logBuffer.toString());        }        // Now try and find the position in the file        RandomAccessFile ins = null;        try {            ins = new RandomAccessFile(mboxFile, "r");            if (messageStart != 0) {                ins.seek(messageStart - 1);            }            MessageAction op = new MessageAction() {                public boolean isComplete() { return true; }                public MimeMessage messageAction(String messageSeparator, String bodyText, long messageStart) {                    try {                        if (key.equals(generateKeyValue(bodyText))) {                            getLogger().debug(this.getClass().getName() + " Located message. Returning MIME message");                            return convertTextToMimeMessage(bodyText);                        }                    } catch (NoSuchAlgorithmException e) {                        getLogger().error("MD5 not supported! ",e);                    }                    return null;                }            };            foundMessage = this.parseMboxFile(ins, op);        } catch (FileNotFoundException e) {            getLogger().error("Unable to save(open) file (File not found) " + mboxFile, e);        } catch (IOException e) {            getLogger().error("Unable to write file (General I/O problem) " + mboxFile, e);        } finally {            if (foundMessage == null) {                if ((DEEP_DEBUG) && (getLogger().isDebugEnabled())) {                    StringBuffer logBuffer =                            new StringBuffer(128)                            .append(this.getClass().getName())                            .append(" select - message not found ")                            .append(mboxFile);                    getLogger().debug(logBuffer.toString());                }            }            if (ins != null) try { ins.close(); } catch (IOException e) { getLogger().error("Unable to close file (General I/O problem) " + mboxFile, e); }            return foundMessage;        }    }    /**     * Load the message keys and file pointer offsets from disk     */    private synchronized void loadKeys() {        if (mList!=null) {            return;        }        RandomAccessFile ins = null;        try {            ins = new RandomAccessFile(mboxFile, "r");            long initialCapacity = (ins.length() >  MLISTPRESIZEFACTOR ? ins.length() /MLISTPRESIZEFACTOR  : 0);            if (initialCapacity < DEFAULTMLISTCAPACITY ) {                initialCapacity =  DEFAULTMLISTCAPACITY;            }            if (initialCapacity > Integer.MAX_VALUE) {                initialCapacity = Integer.MAX_VALUE - 1;            }            this.mList = new Hashtable((int)initialCapacity);            this.parseMboxFile(ins, new MessageAction() {                public boolean isComplete() { return false; }                public MimeMessage messageAction(String messageSeparator, String bodyText, long messageStart) {                    try {                        String key = generateKeyValue(bodyText);                        mList.put(key, new Long(messageStart));                        if ((DEEP_DEBUG) && (getLogger().isDebugEnabled())) {                            getLogger().debug(this.getClass().getName() + " Key " + key + " at " + messageStart);                        }                                            } catch (NoSuchAlgorithmException e) {                        getLogger().error("MD5 not supported! ",e);                    }                    return null;                }            });            //System.out.println("Done Load keys!");        } catch (FileNotFoundException e) {            getLogger().error("Unable to save(open) file (File not found) " + mboxFile, e);        } catch (IOException e) {            getLogger().error("Unable to write file (General I/O problem) " + mboxFile, e);        } finally {            if (ins != null) try { ins.close(); } catch (IOException e) { getLogger().error("Unable to close file (General I/O problem) " + mboxFile, e); }        }    }    /**     * @see org.apache.avalon.framework.context.Contextualizable#contextualize(org.apache.avalon.framework.context.Context)     */    public void contextualize(final Context context)            throws ContextException {        this.context = context;    }    /**     * Store the given email in the current mbox file     * @param mc The mail to store     */    public void store(MailImpl mc) {        if ((DEEP_DEBUG) && (getLogger().isDebugEnabled())) {            StringBuffer logBuffer =                    new StringBuffer(128)                    .append(this.getClass().getName())                    .append(" Will store message to file ")                    .append(mboxFile);            getLogger().debug(logBuffer.toString());        }        this.mList = null;        // Now make up the from header        String fromHeader = null;        String message = null;        try {            message = getRawMessage(mc.getMessage());            fromHeader = "From " + ((InternetAddress)mc.getMessage().getFrom()[0]).getAddress() + " " + dy.format(Calendar.getInstance().getTime());        } catch (IOException e) {            getLogger().error("Unable to parse mime message for " + mboxFile, e);        } catch (MessagingException e) {            getLogger().error("Unable to parse mime message for " + mboxFile, e);        }        // And save only the new stuff to disk        RandomAccessFile saveFile = null;        try {            saveFile = new RandomAccessFile(mboxFile, "rw");            saveFile.seek(saveFile.length()); // Move to the end            saveFile.writeBytes((fromHeader + "\n"));            saveFile.writeBytes((message + "\n"));            saveFile.close();        } catch (FileNotFoundException e) {            getLogger().error("Unable to save(open) file (File not found) " + mboxFile, e);        } catch (IOException e) {            getLogger().error("Unable to write file (General I/O problem) " + mboxFile, e);        }    }    /**     * Return the list of the current messages' keys     * @return A list of the keys of the emails currently loaded     */    public Iterator list() {        loadKeys();        // find the first message.  This is a trick to make sure that if        // the file is changed out from under us, we will detect it and        // correct for it BEFORE we return the iterator.        findMessage((String) mList.keySet().iterator().next());        if ((DEEP_DEBUG) && (getLogger().isDebugEnabled())) {            StringBuffer logBuffer =                    new StringBuffer(128)                    .append(this.getClass().getName())                    .append(" ")                    .append(mList.size())                    .append(" keys to be iterated over.");            getLogger().debug(logBuffer.toString());        }        return mList.keySet().iterator();    }    /**     * Get a message from the backing store (disk)     * @param key     * @return The mail found from the key. Returns null if the key is not found     */    public MailImpl retrieve(String key) {        loadKeys();        MailImpl res = null;        try {            MimeMessage foundMessage = findMessage(key);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -