Classes in this File | Line Coverage | Branch Coverage | Complexity | ||||
ServiceVisitor |
|
| 3.0;3 |
1 | /* | |
2 | * Licensed under the Apache License, Version 2.0 (the "License"); | |
3 | * you may not use this file except in compliance with the License. | |
4 | * You may obtain a copy of the License at | |
5 | * | |
6 | * http://www.apache.org/licenses/LICENSE-2.0 | |
7 | * | |
8 | * Unless required by applicable law or agreed to in writing, software | |
9 | * distributed under the License is distributed on an "AS IS" BASIS, | |
10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
11 | * See the License for the specific language governing permissions and | |
12 | * limitations under the License. | |
13 | */ | |
14 | package org.apache.commons.classscan.util; | |
15 | ||
16 | import java.util.Iterator; | |
17 | import java.util.ServiceConfigurationError; | |
18 | import java.util.ServiceLoader; | |
19 | ||
20 | import org.slf4j.Logger; | |
21 | import org.slf4j.LoggerFactory; | |
22 | ||
23 | /** | |
24 | * Visit the provider instances specified in the META-INF/services directories | |
25 | * | |
26 | * @param <T> The type of the provider | |
27 | */ | |
28 | 0 | public abstract class ServiceVisitor<T> { |
29 | ||
30 | 0 | private static final Logger logger = LoggerFactory.getLogger(ServiceVisitor.class); |
31 | ||
32 | /** | |
33 | * Visit the service provider available for the given interface and ClassLoader | |
34 | * | |
35 | * @param serviceInterface The interface of the service | |
36 | * @param classLoader The ClassLoader which will load the service | |
37 | */ | |
38 | public void visitProviders(Class<T> serviceInterface, ClassLoader classLoader) { | |
39 | 0 | Iterator<T> factories = ServiceLoader.load(serviceInterface, classLoader).iterator(); |
40 | for(;;) { | |
41 | // this odd loop is due to the possibility of the iterator throwing | |
42 | // ServiceConfigurationError from either hasNext() or next() | |
43 | try { | |
44 | 0 | if(!factories.hasNext()) { |
45 | 0 | break; |
46 | } | |
47 | 0 | T factory = factories.next(); |
48 | 0 | if(!visit(factory)) { |
49 | 0 | break; |
50 | } | |
51 | } | |
52 | 0 | catch(ServiceConfigurationError error) { |
53 | 0 | logger.warn("Ignoring configuration error", error); |
54 | 0 | } |
55 | } | |
56 | 0 | } |
57 | ||
58 | /** | |
59 | * The callback method which is invoked upon finding a service provider | |
60 | * | |
61 | * @param serviceProvider An instance of the service provider | |
62 | * @return true, if additional service providers desired; false, stop the visiting | |
63 | */ | |
64 | abstract protected boolean visit(T serviceProvider); | |
65 | } |