<commit_before>/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2011, 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.cli;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jboss.as.cli.handlers.ConnectHandler;
import org.jboss.as.cli.handlers.PrintWorkingNodeHandler;
import org.jboss.as.cli.handlers.DeployHandler;
import org.jboss.as.cli.handlers.HelpHandler;
import org.jboss.as.cli.handlers.HistoryHandler;
import org.jboss.as.cli.handlers.LsHandler;
import org.jboss.as.cli.handlers.OperationRequestHandler;
import org.jboss.as.cli.handlers.PrefixHandler;
import org.jboss.as.cli.handlers.QuitHandler;
import org.jboss.as.cli.handlers.UndeployHandler;
import org.jboss.as.cli.operation.OperationCandidatesProvider;
import org.jboss.as.cli.operation.OperationRequestAddress;
import org.jboss.as.cli.operation.OperationRequestCompleter;
import org.jboss.as.cli.operation.OperationRequestParser;
import org.jboss.as.cli.operation.PrefixFormatter;
import org.jboss.as.cli.operation.impl.DefaultOperationCandidatesProvider;
import org.jboss.as.cli.operation.impl.DefaultOperationRequestAddress;
import org.jboss.as.cli.operation.impl.DefaultOperationRequestParser;
import org.jboss.as.cli.operation.impl.DefaultPrefixFormatter;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.protocol.StreamUtils;

/**
 *
 * @author <NAME>
 */
public class CommandLineMain {

    private static final Map<String, CommandHandler> handlers = new HashMap<String, CommandHandler>();
    static {
        registerHandler(new HelpHandler(), "help", "h");
        registerHandler(new QuitHandler(), "quit", "q");
        registerHandler(new ConnectHandler(), "connect");
        registerHandler(new PrefixHandler(), "cd", "cn");
        registerHandler(new LsHandler(), "ls");
        registerHandler(new HistoryHandler(), "history");
        registerHandler(new DeployHandler(), "deploy");
        registerHandler(new UndeployHandler(), "undeploy");
        registerHandler(new PrintWorkingNodeHandler(), "pwn", "pwd");
    }

    private static void registerHandler(CommandHandler handler, String... names) {
        for(String name : names) {
            CommandHandler previous = handlers.put(name, handler);
            if(previous != null)
                throw new IllegalStateException("Duplicate command name '" + name + "'. Handlers: " + previous + ", " + handler);
        }
    }

    private static final CommandHandler operationHandler = new OperationRequestHandler();

    public static void main(String[] args) throws Exception {

        final jline.ConsoleReader console = initConsoleReader();

        final CommandContextImpl cmdCtx = new CommandContextImpl(console);
        SecurityActions.addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                cmdCtx.disconnectController();
            }
        }));
        OperationRequestCompleter opCompleter = new OperationRequestCompleter(cmdCtx);
        console.addCompletor(new CommandCompleter(handlers.keySet(), cmdCtx, opCompleter));
        console.addCompletor(opCompleter);

        boolean connect = false;
        for(String arg : args) {
            if(arg.startsWith("controller=")) {
                String value = arg.substring(11);
                String portStr = null;
                int colonIndex = value.indexOf(':');
                if(colonIndex < 0) {
                    // default port
                    cmdCtx.defaultControllerHost = value;
                } else if(colonIndex == 0) {
                    // default host
                    portStr = value.substring(1);
                } else {
                    cmdCtx.defaultControllerHost = value.substring(0, colonIndex);
                    portStr = value.substring(colonIndex + 1);
                }

                if(portStr != null) {
                    int port = -1;
                    try {
                        port = Integer.parseInt(portStr);
                        if(port < 0) {
                            cmdCtx.printLine("The port must be a valid non-negative integer: '" + args + "'");
                        } else {
                            cmdCtx.defaultControllerPort = port;
                        }
                    } catch(NumberFormatException e) {
                        cmdCtx.printLine("The port must be a valid non-negative integer: '" + arg + "'");
                    }
                }
            } else if("--connect".equals(arg)) {
                connect = true;
            }
        }

        if(connect) {
            cmdCtx.connectController(null, -1);
        } else {
            cmdCtx.printLine("You are disconnected at the moment." +
                " Type 'connect' to connect to the server or" +
                " 'help' for the list of supported commands.");
        }

        while (!cmdCtx.terminate) {
            String line = console.readLine(cmdCtx.getPrompt()).trim();

            if (line.isEmpty()) {
                // cmdCtx.log("Type /help for the list of supported commands.");
                continue;
            }

            if(isOperation(line)) {
                cmdCtx.cmdArgs = line;
                operationHandler.handle(cmdCtx);

            } else {
                String cmd = line;
                String cmdArgs = null;
                for (int i = 0; i < cmd.length(); ++i) {
                    if (Character.isWhitespace(cmd.charAt(i))) {
                        cmdArgs = cmd.substring(i + 1).trim();
                        cmd = cmd.substring(0, i);
                        break;
                    }
                }
                cmdCtx.setArgs(cmdArgs);

                CommandHandler handler = handlers.get(cmd.toLowerCase());
                if (handler != null) {
                    handler.handle(cmdCtx);
                } else {
                    cmdCtx.printLine("Unexpected command '"
                            + line
                            + "'. Type 'help' for the list of supported commands.");
                }
            }
        }
        StreamUtils.safeClose(cmdCtx.client);
    }

    protected static jline.ConsoleReader initConsoleReader() {

        final String bindingsName;
        final String osName = SecurityActions.getSystemProperty("os.name").toLowerCase();
        if(osName.indexOf("windows") >= 0) {
            bindingsName = "keybindings/jline-windows-bindings.properties";
        } else if(osName.startsWith("macos")) {
            bindingsName = "keybindings/jline-mac-bindings.properties";
        } else {
            bindingsName = "keybindings/jline-default-bindings.properties";
        }

        ClassLoader cl = SecurityActions.getClassLoader(CommandLineMain.class);
        InputStream bindingsIs = cl.getResourceAsStream(bindingsName);
        if(bindingsIs == null) {
            System.err.println("Failed to locate key bindings for OS '" + osName +"': " + bindingsName);
            try {<commit_msg>fixed mac key bindings (thanks pilhuhn)<commit_after>/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2011, 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.cli;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jboss.as.cli.handlers.ConnectHandler;
import org.jboss.as.cli.handlers.PrintWorkingNodeHandler;
import org.jboss.as.cli.handlers.DeployHandler;
import org.jboss.as.cli.handlers.HelpHandler;
import org.jboss.as.cli.handlers.HistoryHandler;
import org.jboss.as.cli.handlers.LsHandler;
import org.jboss.as.cli.handlers.OperationRequestHandler;
import org.jboss.as.cli.handlers.PrefixHandler;
import org.jboss.as.cli.handlers.QuitHandler;
import org.jboss.as.cli.handlers.UndeployHandler;
import org.jboss.as.cli.operation.OperationCandidatesProvider;
import org.jboss.as.cli.operation.OperationRequestAddress;
import org.jboss.as.cli.operation.OperationRequestCompleter;
import org.jboss.as.cli.operation.OperationRequestParser;
import org.jboss.as.cli.operation.PrefixFormatter;
import org.jboss.as.cli.operation.impl.DefaultOperationCandidatesProvider;
import org.jboss.as.cli.operation.impl.DefaultOperationRequestAddress;
import org.jboss.as.cli.operation.impl.DefaultOperationRequestParser;
import org.jboss.as.cli.operation.impl.DefaultPrefixFormatter;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.protocol.StreamUtils;

/**
 *
 * @author <NAME>
 */
public class CommandLineMain {

    private static final Map<String, CommandHandler> handlers = new HashMap<String, CommandHandler>();
    static {
        registerHandler(new HelpHandler(), "help", "h");
        registerHandler(new QuitHandler(), "quit", "q");
        registerHandler(new ConnectHandler(), "connect");
        registerHandler(new PrefixHandler(), "cd", "cn");
        registerHandler(new LsHandler(), "ls");
        registerHandler(new HistoryHandler(), "history");
        registerHandler(new DeployHandler(), "deploy");
        registerHandler(new UndeployHandler(), "undeploy");
        registerHandler(new PrintWorkingNodeHandler(), "pwn", "pwd");
    }

    private static void registerHandler(CommandHandler handler, String... names) {
        for(String name : names) {
            CommandHandler previous = handlers.put(name, handler);
            if(previous != null)
                throw new IllegalStateException("Duplicate command name '" + name + "'. Handlers: " + previous + ", " + handler);
        }
    }

    private static final CommandHandler operationHandler = new OperationRequestHandler();

    public static void main(String[] args) throws Exception {

        final jline.ConsoleReader console = initConsoleReader();

        final CommandContextImpl cmdCtx = new CommandContextImpl(console);
        SecurityActions.addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                cmdCtx.disconnectController();
            }
        }));
        OperationRequestCompleter opCompleter = new OperationRequestCompleter(cmdCtx);
        console.addCompletor(new CommandCompleter(handlers.keySet(), cmdCtx, opCompleter));
        console.addCompletor(opCompleter);

        boolean connect = false;
        for(String arg : args) {
            if(arg.startsWith("controller=")) {
                String value = arg.substring(11);
                String portStr = null;
                int colonIndex = value.indexOf(':');
                if(colonIndex < 0) {
                    // default port
                    cmdCtx.defaultControllerHost = value;
                } else if(colonIndex == 0) {
                    // default host
                    portStr = value.substring(1);
                } else {
                    cmdCtx.defaultControllerHost = value.substring(0, colonIndex);
                    portStr = value.substring(colonIndex + 1);
                }

                if(portStr != null) {
                    int port = -1;
                    try {
                        port = Integer.parseInt(portStr);
                        if(port < 0) {
                            cmdCtx.printLine("The port must be a valid non-negative integer: '" + args + "'");
                        } else {
                            cmdCtx.defaultControllerPort = port;
                        }
                    } catch(NumberFormatException e) {
                        cmdCtx.printLine("The port must be a valid non-negative integer: '" + arg + "'");
                    }
                }
            } else if("--connect".equals(arg)) {
                connect = true;
            }
        }

        if(connect) {
            cmdCtx.connectController(null, -1);
        } else {
            cmdCtx.printLine("You are disconnected at the moment." +
                " Type 'connect' to connect to the server or" +
                " 'help' for the list of supported commands.");
        }

        while (!cmdCtx.terminate) {
            String line = console.readLine(cmdCtx.getPrompt()).trim();

            if (line.isEmpty()) {
                // cmdCtx.log("Type /help for the list of supported commands.");
                continue;
            }

            if(isOperation(line)) {
                cmdCtx.cmdArgs = line;
                operationHandler.handle(cmdCtx);

            } else {
                String cmd = line;
                String cmdArgs = null;
                for (int i = 0; i < cmd.length(); ++i) {
                    if (Character.isWhitespace(cmd.charAt(i))) {
                        cmdArgs = cmd.substring(i + 1).trim();
                        cmd = cmd.substring(0, i);
                        break;
                    }
                }
                cmdCtx.setArgs(cmdArgs);

                CommandHandler handler = handlers.get(cmd.toLowerCase());
                if (handler != null) {
                    handler.handle(cmdCtx);
                } else {
                    cmdCtx.printLine("Unexpected command '"
                            + line
                            + "'. Type 'help' for the list of supported commands.");
                }
            }
        }
        StreamUtils.safeClose(cmdCtx.client);
    }

    protected static jline.ConsoleReader initConsoleReader() {

        final String bindingsName;
        final String osName = SecurityActions.getSystemProperty("os.name").toLowerCase();
        if(osName.indexOf("windows") >= 0) {
            bindingsName = "keybindings/jline-windows-bindings.properties";
        } else if(osName.startsWith("mac")) {
            bindingsName = "keybindings/jline-mac-bindings.properties";
        } else {
            bindingsName = "keybindings/jline-default-bindings.properties";
        }

        ClassLoader cl = SecurityActions.getClassLoader(CommandLineMain.class);
        InputStream bindingsIs = cl.getResourceAsStream(bindingsName);
        if(bindingsIs == null) {
            System.err.println("Failed to locate key bindings for OS '" + osName +"': " + bindingsName);
            try {
{'fraction_non_alphanumeric': 0.10242041254322165, 'fraction_numerical': 0.0036961964945749375, 'mean_word_length': 2.219769673704415, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5932544', 'n_tokens_mistral': 4494, 'n_tokens_neox': 4294, 'n_words': 1099}