001/**
002 *
003 * Copyright 2003-2007 Jive Software.
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
018package org.jivesoftware.smack.filter;
019
020import java.util.ArrayList;
021import java.util.Arrays;
022import java.util.List;
023
024import org.jivesoftware.smack.packet.Packet;
025
026/**
027 * Implements the logical AND operation over two or more packet filters.
028 * In other words, packets pass this filter if they pass <b>all</b> of the filters.
029 *
030 * @author Matt Tucker
031 */
032public class AndFilter implements PacketFilter {
033
034    /**
035     * The list of filters.
036     */
037    private final List<PacketFilter> filters;
038
039    /**
040     * Creates an empty AND filter. Filters should be added using the
041     * {@link #addFilter(PacketFilter)} method.
042     */
043    public AndFilter() {
044        filters = new ArrayList<PacketFilter>();
045    }
046
047    /**
048     * Creates an AND filter using the specified filters.
049     *
050     * @param filters the filters to add.
051     */
052    public AndFilter(PacketFilter... filters) {
053        if (filters == null) {
054            throw new IllegalArgumentException("Parameter must not be null.");
055        }
056        for(PacketFilter filter : filters) {
057            if(filter == null) {
058                throw new IllegalArgumentException("Parameter must not be null.");
059            }
060        }
061        this.filters = new ArrayList<PacketFilter>(Arrays.asList(filters));
062    }
063
064    /**
065     * Adds a filter to the filter list for the AND operation. A packet
066     * will pass the filter if all of the filters in the list accept it.
067     *
068     * @param filter a filter to add to the filter list.
069     */
070    public void addFilter(PacketFilter filter) {
071        if (filter == null) {
072            throw new IllegalArgumentException("Parameter must not be null.");
073        }
074        filters.add(filter);
075    }
076
077    public boolean accept(Packet packet) {
078        for (PacketFilter filter : filters) {
079            if (!filter.accept(packet)) {
080                return false;
081            }
082        }
083        return true;
084    }
085
086    public String toString() {
087        return filters.toString();
088    }
089}