1. /*
  2. * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
  3. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  4. */
  5. /*
  6. * @(#)MessageContext.java 1.3 99/12/06
  7. *
  8. * Copyright (c) 1998 by Sun Microsystems, Inc.
  9. * All Rights Reserved.
  10. */
  11. package javax.mail;
  12. /**
  13. * The context in which a piece of Message content is contained. A
  14. * <code>MessageContext</code> object is returned by the
  15. * <code>getMessageContext</code> method of the
  16. * <code>MessageAware</code> interface. <code>MessageAware</code> is
  17. * typically implemented by <code>DataSources</code> to allow a
  18. * <code>DataContentHandler</code> to pass on information about the
  19. * context in which a data content object is operating.
  20. *
  21. * @see javax.mail.MessageAware
  22. * @see javax.activation.DataSource
  23. * @see javax.activation.DataContentHandler
  24. * @since JavaMail 1.1
  25. */
  26. public class MessageContext {
  27. private Part part;
  28. /**
  29. * Create a MessageContext object describing the context of the given Part.
  30. */
  31. public MessageContext(Part part) {
  32. this.part = part;
  33. }
  34. /**
  35. * Return the Part that contains the content.
  36. *
  37. * @return the containing Part, or null if not known
  38. */
  39. public Part getPart() {
  40. return part;
  41. }
  42. /**
  43. * Return the Message that contains the content.
  44. * Follows the parent chain up through containing Multipart
  45. * objects until it comes to a Message object, or null.
  46. *
  47. * @return the containing Message, or null if not known
  48. */
  49. public Message getMessage() {
  50. try {
  51. return getMessage(part);
  52. } catch (MessagingException ex) {
  53. return null;
  54. }
  55. }
  56. /**
  57. * Return the Message containing an arbitrary Part.
  58. * Follows the parent chain up through containing Multipart
  59. * objects until it comes to a Message object, or null.
  60. *
  61. * @return the containing Message
  62. * @see javax.mail.BodyPart#getParent
  63. * @see javax.mail.Multipart#getParent
  64. */
  65. private static Message getMessage(Part p) throws MessagingException {
  66. while (p != null) {
  67. if (p instanceof Message)
  68. return (Message)p;
  69. BodyPart bp = (BodyPart)p;
  70. Multipart mp = bp.getParent();
  71. p = mp.getParent();
  72. }
  73. return null;
  74. }
  75. /**
  76. * Return the Session we're operating in.
  77. *
  78. * @return the Session, or null if not known
  79. */
  80. public Session getSession() {
  81. Message msg = getMessage();
  82. return msg != null ? msg.session : null;
  83. }
  84. }