Package org.jboss.as.cli

Examples of org.jboss.as.cli.CommandContext


    }

    @Test
    public void testDeployUndeployArchive() throws Exception {

        final CommandContext ctx = CLITestUtil.getCommandContext();
        try {
            ctx.connectController();
            ctx.handle("deploy " + cliArchiveFile.getAbsolutePath());

            // check that now both wars are deployed
            String response = HttpRequest.get(getBaseURL(url) + "deployment0/SimpleServlet", 10, TimeUnit.SECONDS);
            assertTrue("Invalid response: " + response, response.indexOf("SimpleServlet") >=0);
            response = HttpRequest.get(getBaseURL(url) + "deployment1/SimpleServlet", 10, TimeUnit.SECONDS);
            assertTrue("Invalid response: " + response, response.indexOf("SimpleServlet") >=0);
            assertTrue(checkUndeployed(getBaseURL(url) + "deployment2/SimpleServlet"));

            ctx.handle("undeploy " + "--path=" + cliArchiveFile.getAbsolutePath());

            // check that both wars are undeployed
            assertTrue(checkUndeployed(getBaseURL(url) + "deployment0/SimpleServlet"));
            assertTrue(checkUndeployed(getBaseURL(url) + "deployment1/SimpleServlet"));
        } finally {
            ctx.terminateSession();
        }
    }
View Full Code Here


     * @throws IOException              if the client has an IOException
     * @throws IllegalArgumentException if an command is invalid
     */
    public final void execute(final ModelControllerClient client) throws IOException {
        if (hasCommands()) {
            final CommandContext ctx = create();
            try {
                if (isBatch()) {
                    final CompositeOperationBuilder builder = CompositeOperationBuilder.create();
                    for (String cmd : getCommands()) {
                        try {
                            builder.addStep(ctx.buildRequest(cmd));
                        } catch (CommandFormatException e) {
                            throw new IllegalArgumentException(String.format("Command '%s' is invalid", cmd), e);
                        }
                    }
                    final ModelNode result = client.execute(builder.build());
                    if (!Operations.successful(result)) {
                        throw new IllegalArgumentException(Operations.getFailureDescription(result));
                    }
                } else {
                    for (String cmd : getCommands()) {
                        final ModelNode result;
                        try {
                            result = client.execute(ctx.buildRequest(cmd));
                        } catch (CommandFormatException e) {
                            throw new IllegalArgumentException(String.format("Command '%s' is invalid", cmd), e);
                        }
                        if (!Operations.successful(result)) {
                            throw new IllegalArgumentException(String.format("Command '%s' was unsuccessful. Reason: %s", cmd, Operations.getFailureDescription(result)));
                        }
                    }
                }
            } finally {
                ctx.terminateSession();
            }
        }
    }
View Full Code Here

     * @return the command line context
     *
     * @throws IllegalStateException if the context fails to initialize
     */
    public static CommandContext create() {
        final CommandContext commandContext;
        try {
            commandContext = CommandContextFactory.getInstance().newCommandContext();
        } catch (CliInitializationException e) {
            throw new IllegalStateException("Failed to initialize CLI context", e);
        }
View Full Code Here

    this.jbossProcess = jbossProcess;
    this.context = context;

    logger.branch(Type.INFO, "Starting container initialization...");

    CommandContext ctx = null;
    try {
      try {
        logger.branch(Type.INFO, "Creating new command context...");

        ctx = CommandContextFactory.getInstance().newCommandContext();
        this.ctx = ctx;

        logger.log(Type.INFO, "Command context created");
        logger.unbranch();
      } catch (CliInitializationException e) {
        logger.branch(TreeLogger.Type.ERROR, "Could not initialize JBoss AS command context", e);
        throw new UnableToCompleteException();
      }

      try {
        logger.branch(Type.INFO, "Connecting to JBoss AS...");

        ctx.handle("connect localhost:9999");

        logger.log(Type.INFO, "Connected to JBoss AS");
        logger.unbranch();
      } catch (CommandLineException e) {
        logger.branch(Type.ERROR, "Could not connect to AS", e);
        throw new UnableToCompleteException();
      }

      try {
        logger.branch(Type.INFO, String.format("Setting AS to listen for http requests on port %d...", port));

        ctx.handle(String.format(
                "/socket-binding-group=standard-sockets/socket-binding=http:write-attribute(name=port,value=%d)", port));
        ctx.handle(":reload");
        // Give the server time to reload
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          logger.log(Type.WARN, "Interrupted while waiting for JBoss AS to reload", e);
        }

        logger.log(Type.INFO, "Port change successful");
        logger.unbranch();
      } catch (CommandLineException e1) {
        logger.branch(Type.ERROR, String.format("Could not change the http port to %d", port), e1);
        throw new UnableToCompleteException();
      }

      try {
        /*
         * Need to add deployment resource to specify exploded archive
         *
         * path : the absolute path the deployment file/directory archive : true iff the an archived
         * file, false iff an exploded archive enabled : true iff war should be automatically
         * scanned and deployed
         */
        logger.branch(Type.INFO,
                String.format("Adding deployment %s at %s...", getAppName(), appRootDir.getAbsolutePath()));

        ctx.handle(String.format("/deployment=%s:add(content=[{\"path\"=>\"%s\",\"archive\"=>false}], enabled=false)",
                getAppName(), appRootDir.getAbsolutePath()));

        logger.log(Type.INFO, "Deployment resource added");
        logger.unbranch();
      } catch (CommandLineException e) {
        logger.branch(Type.ERROR, String.format("Could not add deployment %s", getAppName()), e);
        throw new UnableToCompleteException();
      }

      try {
        logger.branch(Type.INFO, String.format("Deploying %s...", getAppName()));

        ctx.handle(String.format("/deployment=%s:deploy", getAppName()));

        logger.log(Type.INFO, String.format("%s deployed", getAppName()));
        logger.unbranch();
      } catch (CommandLineException e) {
        logger.branch(Type.ERROR, String.format("Could not deploy %s", getAppName()), e);
View Full Code Here

    @Override
    public Map<String,JPanel> getTabs() {
        Map<String, JPanel> panelMap = new HashMap<String, JPanel>();

        final CommandContext cmdCtx;
        try {
            cmdCtx = CommandContextFactory.getInstance().newCommandContext();
            isConnected = connectCommandContext(cmdCtx);
            if (!isConnected) return panelMap;
        } catch (Exception e) {
View Full Code Here

    this.jbossProcess = jbossProcess;
    this.context = context;

    logger.branch(Type.INFO, "Starting container initialization...");

    CommandContext ctx = null;
    try {
      // Create command context
      try {
        logger.branch(Type.INFO, "Creating new command context...");

        ctx = CommandContextFactory.getInstance().newCommandContext();
        this.ctx = ctx;

        logger.log(Type.INFO, "Command context created");
        logger.unbranch();
      } catch (CliInitializationException e) {
        logger.branch(TreeLogger.Type.ERROR, "Could not initialize JBoss AS command context", e);
        throw new UnableToCompleteException();
      }

      attemptCommandContextConnection(9);

      // Change to given port
      try {
        logger.branch(Type.INFO, String.format("Setting AS to listen for http requests on port %d...", port));
        // Build operations (change port then restart)
        ModelNode[] operations = new ModelNode[] {
            Operations.createOperation(
                    ClientConstants.WRITE_ATTRIBUTE_OPERATION,
                    new ModelNode().add(ClientConstants.SOCKET_BINDING_GROUP, "standard-sockets").add(
                            ClientConstants.SOCKET_BINDING, "http")), Operations.createOperation("reload") };
        operations[0].get(ClientConstants.NAME).set("port");
        operations[0].get(ClientConstants.VALUE).set(port);

        for (final ModelNode operation : operations) {
          ModelNode result = ctx.getModelControllerClient().execute(operation);
          if (!Operations.isSuccessfulOutcome(result)) {
            logger.log(Type.ERROR, String.format("Could not switch ports:\nInput:\n%s\nOutput:\n%s",
                    operation.toJSONString(false), result.toJSONString(false)));
            throw new UnableToCompleteException();
          }
        }

        logger.branch(Type.INFO, "Port change successful. Waiting for AS to reload...");
        // Disconnect from server then attempt to reconnect (which should be unsuccessful until it has reloaded).
        ctx.disconnectController();
        attemptCommandContextConnection(4);
        logger.unbranch();

        logger.log(Type.INFO, "Port change successful");
        logger.unbranch();
      } catch (IOException e) {
        logger.branch(Type.ERROR, String.format("Could not change the http port to %d", port), e);
        throw new UnableToCompleteException();
      }

      try {
        /*
         * Need to add deployment resource to specify exploded archive
         *
         * path : the absolute path the deployment file/directory archive : true
         * iff the an archived file, false iff an exploded archive enabled :
         * true iff war should be automatically scanned and deployed
         */
        logger.branch(Type.INFO,
                String.format("Adding deployment %s at %s...", getAppName(), appRootDir.getAbsolutePath()));

        final ModelNode operation = getAddOperation(appRootDir.getAbsolutePath());
        final ModelNode result = ctx.getModelControllerClient().execute(operation);
        if (!Operations.isSuccessfulOutcome(result)) {
          logger.log(Type.ERROR, String.format("Could not add deployment:\nInput:\n%s\nOutput:\n%s",
                  operation.toJSONString(false), result.toJSONString(false)));
          throw new UnableToCompleteException();
        }
View Full Code Here

    @Override
    public Map<String,JPanel> getTabs() {
        Map<String, JPanel> panelMap = new HashMap<String, JPanel>();

        final CommandContext cmdCtx;
        try {
            cmdCtx = CommandContextFactory.getInstance().newCommandContext();
            isConnected = connectCommandContext(cmdCtx);
            if (!isConnected) return panelMap;
        } catch (Exception e) {
View Full Code Here

    @Override
    public CommandContext newCommandContext(String controllerHost,
            int controllerPort, String username, char[] password,
            boolean initConsole, final int connectionTimeout) throws CliInitializationException {
        final CommandContext ctx = new CommandContextImpl(controllerHost, controllerPort, username, password, initConsole, connectionTimeout);
        addShutdownHook(ctx);
        return ctx;
    }
View Full Code Here

    @Override
    public CommandContext newCommandContext(String controllerHost, int controllerPort,
            String username, char[] password,
            InputStream consoleInput, OutputStream consoleOutput) throws CliInitializationException {
        final CommandContext ctx = new CommandContextImpl(controllerHost, controllerPort, username, password, consoleInput, consoleOutput);
        addShutdownHook(ctx);
        return ctx;
    }
View Full Code Here

*/
public class CliLauncher {

    public static void main(String[] args) throws Exception {
        int exitCode = 0;
        CommandContext cmdCtx = null;
        boolean gui = false;
        try {
            String argError = null;
            List<String> commands = null;
            File file = null;
            boolean connect = false;
            String defaultControllerHost = null;
            int defaultControllerPort = -1;
            boolean version = false;
            String username = null;
            char[] password = null;
            int connectionTimeout = -1;

            for(String arg : args) {
                if(arg.startsWith("--controller=") || arg.startsWith("controller=")) {
                    final String value;
                    if(arg.startsWith("--")) {
                        value = arg.substring(13);
                    } else {
                        value = arg.substring(11);
                    }
                    String portStr = null;
                    int colonIndex = value.lastIndexOf(':');
                    if(colonIndex < 0) {
                        // default port
                        defaultControllerHost = value;
                    } else if(colonIndex == 0) {
                        // default host
                        portStr = value.substring(1);
                    } else {
                        final boolean hasPort;
                        int closeBracket = value.lastIndexOf(']');
                        if (closeBracket != -1) {
                            //possible ip v6
                            if (closeBracket > colonIndex) {
                                hasPort = false;
                            } else {
                                hasPort = true;
                            }
                        } else {
                            //probably ip v4
                            hasPort = true;
                        }
                        if (hasPort) {
                            defaultControllerHost = value.substring(0, colonIndex).trim();
                            portStr = value.substring(colonIndex + 1).trim();
                        } else {
                            defaultControllerHost = value;
                        }
                    }

                    if(portStr != null) {
                        int port = -1;
                        try {
                            port = Integer.parseInt(portStr);
                            if(port < 0) {
                                argError = "The port must be a valid non-negative integer: '" + args + "'";
                            } else {
                                defaultControllerPort = port;
                            }
                        } catch(NumberFormatException e) {
                            argError = "The port must be a valid non-negative integer: '" + arg + "'";
                        }
                    }
                } else if("--connect".equals(arg) || "-c".equals(arg)) {
                    connect = true;
                } else if("--version".equals(arg)) {
                    version = true;
                } else if ("--gui".equals(arg)) {
                    gui = true;
                } else if(arg.startsWith("--file=") || arg.startsWith("file=")) {
                    if(file != null) {
                        argError = "Duplicate argument '--file'.";
                        break;
                    }
                    if(commands != null) {
                        argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                        break;
                    }

                    final String fileName = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
                    if(!fileName.isEmpty()) {
                        file = new File(fileName);
                        if(!file.exists()) {
                            argError = "File " + file.getAbsolutePath() + " doesn't exist.";
                            break;
                        }
                    } else {
                        argError = "Argument '--file' is missing value.";
                        break;
                    }
                } else if(arg.startsWith("--commands=") || arg.startsWith("commands=")) {
                    if(file != null) {
                        argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                        break;
                    }
                    if(commands != null) {
                        argError = "Duplicate argument '--command'/'--commands'.";
                        break;
                    }
                    final String value = arg.startsWith("--") ? arg.substring(11) : arg.substring(9);
                    commands = Util.splitCommands(value);
                } else if(arg.startsWith("--command=") || arg.startsWith("command=")) {
                    if(file != null) {
                        argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time.";
                        break;
                    }
                    if(commands != null) {
                        argError = "Duplicate argument '--command'/'--commands'.";
                        break;
                    }
                    final String value = arg.startsWith("--") ? arg.substring(10) : arg.substring(8);
                    commands = Collections.singletonList(value);
                } else if (arg.startsWith("--user=")) {
                    username = arg.startsWith("--") ? arg.substring(7) : arg.substring(5);
                } else if (arg.startsWith("--password=")) {
                    password = (arg.startsWith("--") ? arg.substring(11) : arg.substring(9)).toCharArray();
                } else if (arg.startsWith("--timeout=")) {
                    if (connectionTimeout > 0) {
                        argError = "Duplicate argument '--timeout'";
                        break;
                    }
                    final String value = arg.substring(10);
                    try {
                        connectionTimeout = Integer.parseInt(value);
                    } catch (final NumberFormatException e) {
                        //
                    }
                    if (connectionTimeout <= 0) {
                        argError = "The timeout must be a valid positive integer: '" + value + "'";
                    }
                } else if (arg.equals("--help") || arg.equals("-h")) {
                    commands = Collections.singletonList("help");
                } else if (arg.startsWith("--properties=")) {
                    final String value  = arg.substring(13);
                    final File propertiesFile = new File(value);
                    if(!propertiesFile.exists()) {
                        argError = "File doesn't exist: " + propertiesFile.getAbsolutePath();
                        break;
                    }
                    final Properties props = new Properties();
                    FileInputStream fis = null;
                    try {
                        fis = new FileInputStream(propertiesFile);
                        props.load(fis);
                    } catch(FileNotFoundException e) {
                        argError = e.getLocalizedMessage();
                        break;
                    } catch(java.io.IOException e) {
                        argError = "Failed to load properties from " + propertiesFile.getAbsolutePath() + ": " + e.getLocalizedMessage();
                        break;
                    } finally {
                        if(fis != null) {
                            try {
                                fis.close();
                            } catch(java.io.IOException e) {
                            }
                        }
                    }
                    for(Object prop : props.keySet()) {
                        SecurityActions.setSystemProperty((String)prop, (String)props.get(prop));
                    }
                } else if(!(arg.startsWith("-D") || arg.equals("-XX:"))) {// skip system properties and jvm options
                    // assume it's commands
                    if(file != null) {
                        argError = "Only one of '--file', '--commands' or '--command' can appear as the argument at a time: " + arg;
                        break;
                    }
                    if(commands != null) {
                        argError = "Duplicate argument '--command'/'--commands'.";
                        break;
                    }
                    commands = Util.splitCommands(arg);
                }
            }

            if(argError != null) {
                System.err.println(argError);
                exitCode = 1;
                return;
            }

            if(version) {
                cmdCtx = initCommandContext(defaultControllerHost, defaultControllerPort, username, password, false, connect, connectionTimeout);
                VersionHandler.INSTANCE.handle(cmdCtx);
                return;
            }

            if(file != null) {
                cmdCtx = initCommandContext(defaultControllerHost, defaultControllerPort, username, password, false, connect, connectionTimeout);
                processFile(file, cmdCtx);
                return;
            }

            if(commands != null) {
                cmdCtx = initCommandContext(defaultControllerHost, defaultControllerPort, username, password, false, connect, connectionTimeout);
                processCommands(commands, cmdCtx);
                return;
            }

            if (gui) {
                cmdCtx = initCommandContext(defaultControllerHost, defaultControllerPort, username, password, false, true, connectionTimeout);
                processGui(cmdCtx);
                return;
            }

            // Interactive mode
            cmdCtx = initCommandContext(defaultControllerHost, defaultControllerPort, username, password, true, connect, connectionTimeout);
            cmdCtx.interact();
        } catch(Throwable t) {
            t.printStackTrace();
            exitCode = 1;
        } finally {
            if(cmdCtx != null && cmdCtx.getExitCode() != 0) {
                exitCode = cmdCtx.getExitCode();
            }
            if (!gui) {
                System.exit(exitCode);
            }
        }
View Full Code Here

TOP

Related Classes of org.jboss.as.cli.CommandContext

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.