blob: 4c34fd04a01a58ffd530736b2293e86237f7b94e [file] [log] [blame]
Shuyi Chend7955ce2013-05-22 14:51:55 -07001/**
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;
24
25/**
26 * Implements the logical OR operation over two or more packet filters. In
27 * other words, packets pass this filter if they pass <b>any</b> of the filters.
28 *
29 * @author Matt Tucker
30 */
31public class OrFilter implements PacketFilter {
32
33 /**
34 * The current number of elements in the filter.
35 */
36 private int size;
37
38 /**
39 * The list of filters.
40 */
41 private PacketFilter [] filters;
42
43 /**
44 * Creates an empty OR filter. Filters should be added using the
45 * {@link #addFilter(PacketFilter)} method.
46 */
47 public OrFilter() {
48 size = 0;
49 filters = new PacketFilter[3];
50 }
51
52 /**
53 * Creates an OR filter using the two specified filters.
54 *
55 * @param filter1 the first packet filter.
56 * @param filter2 the second packet filter.
57 */
58 public OrFilter(PacketFilter filter1, PacketFilter filter2) {
59 if (filter1 == null || filter2 == null) {
60 throw new IllegalArgumentException("Parameters cannot be null.");
61 }
62 size = 2;
63 filters = new PacketFilter[2];
64 filters[0] = filter1;
65 filters[1] = filter2;
66 }
67
68 /**
69 * Adds a filter to the filter list for the OR operation. A packet
70 * will pass the filter if any filter in the list accepts it.
71 *
72 * @param filter a filter to add to the filter list.
73 */
74 public void addFilter(PacketFilter filter) {
75 if (filter == null) {
76 throw new IllegalArgumentException("Parameter cannot be null.");
77 }
78 // If there is no more room left in the filters array, expand it.
79 if (size == filters.length) {
80 PacketFilter [] newFilters = new PacketFilter[filters.length+2];
81 for (int i=0; i<filters.length; i++) {
82 newFilters[i] = filters[i];
83 }
84 filters = newFilters;
85 }
86 // Add the new filter to the array.
87 filters[size] = filter;
88 size++;
89 }
90
91 public boolean accept(Packet packet) {
92 for (int i=0; i<size; i++) {
93 if (filters[i].accept(packet)) {
94 return true;
95 }
96 }
97 return false;
98 }
99
100 public String toString() {
101 return filters.toString();
102 }
103}