001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements. See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership. The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied. See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019
020 package javax.mail.search;
021
022 import javax.mail.Flags;
023 import javax.mail.Message;
024 import javax.mail.MessagingException;
025
026 /**
027 * Term for matching message {@link Flags}.
028 *
029 * @version $Rev: 920714 $ $Date: 2010-03-09 01:55:49 -0500 (Tue, 09 Mar 2010) $
030 */
031 public final class FlagTerm extends SearchTerm {
032
033 private static final long serialVersionUID = -142991500302030647L;
034
035 /**
036 * If true, test that all flags are set; if false, test that all flags are clear.
037 */
038 protected boolean set;
039 /**
040 * The flags to test.
041 */
042 protected Flags flags;
043
044 /**
045 * @param flags the flags to test
046 * @param set test for set or clear; {@link #set}
047 */
048 public FlagTerm(Flags flags, boolean set) {
049 this.set = set;
050 this.flags = flags;
051 }
052
053 public Flags getFlags() {
054 return flags;
055 }
056
057 public boolean getTestSet() {
058 return set;
059 }
060
061 public boolean match(Message message) {
062 try {
063 Flags msgFlags = message.getFlags();
064 if (set) {
065 return msgFlags.contains(flags);
066 } else {
067 // yuk - I wish we could get at the internal state of the Flags
068 Flags.Flag[] system = flags.getSystemFlags();
069 for (int i = 0; i < system.length; i++) {
070 Flags.Flag flag = system[i];
071 if (msgFlags.contains(flag)) {
072 return false;
073 }
074 }
075 String[] user = flags.getUserFlags();
076 for (int i = 0; i < user.length; i++) {
077 String flag = user[i];
078 if (msgFlags.contains(flag)) {
079 return false;
080 }
081 }
082 return true;
083 }
084 } catch (MessagingException e) {
085 return false;
086 }
087 }
088
089 public boolean equals(Object other) {
090 if (other == this) return true;
091 if (other instanceof FlagTerm == false) return false;
092 final FlagTerm otherFlags = (FlagTerm) other;
093 return otherFlags.set == this.set && otherFlags.flags.equals(flags);
094 }
095
096 public int hashCode() {
097 return set ? flags.hashCode() : ~flags.hashCode();
098 }
099 }