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