View Javadoc
1   /*
2    * Copyright 2016 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  
17  package org.openehealth.ipf.commons.core.config;
18  
19  import java.util.Collection;
20  import java.util.Optional;
21  import java.util.ServiceLoader;
22  import java.util.stream.Collectors;
23  import java.util.stream.Stream;
24  import java.util.stream.StreamSupport;
25  
26  /**
27   * Lookup implementation of an interface type using {@link ServiceLoader}.
28   */
29  public class Lookup {
30  
31      /**
32       * Returns the first implementation of T
33       *
34       * @param clazz interface
35       * @param <T>   interface type
36       * @return first implementation of T, if any
37       */
38      public static <T> Optional<T> lookup(Class<T> clazz) {
39          return load(clazz).findFirst();
40      }
41  
42      /**
43       * Returns all implementations of T
44       *
45       * @param clazz interface
46       * @param <T>   interface type
47       * @return implementations of T or an empty collection
48       */
49      public static <T> Collection<? extends T> lookupAll(Class<T> clazz) {
50          return load(clazz).collect(Collectors.toList());
51      }
52  
53      private static <T> Stream<T> load(Class<T> clazz) {
54          return StreamSupport.stream(ServiceLoader.load(clazz).spliterator(), false);
55      }
56  
57  }