View Javadoc
1   /**
2    * Copyright 2010-2014 The Kuali Foundation
3    *
4    * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
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.kuali.common.util.serviceloader;
17  
18  import static com.google.common.base.Preconditions.checkState;
19  
20  import java.util.Iterator;
21  import java.util.List;
22  import java.util.ServiceLoader;
23  
24  import com.google.common.collect.Lists;
25  
26  public class ServiceProvider {
27  
28  	/**
29  	 * Return the first service located by ServiceLoader
30  	 * 
31  	 * @throws IllegalStateException
32  	 *             If no service can be found
33  	 */
34  	public static <T> T getFirst(Class<T> type) {
35  		return getFirst(type, Thread.currentThread().getContextClassLoader());
36  	}
37  
38  	/**
39  	 * Return the first service located by ServiceLoader
40  	 * 
41  	 * @throws IllegalStateException
42  	 *             If no service can be found
43  	 */
44  	public static <T> T getFirst(Class<T> type, ClassLoader classLoader) {
45  		ServiceLoader<T> loader = ServiceLoader.load(type, classLoader);
46  		Iterator<T> itr = loader.iterator();
47  		checkState(itr.hasNext(), "ServiceLoader could not find a service for type [%s]", type.getCanonicalName());
48  		return itr.next();
49  	}
50  
51  	/**
52  	 * Return all service implementations located by ServiceLoader
53  	 */
54  	public static <T> List<T> getAll(Class<T> type) {
55  		return getAll(type, Thread.currentThread().getContextClassLoader());
56  	}
57  
58  	/**
59  	 * Return all service implementations located by ServiceLoader
60  	 */
61  	public static <T> List<T> getAll(Class<T> type, ClassLoader classLoader) {
62  		ServiceLoader<T> loader = ServiceLoader.load(type);
63  		Iterator<T> itr = loader.iterator();
64  		List<T> list = Lists.newArrayList();
65  		while (itr.hasNext()) {
66  			list.add(itr.next());
67  		}
68  		return list;
69  	}
70  
71  }