+++ /dev/null
-/*
- * Copyright (c) 2018. Developed by Hedgecode.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.hedgecode.chess.service;
-
-import java.util.Iterator;
-import java.util.ServiceLoader;
-
-import org.hedgecode.chess.domain.Adapter;
-import org.hedgecode.chess.domain.EtudeAdapter;
-import org.hedgecode.chess.dto.EtudeDTO;
-import org.hedgecode.chess.persistence.PersistenceManager;
-
-/**
- * Service Provider Interface (SPI) Registry.
- *
- * @author Dmitry Samoshin aka gotty
- */
-public final class ServiceRegistry {
-
- private ServiceRegistry() {
- }
-
- public static <ServiceType> Iterator<ServiceType> providers(Class<ServiceType> serviceClass) {
- final Iterator<ServiceType> providers = ServiceLoader.load(serviceClass).iterator();
-
- if (!providers.hasNext()) {
- throw new ServiceRegistryException("service.provider.not.found", serviceClass.getName());
- }
-
- return providers;
- }
-
- public static <ServiceType> ServiceType singleProvider(Class<ServiceType> serviceClass) {
- final Iterator<ServiceType> providers = providers(serviceClass);
-
- ServiceType provider = providers.next();
- if (providers.hasNext()) {
- throw new ServiceRegistryException("service.too.many.providers", serviceClass.getName());
- }
-
- return provider;
- }
-
- public static <AdapterType extends Adapter, TargetType> AdapterType singleAdapter(
- Class<AdapterType> adapterClass,
- Class<TargetType> targetClass)
- {
- AdapterType targetAdapter = null;
-
- final Iterator<AdapterType> providers = providers(adapterClass);
-
- while (providers.hasNext()) {
- AdapterType adapter = providers.next();
- if (adapter.getTargetClass().equals(targetClass)) {
- if (targetAdapter != null)
- throw new ServiceRegistryException(
- "service.too.many.adapters", adapterClass.getName(), targetClass.getName()
- );
- targetAdapter = adapter;
- }
- }
- if (targetAdapter == null)
- throw new ServiceRegistryException(
- "service.adapter.not.found", adapterClass.getName(), targetClass.getName()
- );
-
- return targetAdapter;
- }
-
-
- public static void main(String... args) {
-
- AuthorService as = ServiceRegistry.singleProvider(AuthorService.class);
- System.out.println(as);
- PersistenceManager pm = ServiceRegistry.singleProvider(PersistenceManager.class);
- System.out.println(pm);
- EtudeAdapter ea = ServiceRegistry.singleAdapter(EtudeAdapter.class, EtudeDTO.class);
- System.out.println(ea);
-
- }
-
-}