/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2013, Red Hat, Inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.as.ejb3.cache.distributable;

import java.time.Duration;
import java.util.Collection;
import java.util.Iterator;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import org.jboss.as.clustering.controller.CapabilityServiceConfigurator;
import org.jboss.as.ee.component.ComponentConfiguration;
import org.jboss.as.ejb3.cache.Contextual;
import org.jboss.as.ejb3.cache.Identifiable;
import org.jboss.as.ejb3.component.stateful.StatefulComponentDescription;
import org.jboss.as.ejb3.component.stateful.StatefulTimeoutInfo;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.modules.ModuleLoader;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.wildfly.clustering.ee.Batch;
import org.wildfly.clustering.ejb.BeanContext;
import org.wildfly.clustering.ejb.BeanManagerFactoryServiceConfiguratorConfiguration;
import org.wildfly.clustering.ejb.BeanManagerFactoryServiceConfiguratorFactory;
import org.wildfly.clustering.ejb.BeanManagerFactoryServiceConfiguratorFactoryProvider;
import org.wildfly.clustering.service.ServiceConfigurator;

/**
 * Service that returns a distributable {@link org.jboss.as.ejb3.cache.CacheFactoryBuilder}.
 * @author Paul Ferraro
 * @param <K> the cache key type
 * @param <V> the cache value type
 */
public class DistributableCacheFactoryBuilderServiceConfigurator<K, V extends Identifiable<K> & Contextual<Batch>> extends DistributableCacheFactoryBuilderServiceNameProvider implements ServiceConfigurator, DistributableCacheFactoryBuilder<K, V> {

    private final BeanManagerFactoryServiceConfiguratorFactory builder;
    private final BeanManagerFactoryServiceConfiguratorConfiguration config;

    public DistributableCacheFactoryBuilderServiceConfigurator(String name, BeanManagerFactoryServiceConfiguratorConfiguration config) {
        this(name, load(), config);
    }

    private static BeanManagerFactoryServiceConfiguratorFactoryProvider load() {
        Iterator<BeanManagerFactoryServiceConfiguratorFactoryProvider> providers = ServiceLoader.load(BeanManagerFactoryServiceConfiguratorFactoryProvider.class, BeanManagerFactoryServiceConfiguratorFactoryProvider.class.getClassLoader()).iterator();
        if (!providers.hasNext()) {
            throw new ServiceConfigurationError(BeanManagerFactoryServiceConfiguratorFactoryProvider.class.getName());
        }
        return providers.next();
    }

    public DistributableCacheFactoryBuilderServiceConfigurator(String name, BeanManagerFactoryServiceConfiguratorFactoryProvider provider, BeanManagerFactoryServiceConfiguratorConfiguration config) {
        super(name);
        this.config = config;
        this.builder = provider.getBeanManagerFactoryBuilder(name, config);
    }

    @Override
    public ServiceBuilder<?> build(ServiceTarget target) {
        ServiceName name = this.getServiceName();
        ServiceBuilder<?> builder = target.addService(name);
        Consumer<DistributableCacheFactoryBuilder<K, V>> cacheFactoryBuilder = builder.provides(name);
        Service service = Service.newInstance(cacheFactoryBuilder, this);
        return builder.setInstance(service);
    }

    @Override
    public BeanManagerFactoryServiceConfiguratorConfiguration getConfiguration() {
        return this.config;
    }

    @Override
    public Collection<CapabilityServiceConfigurator> getDeploymentServiceConfigurators(DeploymentUnit unit) {
        return this.builder.getDeploymentServiceConfigurators(unit.getServiceName());
    }

    @Override
    public CapabilityServiceConfigurator getServiceConfigurator(ServiceName name, StatefulComponentDescription description, ComponentConfiguration configuration) {
        BeanContext context = new BeanContext() {
            @Override
            public String getBeanName() {
                return configuration.getComponentName();
            }

            @Override
            public ServiceName getDeploymentUnitServiceName() {
                return description.getDeploymentUnitServiceName();
            }

            @Override
            public ModuleLoader getModuleLoader() {
                return configuration.getModuleLoader();
            }

            @Override
            public ClassLoader getClassLoader() {
                return configuration.getModuleClassLoader();
            }

            @Override
            public Duration getTimeout() {
                StatefulTimeoutInfo info = description.getStatefulTimeout();
                // TODO Once based on JDK9+, change to Duration.of(this.info.getValue(), this.info.getTimeUnit().toChronoUnit())
                return (info != null) ? Duration.ofMillis(TimeUnit.MILLISECONDS.convert(info.getValue(), info.getTimeUnit())) : null;
            }
        };
        CapabilityServiceConfigurator configurator = this.builder.getBeanManagerFactoryServiceConfigurator(context);
        return new DistributableCacheFactoryServiceConfigurator<K, V>(name, configurator);
    }

    @Override
    public boolean supportsPassivation() {
        return true;
    }
}

@@ -1064,16 +1064,55 @@
 table;%0A%0A
+import java.security.PrivilegedAction;%0A
 import j
@@ -2347,16 +2347,76 @@
 gurator;
+%0Aimport org.wildfly.security.manager.WildFlySecurityManager;
 %0A%0A/**%0A *
@@ -3349,22 +3349,8 @@
 s = 
-ServiceLoader.
 load
@@ -3412,85 +3412,8 @@
 lass
-, BeanManagerFactoryServiceConfiguratorFactoryProvider.class.getClassLoader()
 ).it
@@ -3623,24 +3623,417 @@
 t();%0A    %7D%0A%0A
+    private static %3CT%3E Iterable%3CT%3E load(Class%3CT%3E providerClass) %7B%0A        PrivilegedAction%3CIterable%3CT%3E%3E action = new PrivilegedAction%3CIterable%3CT%3E%3E() %7B%0A            @Override%0A            public Iterable%3CT%3E run() %7B%0A                return ServiceLoader.load(providerClass, providerClass.getClassLoader());%0A            %7D%0A        %7D;%0A        return WildFlySecurityManager.doUnchecked(action);%0A    %7D%0A%0A
     public D

Use PrivilegedAction for BeanManagerFactoryServiceConfiguratorFactoryProvider loading.