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.Map;
21  
22  import org.apache.commons.functor.BinaryFunction;
23  import org.apache.commons.functor.BinaryProcedure;
24  import org.apache.commons.functor.adapter.BinaryProcedureBinaryFunction;
25  import org.apache.commons.functor.core.algorithm.GeneratorContains;
26  import org.apache.commons.functor.core.composite.UnaryNot;
27  import org.apache.commons.functor.generator.IteratorToGeneratorAdapter;
28  
29  /**
30   * @version $Revision: 666157 $ $Date: 2008-06-10 17:34:23 +0200 (Tue, 10 Jun 2008) $
31   * @author Rodney Waldhoff
32   */
33  @SuppressWarnings("unchecked")
34  public class FixedSizeMap extends FunctoredMap {
35      public FixedSizeMap(Map map) {
36          super(map);
37          setOnPut(new BinaryFunction() {
38              public Object evaluate(Object a, Object b) {
39                  Map map = (Map) a;
40                  Object key = Array.get(b,0);
41                  Object value = Array.get(b,1);
42                  if (map.containsKey(key)) {
43                      return map.put(key,value);
44                  } else {
45                      throw new IllegalArgumentException();
46                  }
47              }
48          });
49  
50          setOnPutAll(new BinaryProcedure() {
51              public void run(Object a, Object b) {
52                  Map dest = (Map) a;
53                  Map src = (Map) b;
54  
55                  if (GeneratorContains.instance().test(IteratorToGeneratorAdapter.adapt(src.keySet().iterator()),UnaryNot.not(new ContainsKey(dest)))) {
56                      throw new IllegalArgumentException();
57                  } else {
58                      dest.putAll(src);
59                  }
60              }
61          });
62  
63          setOnRemove(new BinaryProcedureBinaryFunction(new Throw(new UnsupportedOperationException())));
64          setOnClear(new Throw(new UnsupportedOperationException()));
65      }
66  }