1/**
2 * $RCSfile$
3 * $Revision$
4 * $Date$
5 *
6 * Copyright 2003-2007 Jive Software.
7 *
8 * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
11 *
12 *     http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 */
20
21package org.jivesoftware.smack.filter;
22
23import org.jivesoftware.smack.packet.Packet;
24import org.jivesoftware.smack.util.StringUtils;
25
26/**
27 * Filter for packets where the "from" field exactly matches a specified JID. If the specified
28 * address is a bare JID then the filter will match any address whose bare JID matches the
29 * specified JID. But if the specified address is a full JID then the filter will only match
30 * if the sender of the packet matches the specified resource.
31 *
32 * @author Gaston Dombiak
33 */
34public class FromMatchesFilter implements PacketFilter {
35
36    private String address;
37    /**
38     * Flag that indicates if the checking will be done against bare JID addresses or full JIDs.
39     */
40    private boolean matchBareJID = false;
41
42    /**
43     * Creates a "from" filter using the "from" field part. If the specified address is a bare JID
44     * then the filter will match any address whose bare JID matches the specified JID. But if the
45     * specified address is a full JID then the filter will only match if the sender of the packet
46     * matches the specified resource.
47     *
48     * @param address the from field value the packet must match. Could be a full or bare JID.
49     */
50    public FromMatchesFilter(String address) {
51        if (address == null) {
52            throw new IllegalArgumentException("Parameter cannot be null.");
53        }
54        this.address = address.toLowerCase();
55        matchBareJID = "".equals(StringUtils.parseResource(address));
56    }
57
58    public boolean accept(Packet packet) {
59        if (packet.getFrom() == null) {
60            return false;
61        }
62        else if (matchBareJID) {
63            // Check if the bare JID of the sender of the packet matches the specified JID
64            return packet.getFrom().toLowerCase().startsWith(address);
65        }
66        else {
67            // Check if the full JID of the sender of the packet matches the specified JID
68            return address.equals(packet.getFrom().toLowerCase());
69        }
70    }
71
72    public String toString() {
73        return "FromMatchesFilter: " + address;
74    }
75}
76