View Javadoc
1   /*
2    * Copyright 2013 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.openehealth.ipf.commons.core.config;
17  
18  
19  import java.util.HashMap;
20  import java.util.Map;
21  import java.util.stream.Collectors;
22  
23  /**
24   * A simple registry implementation that can e.g. be used in tests to
25   * abstract away more complex bean registries like Spring. This is
26   * sometimes easier to use than mocking the requests to individual
27   * methods.
28   * Note that no synchronization is done for adding beans or clearing
29   * the registry.
30   */
31  public class SimpleRegistry implements Registry {
32  
33      private Map<String, Object> beans = new HashMap<>();
34  
35      @Override
36      public Object bean(String name) {
37          return beans.get(name);
38      }
39  
40      @SuppressWarnings("unchecked")
41      @Override
42      public <T> T bean(Class<T> requiredType) {
43          for (Object value : beans.values()) {
44              if (requiredType.isAssignableFrom(value.getClass())) return (T) value;
45          }
46          return null;
47      }
48  
49      @SuppressWarnings("unchecked")
50      @Override
51      public <T> Map<String, T> beans(Class<T> requiredType) {
52          Map<String, T> result = beans.entrySet().stream()
53                  .filter(entry -> requiredType.isAssignableFrom(entry.getValue().getClass()))
54                  .collect(Collectors.toMap(Map.Entry::getKey, p -> (T) p.getValue()));
55          return result;
56      }
57  
58      public Object register(String name, Object object) {
59          return beans.put(name, object);
60      }
61  
62      public void clear() {
63          beans.clear();
64      }
65  }