<commit_before>/*
 * JBoss, Home of Professional Open Source
 * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
 * as indicated by the @authors tag. All rights reserved.
 * See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This copyrighted material is made available to anyone wishing to use,
 * modify, copy, or redistribute it subject to the terms and conditions
 * of the GNU Lesser General Public License, v. 2.1.
 * This program is distributed in the hope that it will be useful, but WITHOUT A
 * 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,
 * v.2.1 along with this distribution; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */
package org.jboss.as.test.integration.domain.management.util;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import org.jboss.as.controller.ControlledProcessState;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.client.Operation;
import org.jboss.as.controller.client.OperationBuilder;
import org.jboss.as.controller.client.helpers.domain.DomainClient;
import org.jboss.as.controller.client.helpers.domain.ServerIdentity;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.network.NetworkUtils;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.remoting3.Channel;
import org.jboss.remoting3.Connection;
import org.jboss.sasl.util.UsernamePasswordHashUtil;
import org.wildfly.core.launcher.DomainCommandBuilder;

/**
 * Utility for controlling the lifecycle of a domain.
 *
 * @author <a href="<EMAIL>"><NAME></a>
 */
public class DomainLifecycleUtil {

    public static final String SLAVE_HOST_USERNAME = "slave";
    public static final String SLAVE_HOST_PASSWORD = "<PASSWORD>";

    private static final ThreadFactory threadFactory = new AsyncThreadFactory();

    private final Logger log = Logger.getLogger(DomainLifecycleUtil.class.getName());

    // The ProcessController process wrapper
    private ProcessWrapper process;
    // The connection to the HC, which can be shared across multiple clients
    private DomainTestConnection connection;
    // A shared domain client
    private DomainTestClient domainClient;

//    private Map<ServerIdentity, ControlledProcessState.State> serverStatuses = new HashMap<ServerIdentity, ControlledProcessState.State>();
    private ExecutorService executor;

    private final WildFlyManagedConfiguration configuration;
    private final DomainControllerClientConfig clientConfiguration;
    private final PathAddress address;
    private final boolean closeClientConfig;

    public DomainLifecycleUtil(final WildFlyManagedConfiguration configuration) throws IOException {
        this(configuration, DomainControllerClientConfig.create(), true);
    }

    public DomainLifecycleUtil(final WildFlyManagedConfiguration configuration, final DomainControllerClientConfig clientConfiguration) {
        this(configuration, clientConfiguration, false);
    }

    private DomainLifecycleUtil(final WildFlyManagedConfiguration configuration,
                                final DomainControllerClientConfig clientConfiguration, final boolean closeClientConfig) {
        assert configuration != null : "configuration is null";
        assert clientConfiguration != null : "clientConfiguration is null";
        this.configuration = configuration;
        this.clientConfiguration = clientConfiguration;
        this.address = PathAddress.pathAddress(PathElement.pathElement(ModelDescriptionConstants.HOST, configuration.getHostName()));
        this.closeClientConfig = closeClientConfig;
    }

    public WildFlyManagedConfiguration getConfiguration() {
        return configuration;
    }

    public PathAddress getAddress() {
        return address;
    }

    public void start() {
        try {
            configuration.validate();

            final String address = NetworkUtils.formatPossibleIpv6Address(configuration.getHostControllerManagementAddress());
            final int port = configuration.getHostControllerManagementPort();
            final URI connectionURI = new URI(configuration.getHostControllerManagementProtocol(), null, address, port, null, null, null);
            // Create the connection - this will try to connect on the first request
            connection = clientConfiguration.createConnection(connectionURI, configuration.getCallbackHandler());

            final DomainCommandBuilder commandBuilder;
            final String jbossHome = configuration.getJbossHome();
            if (configuration.getControllerJavaHome() == null) {
                commandBuilder = DomainCommandBuilder.of(jbossHome);
            } else {
                commandBuilder = DomainCommandBuilder.of(jbossHome, configuration.getControllerJavaHome());
            }

            final String jbossOptions = System.getProperty("jboss.options");
            if (jbossOptions != null) {
                final String[] javaOpts = jbossOptions.split("\\s+");
                commandBuilder.setHostControllerJavaOptions(javaOpts)
                        .setProcessControllerJavaOptions(javaOpts);
            }
            if (configuration.getJavaVmArguments() != null) {
                final String[] javaOpts = configuration.getJavaVmArguments().split("\\s+");
                commandBuilder.addHostControllerJavaOptions(javaOpts)
                        .addProcessControllerJavaOptions(javaOpts);
            }

            // Set the Java Home for the servers
            if (configuration.getJavaHome() != null) {
                commandBuilder.setServerJavaHome(configuration.getJavaHome());
            }

            if (configuration.getDomainDirectory() != null) {
                commandBuilder.setBaseDirectory(configuration.getDomainDirectory());
            }

            if (configuration.getModulePath() != null && !configuration.getModulePath().isEmpty()) {
                commandBuilder.setModuleDirs(configuration.getModulePath().split(Pattern.quote(File.pathSeparator)));
            }

            final Path domainDir = commandBuilder.getBaseDirectory();
            final Path configDir = commandBuilder.getConfigurationDirectory();

            if (configuration.getMgmtUsersFile() != null) {
                copyConfigFile(configuration.getMgmtUsersFile(), configDir, null);
            } else {
                // No point backing up the file in a test scenario, just write what we need.
                final String text = "slave=" + new UsernamePasswordHashUtil().generateHashedHexURP(SLAVE_HOST_USERNAME, "ManagementRealm", SLAVE_HOST_PASSWORD.toCharArray());<commit_msg>[WFCORE-258] Add a property to pass server arguments to a test domain server.<commit_after>/*
 * JBoss, Home of Professional Open Source
 * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
 * as indicated by the @authors tag. All rights reserved.
 * See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This copyrighted material is made available to anyone wishing to use,
 * modify, copy, or redistribute it subject to the terms and conditions
 * of the GNU Lesser General Public License, v. 2.1.
 * This program is distributed in the hope that it will be useful, but WITHOUT A
 * 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,
 * v.2.1 along with this distribution; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */
package org.jboss.as.test.integration.domain.management.util;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import org.jboss.as.controller.ControlledProcessState;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.client.Operation;
import org.jboss.as.controller.client.OperationBuilder;
import org.jboss.as.controller.client.helpers.domain.DomainClient;
import org.jboss.as.controller.client.helpers.domain.ServerIdentity;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.network.NetworkUtils;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.remoting3.Channel;
import org.jboss.remoting3.Connection;
import org.jboss.sasl.util.UsernamePasswordHashUtil;
import org.wildfly.core.launcher.DomainCommandBuilder;

/**
 * Utility for controlling the lifecycle of a domain.
 *
 * @author <a href="<EMAIL>"><NAME></a>
 */
public class DomainLifecycleUtil {

    public static final String SLAVE_HOST_USERNAME = "slave";
    public static final String SLAVE_HOST_PASSWORD = "<PASSWORD>";

    private static final ThreadFactory threadFactory = new AsyncThreadFactory();

    private final Logger log = Logger.getLogger(DomainLifecycleUtil.class.getName());

    // The ProcessController process wrapper
    private ProcessWrapper process;
    // The connection to the HC, which can be shared across multiple clients
    private DomainTestConnection connection;
    // A shared domain client
    private DomainTestClient domainClient;

//    private Map<ServerIdentity, ControlledProcessState.State> serverStatuses = new HashMap<ServerIdentity, ControlledProcessState.State>();
    private ExecutorService executor;

    private final WildFlyManagedConfiguration configuration;
    private final DomainControllerClientConfig clientConfiguration;
    private final PathAddress address;
    private final boolean closeClientConfig;

    public DomainLifecycleUtil(final WildFlyManagedConfiguration configuration) throws IOException {
        this(configuration, DomainControllerClientConfig.create(), true);
    }

    public DomainLifecycleUtil(final WildFlyManagedConfiguration configuration, final DomainControllerClientConfig clientConfiguration) {
        this(configuration, clientConfiguration, false);
    }

    private DomainLifecycleUtil(final WildFlyManagedConfiguration configuration,
                                final DomainControllerClientConfig clientConfiguration, final boolean closeClientConfig) {
        assert configuration != null : "configuration is null";
        assert clientConfiguration != null : "clientConfiguration is null";
        this.configuration = configuration;
        this.clientConfiguration = clientConfiguration;
        this.address = PathAddress.pathAddress(PathElement.pathElement(ModelDescriptionConstants.HOST, configuration.getHostName()));
        this.closeClientConfig = closeClientConfig;
    }

    public WildFlyManagedConfiguration getConfiguration() {
        return configuration;
    }

    public PathAddress getAddress() {
        return address;
    }

    public void start() {
        try {
            configuration.validate();

            final String address = NetworkUtils.formatPossibleIpv6Address(configuration.getHostControllerManagementAddress());
            final int port = configuration.getHostControllerManagementPort();
            final URI connectionURI = new URI(configuration.getHostControllerManagementProtocol(), null, address, port, null, null, null);
            // Create the connection - this will try to connect on the first request
            connection = clientConfiguration.createConnection(connectionURI, configuration.getCallbackHandler());

            final DomainCommandBuilder commandBuilder;
            final String jbossHome = configuration.getJbossHome();
            if (configuration.getControllerJavaHome() == null) {
                commandBuilder = DomainCommandBuilder.of(jbossHome);
            } else {
                commandBuilder = DomainCommandBuilder.of(jbossHome, configuration.getControllerJavaHome());
            }

            final String jbossOptions = System.getProperty("jboss.options");
            if (jbossOptions != null) {
                final String[] javaOpts = jbossOptions.split("\\s+");
                commandBuilder.setHostControllerJavaOptions(javaOpts)
                        .setProcessControllerJavaOptions(javaOpts);
            }
            if (configuration.getJavaVmArguments() != null) {
                final String[] javaOpts = configuration.getJavaVmArguments().split("\\s+");
                commandBuilder.addHostControllerJavaOptions(javaOpts)
                        .addProcessControllerJavaOptions(javaOpts);
            }

            final String jbossArgs = System.getProperty("jboss.domain.server.args");
            if (jbossArgs != null) {
                commandBuilder.addServerArguments(jbossArgs.split("\\s+"));
            }

            // Set the Java Home for the servers
            if (configuration.getJavaHome() != null) {
                commandBuilder.setServerJavaHome(configuration.getJavaHome());
            }

            if (configuration.getDomainDirectory() != null) {
                commandBuilder.setBaseDirectory(configuration.getDomainDirectory());
            }

            if (configuration.getModulePath() != null && !configuration.getModulePath().isEmpty()) {
                commandBuilder.setModuleDirs(configuration.getModulePath().split(Pattern.quote(File.pathSeparator)));
            }

            final Path domainDir = commandBuilder.getBaseDirectory();
            final Path configDir = commandBuilder.getConfigurationDirectory();

            if (configuration.getMgmtUsersFile() != null) {
                copyConfigFile(configuration.getMgmtUsersFile(), configDir, null);
            } else {
                // No point backing up the file in a test scenario, just write what we need.
                final String text = "slave=" + new UsernamePasswordHashUtil().generateHashedHexURP(SLAVE_HOST_USERNAME, "ManagementRealm", SLAVE_HOST_PASSWORD.toCharArray());
{'fraction_non_alphanumeric': 0.08336978938816324, 'fraction_numerical': 0.002937316417723892, 'mean_word_length': 3.595634692705342, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '3409087', 'n_tokens_mistral': 3994, 'n_tokens_neox': 3817, 'n_words': 1063}