001    /**
002     *
003     * Copyright 2003-2006 The Apache Software Foundation
004     *
005     *  Licensed under the Apache License, Version 2.0 (the "License");
006     *  you may not use this file except in compliance with the License.
007     *  You may obtain a copy of the License at
008     *
009     *     http://www.apache.org/licenses/LICENSE-2.0
010     *
011     *  Unless required by applicable law or agreed to in writing, software
012     *  distributed under the License is distributed on an "AS IS" BASIS,
013     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     *  See the License for the specific language governing permissions and
015     *  limitations under the License.
016     */
017    
018    package javax.mail.search;
019    
020    import java.io.IOException;
021    import javax.mail.Message;
022    import javax.mail.MessagingException;
023    import javax.mail.Part;
024    import javax.mail.Multipart;
025    import javax.mail.BodyPart;
026    
027    /**
028     * Term that matches on a message body. All {@link javax.mail.BodyPart parts} that have
029     * a MIME type of "text/*" are searched.
030     *
031     * @version $Rev: 421852 $ $Date: 2006-07-14 03:02:19 -0700 (Fri, 14 Jul 2006) $
032     */
033    public final class BodyTerm extends StringTerm {
034        public BodyTerm(String pattern) {
035            super(pattern);
036        }
037    
038        public boolean match(Message message) {
039            try {
040                return matchPart(message);
041            } catch (IOException e) {
042                return false;
043            } catch (MessagingException e) {
044                return false;
045            }
046        }
047    
048        private boolean matchPart(Part part) throws MessagingException, IOException {
049            if (part.isMimeType("multipart/*")) {
050                Multipart mp = (Multipart) part.getContent();
051                int count = mp.getCount();
052                for (int i=0; i < count; i++) {
053                    BodyPart bp = mp.getBodyPart(i);
054                    if (matchPart(bp)) {
055                        return true;
056                    }
057                }
058                return false;
059            } else if (part.isMimeType("text/*")) {
060                String content = (String) part.getContent();
061                return super.match(content);
062            } else {
063                return false;
064            }
065        }
066    }