View Javadoc
1   /*
2    * Copyright 2008 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.platform.camel.core.util;
17  
18  import org.apache.camel.CamelContext;
19  
20  import java.util.Set;
21  
22  /**
23   * @author Martin Krasser
24   */
25  public class Contexts {
26  
27      public static <T> T bean(Class<T> type, CamelContext camelContext) {
28          T bean = beanOrNull(type, camelContext);
29          if (bean == null) {
30              throw new IllegalArgumentException(
31                      "No bean available in the application context of type: " 
32                      + type);
33          }
34          return bean;
35      }
36      
37      public static <T> T beanOrNull(Class<T> type, CamelContext camelContext) {
38          Set<T> beans = camelContext.getRegistry().findByType(type);
39          int count = beans.size();
40          if (count == 1) {
41              return beans.iterator().next();
42          } else if (count == 0) {
43              return null; 
44          } else {
45              throw new IllegalArgumentException(
46                      "Too many beans in the application context of type: " 
47                      + type + ". Found: " + count);
48          }
49      }
50      
51  }