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. /**
  7. * This class implements the match method for Strings. The current
  8. * implementation provides only for substring matching. We
  9. * could add comparisons (like strcmp ...).
  10. *
  11. * @author Bill Shannon
  12. * @author John Mani
  13. */
  14. public abstract class StringTerm extends SearchTerm {
  15. /**
  16. * The pattern.
  17. *
  18. * @serial
  19. */
  20. protected String pattern;
  21. /**
  22. * Ignore case when comparing?
  23. *
  24. * @serial
  25. */
  26. protected boolean ignoreCase;
  27. protected StringTerm(String pattern) {
  28. this.pattern = pattern;
  29. ignoreCase = true;
  30. }
  31. protected StringTerm(String pattern, boolean ignoreCase) {
  32. this.pattern = pattern;
  33. this.ignoreCase = ignoreCase;
  34. }
  35. /**
  36. * Return the string to match with.
  37. */
  38. public String getPattern() {
  39. return pattern;
  40. }
  41. /**
  42. * Return true if we should ignore case when matching.
  43. */
  44. public boolean getIgnoreCase() {
  45. return ignoreCase;
  46. }
  47. protected boolean match(String s) {
  48. int len = s.length() - pattern.length();
  49. for (int i=0; i <= len; i++) {
  50. if (s.regionMatches(ignoreCase, i,
  51. pattern, 0, pattern.length()))
  52. return true;
  53. }
  54. return false;
  55. }
  56. /**
  57. * Equality comparison.
  58. */
  59. public boolean equals(Object obj) {
  60. if (!(obj instanceof StringTerm))
  61. return false;
  62. StringTerm st = (StringTerm)obj;
  63. if (ignoreCase)
  64. return st.pattern.equalsIgnoreCase(this.pattern) &&
  65. st.ignoreCase == this.ignoreCase;
  66. else
  67. return st.pattern.equals(this.pattern) &&
  68. st.ignoreCase == this.ignoreCase;
  69. }
  70. /**
  71. * Compute a hashCode for this object.
  72. */
  73. public int hashCode() {
  74. return ignoreCase ? pattern.hashCode() : ~pattern.hashCode();
  75. }
  76. }