1 21 22 package org.armedbear.j.mail; 23 24 import java.util.Calendar ; 25 26 public final class RelativeDateMailboxFilter extends MailboxFilter 27 { 28 private boolean after; 29 private int days; 30 private int months; 31 private int years; 32 33 private RFC822Date begin; 34 private RFC822Date end; 35 36 private long initMillis; 37 38 private RelativeDateMailboxFilter(int days, int months, int years, boolean after) 39 { 40 this.after = after; 41 this.days = days; 42 this.months = months; 43 this.years = years; 44 } 45 46 public static MailboxFilter getMailboxFilter(String pattern) 47 { 48 if (pattern.length() < 3) 50 return null; 51 char c = pattern.charAt(0); 52 boolean after; 53 if (c == '<') 55 after = true; 56 else if (c == '>') 57 after = false; 58 else 59 return null; 60 String number = pattern.substring(1, pattern.length() - 1); 61 int n; 62 try { 63 n = Integer.parseInt(number); 64 } 65 catch (NumberFormatException e) { 66 return null; 67 } 68 if (n == 0) 69 return null; 70 c = pattern.charAt(pattern.length() - 1); 71 switch (c) { 72 case 'd': 73 return new RelativeDateMailboxFilter(n, 0, 0, after); 74 case 'w': 75 return new RelativeDateMailboxFilter(n * 7, 0, 0, after); 76 case 'm': 77 return new RelativeDateMailboxFilter(0, n, 0, after); 78 case 'y': 79 return new RelativeDateMailboxFilter(0, 0, n, after); 80 default: 81 return null; 82 } 83 } 84 85 private void init() 86 { 87 Calendar cal = Calendar.getInstance(); 88 if (days != 0) { 89 cal.add(Calendar.DATE, - days); 90 if (after) 91 cal.add(Calendar.DATE, 1); 92 } else if (months != 0) { 93 cal.add(Calendar.MONTH, - months); 94 if (after) 95 cal.add(Calendar.DATE, 1); 96 } else if (years != 0) { 97 cal.add(Calendar.YEAR, - years); 98 if (after) 99 cal.add(Calendar.DATE, 1); 100 } 101 cal.set(Calendar.HOUR_OF_DAY, 0); 102 cal.set(Calendar.MINUTE, 0); 103 cal.set(Calendar.SECOND, 0); 104 cal.set(Calendar.MILLISECOND, 0); 105 if (after) { 106 begin = new RFC822Date(cal.getTime()); 107 end = null; 108 } else { 109 begin = null; 110 end = new RFC822Date(cal.getTime()); 111 } 112 initMillis = System.currentTimeMillis(); 113 } 114 115 public boolean accept(MailboxEntry entry) 116 { 117 if (initMillis == 0 || System.currentTimeMillis() - initMillis > 60000) 118 init(); 119 RFC822Date date = entry.getDate(); 120 if (begin != null) 121 if (date.before(begin)) 122 return false; 123 if (end != null) 124 if (date.after(end)) 125 return false; 126 return true; 127 } 128 } 129 | Popular Tags |