imapmessage.java

来自「此源码是在sun站点上提供的javamail基础上改进。用来解决中文邮件或很多国」· Java 代码 · 共 1,442 行 · 第 1/3 页

JAVA
1,442
字号
    public void setContentID(String cid) throws MessagingException {
	throw new IllegalWriteException("IMAPMessage is read-only");
    }

    /**
     * Get the Content-MD5.
     */
    public String getContentMD5() throws MessagingException {
	checkExpunged();
	loadBODYSTRUCTURE();
	return bs.md5;
    }

    public void setContentMD5(String md5) throws MessagingException {
	throw new IllegalWriteException("IMAPMessage is read-only");
    }

    /**
     * Get the decoded Content-Description.
     */
    public String getDescription() throws MessagingException {
	checkExpunged();

	if (description != null) // cached value ?
	    return description;
	
	loadBODYSTRUCTURE();
	if (bs.description == null)
	    return null;
	
	try {
	    description = MimeUtility.decodeText(bs.description);
	} catch (UnsupportedEncodingException ex) {
	    description = bs.description;
	}

	return description;
    }

    public void setDescription(String description, String charset) 
			throws MessagingException {
	throw new IllegalWriteException("IMAPMessage is read-only");
    }

    /**
     * Get the Message-ID.
     */
    public String getMessageID() throws MessagingException {
	checkExpunged();
	loadEnvelope();
	return envelope.messageId;
    }

    /**
     * Get the "filename" Disposition parameter. (Only available in
     * IMAP4rev1). If thats not available, get the "name" ContentType
     * parameter.
     */
    public String getFileName() throws MessagingException {
	checkExpunged();

	String filename = null;
	loadBODYSTRUCTURE();

	if (bs.dParams != null)
	    filename = bs.dParams.get("filename");
	if (filename == null && bs.cParams != null)
	    filename = bs.cParams.get("name");
	return filename;
    }

    public void setFileName(String filename) throws MessagingException {
	throw new IllegalWriteException("IMAPMessage is read-only");
    }

    /**
     * Get all the bytes for this message. Overrides getContentStream()
     * in MimeMessage. This method is ultimately used by the DataHandler
     * to obtain the input stream for this message.
     *
     * @see javax.mail.internet.MimeMessage#getContentStream
     */
    protected InputStream getContentStream() throws MessagingException {
	InputStream is = null;
	boolean pk = getPeek();	// get before acquiring message cache lock

        // Acquire MessageCacheLock, to freeze seqnum.
        synchronized(getMessageCacheLock()) {
	    try {
		IMAPProtocol p = getProtocol();

		// This message could be expunged when we were waiting
		// to acquire the lock ...
		checkExpunged();

		if (p.isREV1() && (getFetchBlockSize() != -1)) // IMAP4rev1
		    return new IMAPInputStream(this, toSection("TEXT"),
					   bs != null ? bs.size : -1, pk);

		if (p.isREV1()) {
		    BODY b;
		    if (pk)
			b = p.peekBody(getSequenceNumber(), toSection("TEXT"));
		    else
			b = p.fetchBody(getSequenceNumber(), toSection("TEXT"));
		    if (b != null)
			is = b.getByteArrayInputStream();
		} else {
		    RFC822DATA rd = p.fetchRFC822(getSequenceNumber(), "TEXT");
		    if (rd != null)
			is = rd.getByteArrayInputStream();
		}
	    } catch (ConnectionException cex) {
		throw new FolderClosedException(folder, cex.getMessage());
	    } catch (ProtocolException pex) {
		forceCheckExpunged();
		throw new MessagingException(pex.getMessage(), pex);
	    }
	}

	if (is == null)
	    throw new MessagingException("No content");
	else
	    return is;
    }

    /**
     * Get the DataHandler object for this message.
     */
    public synchronized DataHandler getDataHandler()
		throws MessagingException {
	checkExpunged();

	if (dh == null) {
	    loadBODYSTRUCTURE();
	    if (type == null) { // type not yet computed
		// generate content-type from BODYSTRUCTURE
		ContentType ct = new ContentType(bs.type, bs.subtype,
						 bs.cParams);
		type = ct.toString();
	    }

	    /* Special-case Multipart and Nested content. All other
	     * cases are handled by the superclass.
	     */
	    if (bs.isMulti())
		dh = new DataHandler(
			new IMAPMultipartDataSource(this, bs.bodies, 
						    sectionId, this)
		     );
	    else if (bs.isNested() && isREV1())
		/* Nested messages are handled specially only for
		 * IMAP4rev1. IMAP4 doesn't provide enough support to 
		 * FETCH the components of nested messages
		 */
		dh = new DataHandler(
			    new IMAPNestedMessage(this, 
				bs.bodies[0], 
				bs.envelope,
				sectionId == null ? "1" : sectionId + ".1"),
			    type
		     );
	}

	return super.getDataHandler();
    }

    public void setDataHandler(DataHandler content) 
			throws MessagingException {
	throw new IllegalWriteException("IMAPMessage is read-only");
    }

    /**
     * Write out the bytes into the given outputstream.
     */
    public void writeTo(OutputStream os)
				throws IOException, MessagingException {
	InputStream is = null;
	boolean pk = getPeek();	// get before acquiring message cache lock

        // Acquire MessageCacheLock, to freeze seqnum.
        synchronized(getMessageCacheLock()) {
	    try {
		IMAPProtocol p = getProtocol();

		checkExpunged(); // insure this message is not expunged

		if (p.isREV1()) {
		    BODY b;
		    if (pk)
			b = p.peekBody(getSequenceNumber(), sectionId);
		    else
			b = p.fetchBody(getSequenceNumber(), sectionId);
		    if (b != null)
			is = b.getByteArrayInputStream();
		} else {
		    RFC822DATA rd = p.fetchRFC822(getSequenceNumber(), null);
		    if (rd != null)
			is = rd.getByteArrayInputStream();
		}
	    } catch (ConnectionException cex) {
		throw new FolderClosedException(folder, cex.getMessage());
	    } catch (ProtocolException pex) {
		forceCheckExpunged();
		throw new MessagingException(pex.getMessage(), pex);
	    }
	}

	if (is == null)
	    throw new MessagingException("No content");
	
	// write out the bytes
	byte[] bytes = new byte[1024];
	int count;
	while ((count = is.read(bytes)) != -1)
	    os.write(bytes, 0, count);
    }

    /**
     * Get the named header.
     */
    public String[] getHeader(String name) throws MessagingException {
	checkExpunged();

	if (isHeaderLoaded(name)) // already loaded ?
	    return headers.getHeader(name);

	// Load this particular header
	InputStream is = null;

        // Acquire MessageCacheLock, to freeze seqnum.
        synchronized(getMessageCacheLock()) {
	    try {
		IMAPProtocol p = getProtocol();

		// This message could be expunged when we were waiting
		// to acquire the lock ...
		checkExpunged();

		if (p.isREV1()) {
		    BODY b = p.peekBody(getSequenceNumber(), 
				toSection("HEADER.FIELDS (" + name + ")")
			     );
		    if (b != null)
			is = b.getByteArrayInputStream();
		} else {
		    RFC822DATA rd = p.fetchRFC822(getSequenceNumber(), 
					"HEADER.LINES (" + name + ")");
		    if (rd != null)
			is = rd.getByteArrayInputStream();
		}
	    } catch (ConnectionException cex) {
		throw new FolderClosedException(folder, cex.getMessage());
	    } catch (ProtocolException pex) {
		forceCheckExpunged();
		throw new MessagingException(pex.getMessage(), pex);
	    }
	}

	// if we get this far without "is" being set, something has gone
	// wrong; prevent a later NullPointerException and return null here
	if (is == null)
	    return null;

	if (headers == null)
	    headers = new InternetHeaders();
	headers.load(is); // load this header into the Headers object.
	setHeaderLoaded(name); // Mark this header as loaded

	return headers.getHeader(name);
    }

    /**
     * Get the named header.
     */
    public String getHeader(String name, String delimiter)
			throws MessagingException {
	checkExpunged();

	// force the header to be loaded by invoking getHeader(name)
	if (getHeader(name) == null)
	    return null;
	return headers.getHeader(name, delimiter);
    }

    public void setHeader(String name, String value)
			throws MessagingException {
	throw new IllegalWriteException("IMAPMessage is read-only");
    }

    public void addHeader(String name, String value)
			throws MessagingException {
	throw new IllegalWriteException("IMAPMessage is read-only");
    }
	    
    public void removeHeader(String name)
			throws MessagingException {
	throw new IllegalWriteException("IMAPMessage is read-only");
    }

    /**
     * Get all headers.
     */
    public Enumeration getAllHeaders() throws MessagingException {
	checkExpunged();
	loadHeaders();
	return super.getAllHeaders();
    }

    /**
     * Get matching headers.
     */
    public Enumeration getMatchingHeaders(String[] names)
			throws MessagingException {
	checkExpunged();
	loadHeaders();
	return super.getMatchingHeaders(names);
    }

    /**
     * Get non-matching headers.
     */
    public Enumeration getNonMatchingHeaders(String[] names)
			throws MessagingException {
	checkExpunged();
	loadHeaders();
	return super.getNonMatchingHeaders(names);
    }

    public void addHeaderLine(String line) throws MessagingException {
	throw new IllegalWriteException("IMAPMessage is read-only");
    }

    /**
     * Get all header-lines.
     */
    public Enumeration getAllHeaderLines() throws MessagingException {
	checkExpunged();
	loadHeaders();
	return super.getAllHeaderLines();
    }

    /**
     * Get all matching header-lines.
     */
    public Enumeration getMatchingHeaderLines(String[] names)
			throws MessagingException {
	checkExpunged();
	loadHeaders();
	return super.getMatchingHeaderLines(names);
    }

    /**
     * Get all non-matching headerlines.
     */
    public Enumeration getNonMatchingHeaderLines(String[] names)
			throws MessagingException {
	checkExpunged();
	loadHeaders();
	return super.getNonMatchingHeaderLines(names);
    }

    /**
     * Get the Flags for this message.
     */
    public synchronized Flags getFlags() throws MessagingException {
	checkExpunged();
	loadFlags();
	return super.getFlags();
    }

    /**
     * Test if the given Flags are set in this message.
     */
    public synchronized boolean isSet(Flags.Flag flag)
				throws MessagingException {
	checkExpunged();
	loadFlags();
	return super.isSet(flag);
    }

    /**
     * Set/Unset the given flags in this message.
     */
    public synchronized void setFlags(Flags flag, boolean set)
			throws MessagingException {
        // Acquire MessageCacheLock, to freeze seqnum.
        synchronized(getMessageCacheLock()) {
	    try {
		IMAPProtocol p = getProtocol();
		checkExpunged(); // Insure that this message is not expunged
		p.storeFlags(getSequenceNumber(), flag, set);
	    } catch (ConnectionException cex) {
		throw new FolderClosedException(folder, cex.getMessage());
	    } catch (ProtocolException pex) {
		throw new MessagingException(pex.getMessage(), pex);
	    }
	}
    }

    /**
     * Set whether or not to use the PEEK variant of FETCH when
     * fetching message content.
     *
     * @since	JavaMail 1.3.3
     */
    public synchronized void setPeek(boolean peek) {
	this.peek = peek;
    }

    /**
     * Get whether or not to use the PEEK variant of FETCH when
     * fetching message content.
     *
     * @since	JavaMail 1.3.3
     */
    public synchronized boolean getPeek() {
	return peek;
    }

    /**
     * Invalidate cached header and envelope information for this
     * message.  Subsequent accesses of this information will
     * cause it to be fetched from the server.
     *
     * @since	JavaMail 1.3.3
     */
    public synchronized void invalidateHeaders() {
	headersLoaded = false;
	loadedHeaders = null;
	envelope = null;
	bs = null;
	receivedDate = null;
	size = -1;
	type = null;
	subject = null;
	description = null;
    }

    /**
     * The prefetch method. Called from IMAPFolder.fetch()
     */
    static void fetch(IMAPFolder folder, Message[] msgs, 
		      FetchProfile fp) throws MessagingException {

	/* This class implements the test to be done on each
	 * message in the folder. The test is to check whether the
	 * message has already cached all the items requested in the
	 * FetchProfile. If any item is missing, the test succeeds and
	 * breaks out.
	 */
	class FetchProfileCondition implements Utility.Condition {
	    private boolean needEnvelope = false;
	    private boolean needFlags = false;
	    private boolean needBodyStructure = false;
	    private boolean needUID = false;
	    private boolean needHeaders = false;
	    private boolean needSize = false;
	    private String[] hdrs = null;

	    public FetchProfileCondition(FetchProfile fp) {
		if (fp.contains(FetchProfile.Item.ENVELOPE))
		    needEnvelope = true;
		if (fp.contains(FetchProfile.Item.FLAGS))
		    needFlags = true;
		if (fp.contains(FetchProfile.Item.CONTENT_INFO))
		    needBodyStructure = true;
		if (fp.contains(UIDFolder.FetchProfileItem.UID))
		    needUID = true;
		if (fp.contains(IMAPFolder.FetchProfileItem.HEADERS))
		    needHeaders = true;
		if (fp.contains(IMAPFolder.FetchProfileItem.SIZE))
		    needSize = true;
		hdrs = fp.getHeaderNames();
	    }

	    // The actual test.
	    public boolean test(IMAPMessage m) {
		if (needEnvelope && m._getEnvelope() == null)
		    return true; // no envelope
		if (needFlags && m._getFlags() == null)

⌨️ 快捷键说明

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