001/**
002 *
003 * Copyright 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 */
017package org.jivesoftware.smack.filter.jidtype;
018
019import org.jivesoftware.smack.filter.StanzaFilter;
020import org.jivesoftware.smack.packet.Stanza;
021import org.jivesoftware.smack.util.Objects;
022
023import org.jxmpp.jid.Jid;
024
025/**
026 * Base class for XMPP address type filters.
027 *
028 * @author Florian Schmaus
029 *
030 */
031public abstract class AbstractJidTypeFilter implements StanzaFilter {
032
033    private final JidType jidType;
034
035    protected AbstractJidTypeFilter(JidType jidType) {
036        this.jidType = Objects.requireNonNull(jidType, "jidType must not be null");
037    }
038
039    @Override
040    public boolean accept(Stanza stanza) {
041        Jid toMatch = getJidToMatchFrom(stanza);
042        if (toMatch == null) {
043            return false;
044        }
045        return jidType.isTypeOf(toMatch);
046    }
047
048    protected abstract Jid getJidToMatchFrom(Stanza stanza);
049
050    @Override
051    public final String toString() {
052        return getClass().getSimpleName() + ": " + jidType;
053    }
054
055    public enum JidType {
056        BareJid,
057        DomainBareJid,
058        DomainFullJid,
059        DomainJid,
060        EntityBareJid,
061        EntityFullJid,
062        EntityJid,
063        FullJid,
064        ;
065
066        public boolean isTypeOf(Jid jid) {
067            if (jid == null) {
068                return false;
069            }
070            switch (this) {
071            case BareJid:
072                return jid.hasNoResource();
073            case DomainBareJid:
074                return jid.isDomainBareJid();
075            case DomainFullJid:
076                return jid.isDomainFullJid();
077            case EntityBareJid:
078                return jid.isEntityBareJid();
079            case EntityFullJid:
080                return jid.isEntityFullJid();
081            case EntityJid:
082                return jid.isEntityJid();
083            case FullJid:
084                return jid.hasResource();
085            default:
086                throw new IllegalStateException();
087            }
088        }
089    }
090}