View Javadoc

1   /**
2    *
3    * Copyright 2003-2006 The Apache Software Foundation
4    *
5    *  Licensed under the Apache License, Version 2.0 (the "License");
6    *  you may not use this file except in compliance with the License.
7    *  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   *  Unless required by applicable law or agreed to in writing, software
12   *  distributed under the License is distributed on an "AS IS" BASIS,
13   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   *  See the License for the specific language governing permissions and
15   *  limitations under the License.
16   */
17  
18  package javax.mail;
19  
20  /**
21   * The context in which a piece of message content is contained.
22   *
23   * @version $Rev: 421852 $ $Date: 2006-07-14 03:02:19 -0700 (Fri, 14 Jul 2006) $
24   */
25  public class MessageContext {
26      private final Part part;
27  
28      /**
29       * Create a MessageContext object describing the context of the supplied Part.
30       *
31       * @param part the containing part
32       */
33      public MessageContext(Part part) {
34          this.part = part;
35      }
36  
37      /**
38       * Return the {@link Part} that contains the content.
39       *
40       * @return the part
41       */
42      public Part getPart() {
43          return part;
44      }
45  
46      /**
47       * Return the message that contains the content; if the Part is a {@link Multipart}
48       * then recurse up the chain until a {@link Message} is found.
49       *
50       * @return
51       */
52      public Message getMessage() {
53          return getMessageFrom(part);
54      }
55  
56      /**
57       * Return the session associated with the Message containing this Part.
58       *
59       * @return the session associated with this context's root message
60       */
61      public Session getSession() {
62          Message message = getMessage();
63          if (message == null) {
64              return null;
65          } else {
66              return message.session;
67          }
68      }
69  
70      // recurse up the chain of MultiPart/BodyPart paris until we hit a message
71      private Message getMessageFrom(Part p) {
72          while (p != null) {
73              if (p instanceof Message) {
74                  return (Message) p;
75              }
76              Multipart mp = ((BodyPart) p).getParent();
77              if (mp == null) {
78                  return null;
79              }
80              p = mp.getParent();
81          }
82          return null;
83      }
84  }