2 * Sonitus - PredicateFilter.java - Copyright © 2013 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.sonitus.data.filter;
20 import static com.google.common.base.Preconditions.checkNotNull;
22 import java.io.IOException;
23 import java.util.concurrent.atomic.AtomicBoolean;
25 import net.pterodactylus.sonitus.data.AbstractFilter;
26 import net.pterodactylus.sonitus.data.Filter;
27 import net.pterodactylus.sonitus.data.Metadata;
29 import com.google.common.base.Predicate;
32 * {@link Filter} implementation that uses a {@link Predicate} to determine
33 * whether a filter will be used or the data will only be passed through.
35 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
37 public class PredicateFilter extends AbstractFilter implements Filter {
40 private final Predicate<Metadata> metadataPredicate;
42 /** The filter to use if the predicate matches. */
43 private final Filter filter;
45 /** Whether the predicate currently matches. */
46 private final AtomicBoolean metadataMatches = new AtomicBoolean(false);
49 * Creates a new predicate filter.
51 * @param metadataPredicate
52 * The predicate to evaluate every time the metadata changes
55 public PredicateFilter(Predicate<Metadata> metadataPredicate, Filter filter) {
56 super(String.format("%s (maybe)", filter.name()));
57 this.metadataPredicate = metadataPredicate;
66 public void open(Metadata metadata) throws IOException {
67 checkNotNull(metadata, "metadata must not be null");
69 metadataMatches.set(metadataPredicate.apply(metadata));
70 if (metadataMatches.get()) {
71 filter.open(metadata);
79 if (metadataMatches.get()) {
87 public Metadata metadata() {
88 if (metadataMatches.get()) {
89 return filter.metadata();
91 return super.metadata();
95 public void metadataUpdated(Metadata metadata) {
96 metadataMatches.set(metadataPredicate.apply(metadata));
97 if (metadataMatches.get()) {
98 filter.metadataUpdated(metadata);
100 super.metadataUpdated(metadata);
105 public void process(byte[] buffer) throws IOException {
106 if (metadataMatches.get()) {
107 filter.process(buffer);
109 super.process(buffer);
114 public byte[] get(int bufferSize) throws IOException {
115 if (metadataMatches.get()) {
116 return filter.get(bufferSize);
118 return super.get(bufferSize);