<commit_before>/*
 * JBoss, Home of Professional Open Source
 * Copyright 2010, Red Hat Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt 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.weld;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.function.Consumer;
import java.util.function.Supplier;

import javax.enterprise.inject.spi.BeanManager;

import org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl;
import org.jboss.as.weld.deployment.WeldDeployment;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.services.ModuleGroupSingletonProvider;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import org.jboss.weld.Container;
import org.jboss.weld.ContainerState;
import org.jboss.weld.bootstrap.WeldBootstrap;
import org.jboss.weld.bootstrap.api.Environment;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.manager.BeanManagerImpl;
import org.jboss.weld.manager.api.ExecutorServices;
import org.jboss.weld.security.spi.SecurityServices;
import org.jboss.weld.transaction.spi.TransactionServices;
import org.wildfly.security.manager.WildFlySecurityManager;

/**
 * Provides the initial bootstrap of the Weld container. This does not actually finish starting the container, merely gets it to
 * the point that the bean manager is available.
 *
 * @author <NAME>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
public class WeldBootstrapService implements Service {

    public static final ServiceName SERVICE_NAME = ServiceName.of("WeldBootstrapService");

    private final WeldBootstrap bootstrap;
    private final WeldDeployment deployment;
    private final Environment environment;
    private final Map<String, BeanDeploymentArchive> beanDeploymentArchives;
    private final BeanDeploymentArchiveImpl rootBeanDeploymentArchive;

    private final String deploymentName;
    private final Consumer<WeldBootstrapService> weldBootstrapServiceConsumer;
    private final Supplier<ExecutorServices> executorServicesSupplier;
    private final Supplier<ExecutorService> serverExecutorSupplier;
    private final Supplier<SecurityServices> securityServicesSupplier;
    private final Supplier<TransactionServices> weldTransactionServicesSupplier;

    private volatile boolean started;

    public WeldBootstrapService(final WeldDeployment deployment, final Environment environment, final String deploymentName,
                                final Consumer<WeldBootstrapService> weldBootstrapServiceConsumer,
                                final Supplier<ExecutorServices> executorServicesSupplier,
                                final Supplier<ExecutorService> serverExecutorSupplier,
                                final Supplier<SecurityServices> securityServicesSupplier,
                                final Supplier<TransactionServices> weldTransactionServicesSupplier
    ) {
        this.deployment = deployment;
        this.environment = environment;
        this.deploymentName = deploymentName;
        this.weldBootstrapServiceConsumer = weldBootstrapServiceConsumer;
        this.executorServicesSupplier = executorServicesSupplier;
        this.serverExecutorSupplier = serverExecutorSupplier;
        this.securityServicesSupplier = securityServicesSupplier;
        this.weldTransactionServicesSupplier = weldTransactionServicesSupplier;
        this.bootstrap = new WeldBootstrap();
        Map<String, BeanDeploymentArchive> bdas = new HashMap<String, BeanDeploymentArchive>();
        BeanDeploymentArchiveImpl rootBeanDeploymentArchive = null;
        for (BeanDeploymentArchive archive : deployment.getBeanDeploymentArchives()) {
            bdas.put(archive.getId(), archive);
            if (archive instanceof BeanDeploymentArchiveImpl) {
                BeanDeploymentArchiveImpl bda = (BeanDeploymentArchiveImpl) archive;
                if (bda.isRoot()) {
                    rootBeanDeploymentArchive = bda;
                }
            }
        }
        this.rootBeanDeploymentArchive = rootBeanDeploymentArchive;
        this.beanDeploymentArchives = Collections.unmodifiableMap(bdas);
    }

    /**
     * Starts the weld container
     *
     * @throws IllegalStateException if the container is already running
     */
    public synchronized void start(final StartContext context) {
        if (started) {
            throw WeldLogger.ROOT_LOGGER.alreadyRunning("WeldContainer");
        }
        started = true;

        WeldLogger.DEPLOYMENT_LOGGER.startingWeldService(deploymentName);
        // set up injected services
        addWeldService(SecurityServices.class, securityServicesSupplier.get());

        TransactionServices transactionServices = weldTransactionServicesSupplier.get();
        if (transactionServices != null) {
            addWeldService(TransactionServices.class, transactionServices);
        }

        if (!deployment.getServices().contains(ExecutorServices.class)) {
            addWeldService(ExecutorServices.class, executorServicesSupplier.get());
        }

        ModuleGroupSingletonProvider.addClassLoaders(deployment.getModule().getClassLoader(),
                deployment.getSubDeploymentClassLoaders());

        ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
        try {
            WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(deployment.getModule().getClassLoader());
            bootstrap.startContainer(deploymentName, environment, deployment);
            WeldProvider.containerInitialized(Container.instance(deploymentName), getBeanManager(), deployment);
        } finally {
            WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
        }
        weldBootstrapServiceConsumer.accept(this);
    }

    /**
     * This is a no-op if {@link WeldStartService#start(StartContext)} completes normally and the shutdown is performed in
     * {@link WeldStartService#stop(org.jboss.msc.service.StopContext)}.
     */
    public synchronized void stop(final StopContext context) {
        weldBootstrapServiceConsumer.accept(null);
        if (started) {
            // WeldStartService#stop() not completed - attempt to perform the container cleanup<commit_msg>[WFLY-11734] Weld subsystem throws NPE deploying an application if transactions subsystem is missing<commit_after>/*
 * JBoss, Home of Professional Open Source
 * Copyright 2010, Red Hat Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt 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.weld;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.function.Consumer;
import java.util.function.Supplier;

import javax.enterprise.inject.spi.BeanManager;

import org.jboss.as.weld.deployment.BeanDeploymentArchiveImpl;
import org.jboss.as.weld.deployment.WeldDeployment;
import org.jboss.as.weld.logging.WeldLogger;
import org.jboss.as.weld.services.ModuleGroupSingletonProvider;
import org.jboss.msc.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StopContext;
import org.jboss.weld.Container;
import org.jboss.weld.ContainerState;
import org.jboss.weld.bootstrap.WeldBootstrap;
import org.jboss.weld.bootstrap.api.Environment;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.manager.BeanManagerImpl;
import org.jboss.weld.manager.api.ExecutorServices;
import org.jboss.weld.security.spi.SecurityServices;
import org.jboss.weld.transaction.spi.TransactionServices;
import org.wildfly.security.manager.WildFlySecurityManager;

/**
 * Provides the initial bootstrap of the Weld container. This does not actually finish starting the container, merely gets it to
 * the point that the bean manager is available.
 *
 * @author <NAME>
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
public class WeldBootstrapService implements Service {

    public static final ServiceName SERVICE_NAME = ServiceName.of("WeldBootstrapService");

    private final WeldBootstrap bootstrap;
    private final WeldDeployment deployment;
    private final Environment environment;
    private final Map<String, BeanDeploymentArchive> beanDeploymentArchives;
    private final BeanDeploymentArchiveImpl rootBeanDeploymentArchive;

    private final String deploymentName;
    private final Consumer<WeldBootstrapService> weldBootstrapServiceConsumer;
    private final Supplier<ExecutorServices> executorServicesSupplier;
    private final Supplier<ExecutorService> serverExecutorSupplier;
    private final Supplier<SecurityServices> securityServicesSupplier;
    private final Supplier<TransactionServices> weldTransactionServicesSupplier;

    private volatile boolean started;

    public WeldBootstrapService(final WeldDeployment deployment, final Environment environment, final String deploymentName,
                                final Consumer<WeldBootstrapService> weldBootstrapServiceConsumer,
                                final Supplier<ExecutorServices> executorServicesSupplier,
                                final Supplier<ExecutorService> serverExecutorSupplier,
                                final Supplier<SecurityServices> securityServicesSupplier,
                                final Supplier<TransactionServices> weldTransactionServicesSupplier
    ) {
        this.deployment = deployment;
        this.environment = environment;
        this.deploymentName = deploymentName;
        this.weldBootstrapServiceConsumer = weldBootstrapServiceConsumer;
        this.executorServicesSupplier = executorServicesSupplier;
        this.serverExecutorSupplier = serverExecutorSupplier;
        this.securityServicesSupplier = securityServicesSupplier;
        this.weldTransactionServicesSupplier = weldTransactionServicesSupplier;
        this.bootstrap = new WeldBootstrap();
        Map<String, BeanDeploymentArchive> bdas = new HashMap<String, BeanDeploymentArchive>();
        BeanDeploymentArchiveImpl rootBeanDeploymentArchive = null;
        for (BeanDeploymentArchive archive : deployment.getBeanDeploymentArchives()) {
            bdas.put(archive.getId(), archive);
            if (archive instanceof BeanDeploymentArchiveImpl) {
                BeanDeploymentArchiveImpl bda = (BeanDeploymentArchiveImpl) archive;
                if (bda.isRoot()) {
                    rootBeanDeploymentArchive = bda;
                }
            }
        }
        this.rootBeanDeploymentArchive = rootBeanDeploymentArchive;
        this.beanDeploymentArchives = Collections.unmodifiableMap(bdas);
    }

    /**
     * Starts the weld container
     *
     * @throws IllegalStateException if the container is already running
     */
    public synchronized void start(final StartContext context) {
        if (started) {
            throw WeldLogger.ROOT_LOGGER.alreadyRunning("WeldContainer");
        }
        started = true;

        WeldLogger.DEPLOYMENT_LOGGER.startingWeldService(deploymentName);
        // set up injected services
        addWeldService(SecurityServices.class, securityServicesSupplier.get());

        TransactionServices transactionServices = weldTransactionServicesSupplier != null ? weldTransactionServicesSupplier.get() : null;
        if (transactionServices != null) {
            addWeldService(TransactionServices.class, transactionServices);
        }

        if (!deployment.getServices().contains(ExecutorServices.class)) {
            addWeldService(ExecutorServices.class, executorServicesSupplier.get());
        }

        ModuleGroupSingletonProvider.addClassLoaders(deployment.getModule().getClassLoader(),
                deployment.getSubDeploymentClassLoaders());

        ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
        try {
            WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(deployment.getModule().getClassLoader());
            bootstrap.startContainer(deploymentName, environment, deployment);
            WeldProvider.containerInitialized(Container.instance(deploymentName), getBeanManager(), deployment);
        } finally {
            WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl);
        }
        weldBootstrapServiceConsumer.accept(this);
    }

    /**
     * This is a no-op if {@link WeldStartService#start(StartContext)} completes normally and the shutdown is performed in
     * {@link WeldStartService#stop(org.jboss.msc.service.StopContext)}.
     */
    public synchronized void stop(final StopContext context) {
        weldBootstrapServiceConsumer.accept(null);
        if (started) {
            // WeldStartService#stop() not completed - attempt to perform the container cleanup
{'fraction_non_alphanumeric': 0.07331989247311828, 'fraction_numerical': 0.002620967741935484, 'mean_word_length': 3.751277139208174, 'pattern_counts': {'":': 0, '<': 39, '<?xml version=': 0, '>': 39, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2278542', 'n_tokens_mistral': 3880, 'n_tokens_neox': 3688, 'n_words': 964}