1 17 18 package org.apache.james.transport.matchers; 19 20 import org.apache.mailet.GenericMatcher; 21 import org.apache.mailet.Mail; 22 23 import javax.mail.MessagingException ; 24 import javax.mail.Multipart ; 25 import javax.mail.Part ; 26 import javax.mail.internet.MimeMessage ; 27 import java.util.ArrayList ; 28 import java.util.Collection ; 29 import java.util.Iterator ; 30 import java.util.StringTokenizer ; 31 import java.util.Locale ; 32 33 34 44 public class AttachmentFileNameIs extends GenericMatcher { 45 48 private static class Mask { 49 50 public boolean suffixMatch; 51 52 53 public String matchString; 54 } 55 56 57 private Mask[] masks = null; 58 59 60 public void init() throws MessagingException { 61 62 63 StringTokenizer st = new StringTokenizer (getCondition(), ", ", false); 64 ArrayList theMasks = new ArrayList (20); 65 while (st.hasMoreTokens()) { 66 Mask mask = new Mask(); 67 String fileName = st.nextToken(); 68 if (fileName.startsWith("*")) { 69 mask.suffixMatch = true; 70 mask.matchString = fileName.substring(1); 71 } else { 72 mask.suffixMatch = false; 73 mask.matchString = fileName; 74 } 75 mask.matchString = mask.matchString.toLowerCase(Locale.US); 76 mask.matchString = mask.matchString.trim(); 77 theMasks.add(mask); 78 } 79 masks = (Mask[])theMasks.toArray(new Mask[0]); 80 } 81 82 86 public Collection match(Mail mail) throws MessagingException { 87 88 Exception anException = null; 89 90 try { 91 MimeMessage message = mail.getMessage(); 92 Object content; 93 94 98 if (message.getContentType() == null) { 99 return null; 100 } 101 102 content = message.getContent(); 103 if (content instanceof Multipart ) { 104 Multipart multipart = (Multipart ) content; 105 for (int i = 0; i < multipart.getCount(); i++) { 106 try { 107 Part part = multipart.getBodyPart(i); 108 String fileName = part.getFileName(); 109 if (fileName != null && matchFound(fileName)) { 110 return mail.getRecipients(); } 112 } catch (MessagingException e) { 113 anException = e; 114 } } 116 } else { 117 String fileName = message.getFileName(); 118 if (fileName != null && matchFound(fileName)) { 119 return mail.getRecipients(); } 121 } 122 } catch (Exception e) { 123 anException = e; 124 } 125 126 if (anException != null) { 128 throw new MessagingException ("Malformed message", anException); 129 } 130 131 return null; } 133 134 137 private boolean matchFound(String fileName) { 138 fileName = fileName.toLowerCase(Locale.US); 139 fileName = fileName.trim(); 140 141 for (int j = 0; j < masks.length; j++) { 142 boolean fMatch; 143 Mask mask = masks[j]; 144 145 if (mask.suffixMatch) { 147 fMatch = fileName.endsWith(mask.matchString); 148 } else { 149 fMatch = fileName.equals(mask.matchString); 150 } 151 if (fMatch) return true; } 153 return false; 154 } 155 } 156 157 | Popular Tags |