001    /**
002     *
003     * Copyright 2003-2006 The Apache Software Foundation
004     *
005     *  Licensed under the Apache License, Version 2.0 (the "License");
006     *  you may not use this file except in compliance with the License.
007     *  You may obtain a copy of the License at
008     *
009     *     http://www.apache.org/licenses/LICENSE-2.0
010     *
011     *  Unless required by applicable law or agreed to in writing, software
012     *  distributed under the License is distributed on an "AS IS" BASIS,
013     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     *  See the License for the specific language governing permissions and
015     *  limitations under the License.
016     */
017    
018    package javax.mail;
019    
020    /**
021     * The context in which a piece of message content is contained.
022     *
023     * @version $Rev: 421852 $ $Date: 2006-07-14 03:02:19 -0700 (Fri, 14 Jul 2006) $
024     */
025    public class MessageContext {
026        private final Part part;
027    
028        /**
029         * Create a MessageContext object describing the context of the supplied Part.
030         *
031         * @param part the containing part
032         */
033        public MessageContext(Part part) {
034            this.part = part;
035        }
036    
037        /**
038         * Return the {@link Part} that contains the content.
039         *
040         * @return the part
041         */
042        public Part getPart() {
043            return part;
044        }
045    
046        /**
047         * Return the message that contains the content; if the Part is a {@link Multipart}
048         * then recurse up the chain until a {@link Message} is found.
049         *
050         * @return
051         */
052        public Message getMessage() {
053            return getMessageFrom(part);
054        }
055    
056        /**
057         * Return the session associated with the Message containing this Part.
058         *
059         * @return the session associated with this context's root message
060         */
061        public Session getSession() {
062            Message message = getMessage();
063            if (message == null) {
064                return null;
065            } else {
066                return message.session;
067            }
068        }
069    
070        // recurse up the chain of MultiPart/BodyPart paris until we hit a message
071        private Message getMessageFrom(Part p) {
072            while (p != null) {
073                if (p instanceof Message) {
074                    return (Message) p;
075                }
076                Multipart mp = ((BodyPart) p).getParent();
077                if (mp == null) {
078                    return null;
079                }
080                p = mp.getParent();
081            }
082            return null;
083        }
084    }