001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.dialogs.properties;
003
004import java.util.Collection;
005import java.util.Collections;
006import java.util.Map;
007
008import javax.swing.RowFilter;
009import javax.swing.table.TableModel;
010
011import org.openstreetmap.josm.actions.search.SearchCompiler;
012import org.openstreetmap.josm.data.osm.Tagged;
013
014/**
015 * A {@link RowFilter} implementation which matches tags w.r.t. the specified filter's
016 * {@link org.openstreetmap.josm.actions.search.SearchCompiler.Match#match(org.openstreetmap.josm.data.osm.Tagged)} method.
017 *
018 * <p>An {@link javax.swing.RowFilter.Entry}'s column 0 is considered as key, and column 1 is considered as value.</p>
019 */
020class SearchBasedRowFilter extends RowFilter<TableModel, Integer> {
021
022    final SearchCompiler.Match filter;
023
024    /**
025     * Constructs a new {@code SearchBasedRowFilter} with the given filter.
026     * @param filter the filter used to match tags
027     */
028    SearchBasedRowFilter(SearchCompiler.Match filter) {
029        this.filter = filter;
030    }
031
032    @Override
033    public boolean include(Entry entry) {
034        final String key = entry.getStringValue(0);
035        final String value = entry.getStringValue(1);
036        return filter.match(new OneKeyValue(key, value));
037    }
038
039    static class OneKeyValue implements Tagged {
040        private final String key;
041        private final String value;
042
043        OneKeyValue(String key, String value) {
044            this.key = key;
045            this.value = value;
046        }
047
048        @Override
049        public void setKeys(Map<String, String> keys) {
050            throw new UnsupportedOperationException();
051        }
052
053        @Override
054        public Map<String, String> getKeys() {
055            return Collections.singletonMap(key, value);
056        }
057
058        @Override
059        public void put(String key, String value) {
060            throw new UnsupportedOperationException();
061        }
062
063        @Override
064        public String get(String k) {
065            return key.equals(k) ? value : null;
066        }
067
068        @Override
069        public void remove(String key) {
070            throw new UnsupportedOperationException();
071        }
072
073        @Override
074        public boolean hasKeys() {
075            return true;
076        }
077
078        @Override
079        public Collection<String> keySet() {
080            return Collections.singleton(key);
081        }
082
083        @Override
084        public void removeAll() {
085            throw new UnsupportedOperationException();
086        }
087    }
088}