1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.functor.example.map;
18  
19  import java.lang.reflect.Array;
20  import java.util.Iterator;
21  import java.util.Map;
22  
23  import org.apache.commons.functor.BinaryPredicate;
24  import org.apache.commons.functor.BinaryProcedure;
25  import org.apache.commons.functor.UnaryPredicate;
26  import org.apache.commons.functor.adapter.BinaryProcedureBinaryFunction;
27  import org.apache.commons.functor.core.composite.ConditionalBinaryFunction;
28  
29  /**
30   * @version $Revision: 666163 $ $Date: 2008-06-10 17:41:34 +0200 (Tue, 10 Jun 2008) $
31   * @author Rodney Waldhoff
32   */
33  @SuppressWarnings("unchecked")
34  public class PredicatedMap extends FunctoredMap {
35      public PredicatedMap(Map map, final UnaryPredicate keyPredicate, final UnaryPredicate valuePredicate) {
36          super(map);
37          setOnPut(new ConditionalBinaryFunction(
38              new BinaryPredicate() {
39                  public boolean test(Object a, Object b) {
40                      return keyPredicate.test(Array.get(b,0)) &&
41                          valuePredicate.test(Array.get(b,1));
42                  }
43              },
44              DEFAULT_ON_PUT,
45              BinaryProcedureBinaryFunction.adapt(new Throw(new IllegalArgumentException()))));
46  
47          setOnPutAll(new BinaryProcedure() {
48              public void run(Object d, Object s) {
49                  Map dest = (Map) d;
50                  Map src = (Map) s;
51                  for (Iterator iter = src.entrySet().iterator(); iter.hasNext(); ) {
52                      Map.Entry pair = (Map.Entry) iter.next();
53                      if (keyPredicate.test(pair.getKey()) &&
54                          valuePredicate.test(pair.getValue())) {
55                          dest.put(pair.getKey(),pair.getValue());
56                      }
57                  }
58              }
59          });
60      }
61  }