001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2017-2018 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.util;
020
021import java.lang.reflect.Array;
022import java.util.Arrays;
023import java.util.Collections;
024import java.util.HashMap;
025import java.util.List;
026import java.util.Map;
027import java.util.ServiceLoader;
028import java.util.function.Function;
029import java.util.function.IntFunction;
030import java.util.stream.Collectors;
031import org.jgrapes.core.Channel;
032import org.jgrapes.core.ComponentFactory;
033import org.jgrapes.util.events.ConfigurationUpdate;
034
035/**
036 * A component that collects all component factory services of 
037 * a given type and uses each to create one or more components
038 * that are then attached to the component collector instance.
039 * 
040 * Effectively, the component collector leverages the 
041 * mechanism provided by the service loader to configure
042 * the component subtree rooted at the collector at "link time".
043 * 
044 * This class uses {@link ComponentProvider#setFactories(ComponentFactory...)} 
045 * and {@link ComponentProvider#setPinned(List)} for its implementation.
046 * As it inherits from {@link ComponentProvider}, it automatically
047 * supports the provisioning of additional components through
048 * {@link ConfigurationUpdate} events. If this is not desired, invoke
049 * {@link ComponentProvider#setComponentsEntry(String)} with `null` as
050 * argument. 
051 * 
052 * @param <F> the component factory type
053 */
054public class ComponentCollector<F extends ComponentFactory>
055        extends ComponentProvider {
056
057    private static final List<Map<Object, Object>> SINGLE_DEFAULT
058        = List.of(Collections.emptyMap());
059
060    /**
061     * Creates a new collector that collects the factories of the given 
062     * type and uses each to create one or more instances with this 
063     * component's (the component collector's) channel. 
064     * 
065     * Before instances are created, the `matcher` function is 
066     * invoked with the name of the class of the component
067     * to be created as argument. The list of maps returned is
068     * used to create components, passing each element in the list
069     * as parameter to {@link ComponentFactory#create(Channel, Map)}.
070     * 
071     * @param factoryClass the factory class
072     * @param componentChannel this component's channel
073     * @param configurator the configurator function
074     */
075    public ComponentCollector(Class<F> factoryClass, Channel componentChannel,
076            Function<String, List<Map<Object, Object>>> configurator) {
077        super(componentChannel);
078        ServiceLoader<F> serviceLoader = ServiceLoader.load(factoryClass);
079
080        // Get all factories
081        IntFunction<F[]> createFactoryArray = size -> {
082            @SuppressWarnings("unchecked")
083            var res = (F[]) Array.newInstance(factoryClass, size);
084            return res;
085        };
086        var factories = serviceLoader.stream().map(p -> p.get())
087            .toArray(createFactoryArray);
088        setFactories(factories);
089
090        // Obtain a configuration for each factory
091        List<Map<?, ?>> configs = Arrays.stream(factories)
092            .map(factory -> configurator
093                .apply(factory.componentType().getName()).stream().map(c -> {
094                    if (c.containsKey(COMPONENT_TYPE)) {
095                        return c;
096                    }
097                    // The map may be immutable, copy.
098                    @SuppressWarnings("PMD.UseConcurrentHashMap")
099                    Map<Object, Object> newMap = new HashMap<>(c);
100                    newMap.put(COMPONENT_TYPE,
101                        factory.componentType().getName());
102                    return newMap;
103                }))
104            .flatMap(Function.identity()).collect(Collectors.toList());
105        setPinned(configs);
106    }
107
108    /**
109     * Utility constructor that uses each factory to create a single
110     * instance, using an empty map as properties.
111     * 
112     * @param factoryClass the factory class
113     * @param componentChannel this component's channel
114     */
115    public ComponentCollector(Class<F> factoryClass, Channel componentChannel) {
116        this(factoryClass, componentChannel, type -> SINGLE_DEFAULT);
117    }
118}