001/**
002 *
003 * Copyright 2014-2015 Florian Schmaus
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.lang.reflect.ParameterizedType;
021
022import org.jivesoftware.smack.packet.Stanza;
023import org.jivesoftware.smack.util.Objects;
024
025/**
026 * Filters for stanzas of a particular type and allows a custom method to further filter the packets.
027 *
028 * @author Florian Schmaus
029 */
030public abstract class FlexibleStanzaTypeFilter<S extends Stanza> implements StanzaFilter {
031
032    protected final Class<S> stanzaType;
033
034    public FlexibleStanzaTypeFilter(Class<S> packetType) {
035        this.stanzaType = Objects.requireNonNull(packetType, "Type must not be null");
036    }
037
038    @SuppressWarnings("unchecked")
039    public FlexibleStanzaTypeFilter() {
040        stanzaType = (Class<S>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
041    }
042
043    @Override
044    @SuppressWarnings("unchecked")
045    public final boolean accept(Stanza packet) {
046        if (stanzaType.isInstance(packet)) {
047            return acceptSpecific((S) packet);
048        }
049        return false;
050    }
051
052    protected abstract boolean acceptSpecific(S packet);
053
054    @Override
055    public String toString() {
056        return getClass().getSimpleName() + ": " + stanzaType.toString();
057    }
058}