001/**
002 *
003 * Copyright 2017 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;
018
019import org.jivesoftware.smack.packet.Stanza;
020import org.jxmpp.jid.Jid;
021
022public abstract class AbstractFromToMatchesFilter implements StanzaFilter {
023
024    private final Jid address;
025
026    /**
027     * Flag that indicates if the checking will be done against bare JID addresses or full JIDs.
028     */
029    private final boolean ignoreResourcepart;
030
031    /**
032     * Creates a filter matching on the address returned by {@link #getAddressToCompare(Stanza)}. The address must be
033     * the same as the filter address. The second parameter specifies whether the full or the bare addresses are
034     * compared.
035     *
036     * @param address The address to filter for. If <code>null</code> is given, then
037     *        {@link #getAddressToCompare(Stanza)} must also return <code>null</code> to match.
038     * @param ignoreResourcepart
039     */
040    protected AbstractFromToMatchesFilter(Jid address, boolean ignoreResourcepart) {
041        if (address != null && ignoreResourcepart) {
042            this.address = address.asBareJid();
043        }
044        else {
045            this.address = address;
046        }
047        this.ignoreResourcepart = ignoreResourcepart;
048    }
049
050    @Override
051    public final boolean accept(final Stanza stanza) {
052        Jid stanzaAddress = getAddressToCompare(stanza);
053
054        if (stanzaAddress == null) {
055            return address == null;
056        }
057
058        if (ignoreResourcepart) {
059            stanzaAddress = stanzaAddress.asBareJid();
060        }
061
062        return stanzaAddress.equals(address);
063    }
064
065    protected abstract Jid getAddressToCompare(Stanza stanza);
066
067    @Override
068    public final String toString() {
069        String matchMode = ignoreResourcepart ? "ignoreResourcepart" : "full";
070        return getClass().getSimpleName() + " (" + matchMode + "): " + address;
071    }
072}