2 * Copyright (c) 2018. Developed by Hedgecode.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.hedgecode.chess.service;
19 import java.util.Iterator;
20 import java.util.ServiceLoader;
22 import org.hedgecode.chess.domain.Adapter;
23 import org.hedgecode.chess.domain.EtudeAdapter;
24 import org.hedgecode.chess.dto.EtudeDTO;
25 import org.hedgecode.chess.persistence.PersistenceManager;
28 * Service Provider Interface (SPI) Registry.
30 * @author Dmitry Samoshin aka gotty
32 public final class ServiceRegistry {
34 private ServiceRegistry() {
37 public static <ServiceType> Iterator<ServiceType> providers(Class<ServiceType> serviceClass) {
38 final Iterator<ServiceType> providers = ServiceLoader.load(serviceClass).iterator();
40 if (!providers.hasNext()) {
41 throw new ServiceRegistryException("service.provider.not.found", serviceClass.getName());
47 public static <ServiceType> ServiceType singleProvider(Class<ServiceType> serviceClass) {
48 final Iterator<ServiceType> providers = providers(serviceClass);
50 ServiceType provider = providers.next();
51 if (providers.hasNext()) {
52 throw new ServiceRegistryException("service.too.many.providers", serviceClass.getName());
58 public static <AdapterType extends Adapter, TargetType> AdapterType singleAdapter(
59 Class<AdapterType> adapterClass,
60 Class<TargetType> targetClass)
62 AdapterType targetAdapter = null;
64 final Iterator<AdapterType> providers = providers(adapterClass);
66 while (providers.hasNext()) {
67 AdapterType adapter = providers.next();
68 if (adapter.getTargetClass().equals(targetClass)) {
69 if (targetAdapter != null)
70 throw new ServiceRegistryException(
71 "service.too.many.adapters", adapterClass.getName(), targetClass.getName()
73 targetAdapter = adapter;
76 if (targetAdapter == null)
77 throw new ServiceRegistryException(
78 "service.adapter.not.found", adapterClass.getName(), targetClass.getName()
85 public static void main(String... args) {
87 AuthorService as = ServiceRegistry.singleProvider(AuthorService.class);
88 System.out.println(as);
89 PersistenceManager pm = ServiceRegistry.singleProvider(PersistenceManager.class);
90 System.out.println(pm);
91 EtudeAdapter ea = ServiceRegistry.singleAdapter(EtudeAdapter.class, EtudeDTO.class);
92 System.out.println(ea);