1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package javax.mail.search;
21
22 import java.io.IOException;
23 import javax.mail.Message;
24 import javax.mail.MessagingException;
25 import javax.mail.Part;
26 import javax.mail.Multipart;
27 import javax.mail.BodyPart;
28
29 /**
30 * Term that matches on a message body. All {@link javax.mail.BodyPart parts} that have
31 * a MIME type of "text/*" are searched.
32 *
33 * @version $Rev: 593593 $ $Date: 2007-11-09 12:04:20 -0500 (Fri, 09 Nov 2007) $
34 */
35 public final class BodyTerm extends StringTerm {
36 public BodyTerm(String pattern) {
37 super(pattern);
38 }
39
40 public boolean match(Message message) {
41 try {
42 return matchPart(message);
43 } catch (IOException e) {
44 return false;
45 } catch (MessagingException e) {
46 return false;
47 }
48 }
49
50 private boolean matchPart(Part part) throws MessagingException, IOException {
51 if (part.isMimeType("multipart/*")) {
52 Multipart mp = (Multipart) part.getContent();
53 int count = mp.getCount();
54 for (int i=0; i < count; i++) {
55 BodyPart bp = mp.getBodyPart(i);
56 if (matchPart(bp)) {
57 return true;
58 }
59 }
60 return false;
61 } else if (part.isMimeType("text/*")) {
62 String content = (String) part.getContent();
63 return super.match(content);
64 } else if (part.isMimeType("message/rfc822")) {
65 // nested messages need recursion
66 return matchPart((Part)part.getContent());
67 } else {
68 return false;
69 }
70 }
71 }