001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  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     */
017    package org.apache.commons.functor.example.map;
018    
019    import java.lang.reflect.Array;
020    import java.util.Iterator;
021    import java.util.Map;
022    
023    import org.apache.commons.functor.BinaryPredicate;
024    import org.apache.commons.functor.BinaryProcedure;
025    import org.apache.commons.functor.UnaryPredicate;
026    import org.apache.commons.functor.adapter.BinaryProcedureBinaryFunction;
027    import org.apache.commons.functor.core.composite.ConditionalBinaryFunction;
028    
029    /**
030     * @version $Revision: 666163 $ $Date: 2008-06-10 17:41:34 +0200 (Tue, 10 Jun 2008) $
031     * @author Rodney Waldhoff
032     */
033    @SuppressWarnings("unchecked")
034    public class PredicatedMap extends FunctoredMap {
035        public PredicatedMap(Map map, final UnaryPredicate keyPredicate, final UnaryPredicate valuePredicate) {
036            super(map);
037            setOnPut(new ConditionalBinaryFunction(
038                new BinaryPredicate() {
039                    public boolean test(Object a, Object b) {
040                        return keyPredicate.test(Array.get(b,0)) &&
041                            valuePredicate.test(Array.get(b,1));
042                    }
043                },
044                DEFAULT_ON_PUT,
045                BinaryProcedureBinaryFunction.adapt(new Throw(new IllegalArgumentException()))));
046    
047            setOnPutAll(new BinaryProcedure() {
048                public void run(Object d, Object s) {
049                    Map dest = (Map) d;
050                    Map src = (Map) s;
051                    for (Iterator iter = src.entrySet().iterator(); iter.hasNext(); ) {
052                        Map.Entry pair = (Map.Entry) iter.next();
053                        if (keyPredicate.test(pair.getKey()) &&
054                            valuePredicate.test(pair.getValue())) {
055                            dest.put(pair.getKey(),pair.getValue());
056                        }
057                    }
058                }
059            });
060        }
061    }