View Javadoc

1   /*
2    * Copyright 2012-2013 smartics, Kronseder & Reiner GmbH
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 de.smartics.properties.integration.cdi.extension;
17  
18  import java.util.ArrayList;
19  import java.util.List;
20  import java.util.Set;
21  
22  import javax.enterprise.context.spi.CreationalContext;
23  import javax.enterprise.inject.spi.Bean;
24  import javax.enterprise.inject.spi.BeanManager;
25  
26  /**
27   * Helper to find beans in the bean manager.
28   */
29  public final class CdiBeanHelper
30  {
31  
32    // ********************************* Fields *********************************
33  
34    // --- constants ------------------------------------------------------------
35  
36    private CdiBeanHelper()
37    {
38  
39    }
40  
41    /**
42     * Find beans of given clazz in bean manager.
43     *
44     * @param beanManager the cdi bean manager.f
45     * @param clazz the class for which an bean is searched.
46     * @param <T> the type.
47     * @return list of cdi beans of given class.
48     */
49    @SuppressWarnings("unchecked")
50    public static <T> List<T> find(final BeanManager beanManager,
51        final Class<T> clazz)
52    {
53      final List<T> result = new ArrayList<T>();
54      if (beanManager != null)
55      {
56        final Set<Bean<?>> beans = beanManager.getBeans(clazz);
57        for (Bean<?> bean : beans)
58        {
59          final CreationalContext<?> cc =
60              beanManager.createCreationalContext(bean);
61          final Object reference = beanManager.getReference(bean, clazz, cc);
62          result.add((T) reference);
63        }
64      }
65      return result;
66    }
67    // --- object basics --------------------------------------------------------
68  
69  }