1. /*
  2. * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
  3. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  4. */
  5. package javax.mail.search;
  6. import javax.mail.*;
  7. /**
  8. * This class implements searches on Message Body.
  9. * Body searches are done only for:
  10. * (1) single-part messages whose primary-type is Text
  11. * OR
  12. * (2) multipart/mixed messages whose first body-part's
  13. * primary-type is Text. In this case, the search is
  14. * done on the first body-part.
  15. *
  16. * @author Bill Shannon
  17. * @author John Mani
  18. */
  19. public final class BodyTerm extends StringTerm {
  20. /**
  21. * Constructor
  22. * @param pattern The String to search for
  23. */
  24. public BodyTerm(String pattern) {
  25. // Note: comparison is case-insensitive
  26. super(pattern);
  27. }
  28. /**
  29. * The match method.
  30. *
  31. * @param msg The pattern search is applied on this Message's body
  32. * @return true if the pattern is found; otherwise false
  33. */
  34. public boolean match(Message msg) {
  35. Object data = null;
  36. String type = null;
  37. Part part = (Part)msg;
  38. try {
  39. type = part.getContentType();
  40. } catch (Exception e) {
  41. return false;
  42. }
  43. if (type.regionMatches(true, 0, "text/", 0, 5)) {
  44. // Single-part text
  45. try {
  46. data = part.getContent();
  47. } catch (Exception e) {}
  48. } else if (type.regionMatches(true, 0, "multipart/mixed",0,15)) {
  49. // multipart/mixed, get first BodyPart
  50. try {
  51. part = ((Multipart)part.getContent()).getBodyPart(0);
  52. type = part.getContentType();
  53. if (type.regionMatches(true, 0, "text/", 0, 5))
  54. data = part.getContent();
  55. } catch (Exception e) {}
  56. }
  57. if (data == null || !(data instanceof String))
  58. return false;
  59. /*
  60. * We invoke our superclass' (ie StringTerm) match method.
  61. * Note however that StringTerm.match() is not optimized
  62. * for substring searches in large string buffers. We really
  63. * need to have a StringTerm subclass, say BigStringTerm,
  64. * with its own match() method that uses a better algorithm ..
  65. * and then subclass BodyTerm from BigStringTerm.
  66. */
  67. return super.match((String)data);
  68. }
  69. /**
  70. * Equality comparison.
  71. */
  72. public boolean equals(Object obj) {
  73. if (!(obj instanceof BodyTerm))
  74. return false;
  75. return super.equals(obj);
  76. }
  77. }