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 org.jivesoftware.smack.packet.Message;
021import org.jivesoftware.smack.packet.Packet;
022import org.jivesoftware.smack.packet.Presence;
023
024/**
025 * Filters for packets of a particular type. The type is given as a Class object, so
026 * example types would:
027 * <ul>
028 *      <li><tt>Message.class</tt>
029 *      <li><tt>IQ.class</tt>
030 *      <li><tt>Presence.class</tt>
031 * </ul>
032 *
033 * @author Matt Tucker
034 */
035public class PacketTypeFilter implements PacketFilter {
036
037    public static final PacketTypeFilter PRESENCE = new PacketTypeFilter(Presence.class);
038    public static final PacketTypeFilter MESSAGE = new PacketTypeFilter(Message.class);
039
040    Class<? extends Packet> packetType;
041
042    /**
043     * Creates a new packet type filter that will filter for packets that are the
044     * same type as <tt>packetType</tt>.
045     *
046     * @param packetType the Class type.
047     */
048    public PacketTypeFilter(Class<? extends Packet> packetType) {
049        // Ensure the packet type is a sub-class of Packet.
050        if (!Packet.class.isAssignableFrom(packetType)) {
051            throw new IllegalArgumentException("Packet type must be a sub-class of Packet.");
052        }
053        this.packetType = packetType;
054    }
055
056    public boolean accept(Packet packet) {
057        return packetType.isInstance(packet);
058    }
059
060    public String toString() {
061        return "PacketTypeFilter: " + packetType.getName();
062    }
063}