All Downloads are FREE. Search and download functionalities are using the official Maven repository.

fr.ird.observe.services.ObserveServiceMainFactory Maven / Gradle / Ivy

package fr.ird.observe.services;

/*
 * #%L
 * ObServe Toolkit :: Common Service
 * %%
 * Copyright (C) 2017 - 2018 IRD, Ultreia.io
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program.  If not, see
 * .
 * #L%
 */

import fr.ird.observe.services.configuration.ObserveDataSourceConfiguration;
import fr.ird.observe.services.configuration.ObserveDataSourceConnection;
import fr.ird.observe.services.service.ObserveService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.Set;

/**
 * Created on 16/08/15.
 *
 * @author Tony Chemit - [email protected]
 */
@SuppressWarnings("unused")
public class ObserveServiceMainFactory implements ObserveServiceFactory {

    /** Logger. */
    private static final Logger log = LogManager.getLogger(ObserveServiceMainFactory.class);

    private static ObserveServiceMainFactory GET;

    private final Set delegateFactories;

    public static ObserveServiceMainFactory get() {
        return GET==null?GET=new ObserveServiceMainFactory():GET;
    }

    @Override
    public ObserveServiceFactory getMainServiceFactory() {
        return this;
    }

    @Override
    public void setMainServiceFactory(ObserveServiceFactory mainServiceFactory) {
        throw new IllegalStateException("You can't set main factory inside the main factory");
    }

    @Override
    public  boolean accept(ObserveDataSourceConfiguration dataSourceConfiguration, Class serviceType) {

        getFactory(dataSourceConfiguration, serviceType);
        return true;

    }

    @Override
    public  boolean accept(ObserveDataSourceConnection dataSourceConnection, Class serviceType) {

        getFactory(dataSourceConnection, serviceType);
        return true;

    }

    @Override
    public  S newService(ObserveServiceInitializer observeServiceInitializer, Class serviceType) {

        Objects.requireNonNull(observeServiceInitializer, "observeServiceInitializerContext can't be null.");
        Objects.requireNonNull(serviceType, "serviceType can't be null.");

        ObserveServiceFactory factory;
        if (observeServiceInitializer.withDataSourceConnection()) {
            factory = getFactory(observeServiceInitializer.getDataSourceConnection().orElseThrow(IllegalStateException::new), serviceType);
        } else if (observeServiceInitializer.withDataSourceConfiguration()) {
            factory = getFactory(observeServiceInitializer.getDataSourceConfiguration().orElseThrow(IllegalStateException::new), serviceType);
        } else {
            throw new IllegalStateException("No dataSourceConnection, nor dataSourceConfiguration given.");
        }

        Objects.requireNonNull(factory, "factory can't be null.");

        if (log.isDebugEnabled()) {
            log.debug("Using factory: " + factory);
        }

        S service = factory.newService(observeServiceInitializer, serviceType);

        if (log.isInfoEnabled()) {
            log.info("New service created: " + service);
        }

        return service;

    }

    @Override
    public void close() {

        try {
            for (ObserveServiceFactory delegateFactory : delegateFactories) {
                try {
                    delegateFactory.close();
                } catch (Exception e) {
                    log.error("Could not close factory: " + delegateFactory, e);
                }
            }
        } finally {
            GET = null;
        }
    }

    private ObserveServiceMainFactory() {

        log.info("Init MainServiceFactory.");

        Set builder = new LinkedHashSet<>();

        for (ObserveServiceFactory factory : ServiceLoader.load(ObserveServiceFactory.class)) {
            log.info("Discover service factory: " + factory);
            factory.setMainServiceFactory(this);
            builder.add(factory);
        }

        if (builder.isEmpty()) {
            throw new IllegalStateException("No service factory found.");
        }
        log.info(String.format("Discover %d service factories.", builder.size()));
        delegateFactories = Collections.unmodifiableSet(builder);

    }

    private  ObserveServiceFactory getFactory(ObserveDataSourceConfiguration dataSourceConfiguration, Class serviceType) {

        Objects.requireNonNull(dataSourceConfiguration);
        Objects.requireNonNull(serviceType);

        Optional result = delegateFactories.stream()
                .filter(f -> f.accept(dataSourceConfiguration, serviceType))
                .findFirst();
        if (!result.isPresent()) {
            throw new NullPointerException(String.format("No factory found for dataSourceConfiguration: %s and serviceType: %s", dataSourceConfiguration, serviceType.getName()));
        }
        return result.get();

    }

    private  ObserveServiceFactory getFactory(ObserveDataSourceConnection dataSourceConnection, Class serviceType) {

        Objects.requireNonNull(dataSourceConnection);
        Objects.requireNonNull(serviceType);

        Optional result = delegateFactories.stream()
                .filter(f -> f.accept(dataSourceConnection, serviceType))
                .findFirst();
        if (!result.isPresent()) {
            throw new NullPointerException(String.format("No factory found for dataSourceConnection: %s and serviceType: %s", dataSourceConnection, serviceType.getName()));
        }
        return result.get();

    }

}