Search in sources :

Example 36 with CommandException

use of org.glassfish.api.admin.CommandException in project Payara by payara.

the class LocalOSGiShellCommand method executeCommands.

/**
 * Read commands from the specified BufferedReader
 * and execute them.  If printPrompt is set, prompt first.
 *
 * @return the exit code of the last command executed
 */
private int executeCommands(ConsoleReader reader) throws CommandException, CommandValidationException, IOException {
    String line = null;
    int rc = 0;
    /*
         * Any program options we start with are copied to the environment
         * to serve as defaults for commands we run, and then we give each
         * command an empty program options.
         */
    programOpts.toEnvironment(env);
    String sessionId = startSession();
    try {
        for (; ; ) {
            if (printPrompt) {
                line = reader.readLine(shellType + "$ ");
            } else {
                line = reader.readLine();
            }
            if (line == null) {
                if (printPrompt) {
                    System.out.println();
                }
                break;
            }
            if (// ignore comment lines
            line.trim().startsWith("#")) {
                continue;
            }
            String[] args = null;
            try {
                args = getArgs(line);
            } catch (ArgumentTokenizer.ArgumentException ex) {
                logger.info(ex.getMessage());
                continue;
            }
            if (args.length == 0) {
                continue;
            }
            String command = args[0];
            if (command.trim().length() == 0) {
                continue;
            }
            // XXX - care about their arguments?
            if (command.equals("exit") || command.equals("quit")) {
                break;
            }
            ProgramOptions po = null;
            try {
                /*
                     * Every command gets its own copy of program options
                     * so that any program options specified in its
                     * command line options don't effect other commands.
                     * But all commands share the same environment.
                     */
                po = new ProgramOptions(env);
                // copy over AsadminMain info
                po.setClassPath(programOpts.getClassPath());
                po.setClassName(programOpts.getClassName());
                // remove the old one and replace it
                atomicReplace(locator, po);
                args = prepareArguments(sessionId, args);
                args = enhanceForTarget(args);
                String output = cmd.executeAndReturnOutput(args).trim();
                if (output != null && output.length() > 0) {
                    logger.info(output);
                }
            } catch (CommandValidationException cve) {
                logger.severe(cve.getMessage());
                logger.severe(cmd.getUsage());
                rc = ERROR;
            } catch (InvalidCommandException ice) {
                // find closest match with local or remote commands
                logger.severe(ice.getMessage());
            } catch (CommandException ce) {
                logger.severe(ce.getMessage());
                rc = ERROR;
            } finally {
                // restore the original program options
                // XXX - is this necessary?
                atomicReplace(locator, programOpts);
            }
            CLIUtil.writeCommandToDebugLog(name, env, args, rc);
        }
    } finally {
        // what if something breaks on the wire?
        rc = stopSession(sessionId);
    }
    return rc;
}
Also used : InvalidCommandException(org.glassfish.api.admin.InvalidCommandException) CommandValidationException(org.glassfish.api.admin.CommandValidationException) ArgumentTokenizer(com.sun.enterprise.admin.cli.ArgumentTokenizer) InvalidCommandException(org.glassfish.api.admin.InvalidCommandException) CommandException(org.glassfish.api.admin.CommandException) ProgramOptions(com.sun.enterprise.admin.cli.ProgramOptions)

Example 37 with CommandException

use of org.glassfish.api.admin.CommandException in project Payara by payara.

the class OSGiShellCommand method execute.

@Override
public void execute(AdminCommandContext context) {
    ActionReport report = context.getActionReport();
    if (instance != null) {
        Server svr = domain.getServerNamed(instance);
        if (svr == null) {
            report.setMessage("No server target found for " + instance);
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
        String host = svr.getAdminHost();
        int port = svr.getAdminPort();
        try {
            ServerRemoteAdminCommand remote = new ServerRemoteAdminCommand(locator, "osgi", host, port, false, "admin", "", log);
            ParameterMap params = new ParameterMap();
            if (commandLine == null) {
                params.set("DEFAULT".toLowerCase(Locale.US), "asadmin-osgi-shell");
            } else if (commandLine instanceof String) {
                params.set("DEFAULT".toLowerCase(Locale.US), (String) commandLine);
            } else if (commandLine instanceof List) {
                params.set("DEFAULT".toLowerCase(Locale.US), (List<String>) commandLine);
            }
            if (sessionOp != null) {
                params.set("session", sessionOp);
            }
            if (sessionId != null) {
                params.set("session-id", sessionId);
            }
            report.setMessage(remote.executeCommand(params));
            report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
            return;
        } catch (CommandException x) {
            report.setMessage("Remote execution failed: " + x.getMessage());
            report.setFailureCause(x);
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
    }
    String cmdName = "";
    String cmd = "";
    if (commandLine == null) {
        cmd = "asadmin-osgi-shell";
        cmdName = cmd;
    } else if (commandLine instanceof String) {
        cmd = (String) commandLine;
        cmdName = cmd;
    } else if (commandLine instanceof List) {
        for (Object arg : (List) commandLine) {
            if (cmd.length() == 0) {
                // first arg
                cmd = (String) arg;
                cmdName = cmd;
            } else {
                cmd += " " + (String) arg;
            }
        }
    } else if (commandLine instanceof String[]) {
        for (Object arg : (String[]) commandLine) {
            if (cmd.length() == 0) {
                // first arg
                cmd = (String) arg;
                cmdName = cmd;
            } else {
                cmd += " " + (String) arg;
            }
        }
    } else {
        // shouldn't happen...
        report.setMessage("Unable to deal with argument list of type " + commandLine.getClass().getName());
        report.setActionExitCode(ActionReport.ExitCode.WARNING);
        return;
    }
    // standard output...
    ByteArrayOutputStream bOut = new ByteArrayOutputStream(512);
    PrintStream out = new PrintStream(bOut);
    // error output...
    ByteArrayOutputStream bErr = new ByteArrayOutputStream(512);
    PrintStream err = new PrintStream(bErr);
    try {
        Object shell = null;
        ServiceReference sref = ctx.getServiceReference("org.apache.felix.service.command.CommandProcessor");
        if (sref != null) {
            shell = ctx.getService(sref);
        }
        if (shell == null) {
            // try with felix...
            sref = ctx.getServiceReference("org.apache.felix.shell.ShellService");
            if (sref != null) {
                shell = ctx.getService(sref);
            }
            if (shell == null) {
                report.setMessage("No Shell Service available");
                report.setActionExitCode(ActionReport.ExitCode.WARNING);
                return;
            } else if ("asadmin-osgi-shell".equals(cmdName)) {
                out.println("felix");
            } else {
                ShellService s = (ShellService) shell;
                s.executeCommand(cmd, out, err);
            }
        } else {
            // try with gogo...
            // GLASSFISH-19126 - prepare fake input stream...
            InputStream in = new InputStream() {

                @Override
                public int read() throws IOException {
                    return -1;
                }

                @Override
                public int available() throws IOException {
                    return 0;
                }

                @Override
                public int read(byte[] b) throws IOException {
                    return -1;
                }

                @Override
                public int read(byte[] b, int off, int len) throws IOException {
                    return -1;
                }
            };
            CommandProcessor cp = (CommandProcessor) shell;
            if (sessionOp == null) {
                if ("asadmin-osgi-shell".equals(cmdName)) {
                    out.println("gogo");
                } else {
                    CommandSession session = cp.createSession(in, out, err);
                    session.execute(cmd);
                    session.close();
                }
            } else if ("new".equals(sessionOp)) {
                CommandSession session = cp.createSession(null, null, null);
                RemoteCommandSession remote = new RemoteCommandSession(session);
                log.log(Level.FINE, "Remote session established: {0}", remote.getId());
                sessions.put(remote.getId(), remote);
                out.println(remote.getId());
            } else if ("list".equals(sessionOp)) {
                for (String id : sessions.keySet()) {
                    out.println(id);
                }
            } else if ("execute".equals(sessionOp)) {
                RemoteCommandSession remote = sessions.get(sessionId);
                CommandSession session = remote.attach(in, out, err);
                session.execute(cmd);
                remote.detach();
            } else if ("stop".equals(sessionOp)) {
                RemoteCommandSession remote = sessions.remove(sessionId);
                CommandSession session = remote.attach(in, out, err);
                session.close();
                log.log(Level.FINE, "Remote session closed: {0}", remote.getId());
            }
        }
        out.flush();
        err.flush();
        String output = bOut.toString("UTF-8");
        String errors = bErr.toString("UTF-8");
        report.setMessage(output);
        if (errors.length() > 0) {
            report.setMessage(errors);
            report.setActionExitCode(ActionReport.ExitCode.WARNING);
        } else {
            report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
        }
    } catch (Exception ex) {
        report.setMessage(ex.getMessage());
        report.setActionExitCode(ActionReport.ExitCode.WARNING);
    }
}
Also used : PrintStream(java.io.PrintStream) Server(com.sun.enterprise.config.serverbeans.Server) InputStream(java.io.InputStream) ServerRemoteAdminCommand(com.sun.enterprise.admin.remote.ServerRemoteAdminCommand) ParameterMap(org.glassfish.api.admin.ParameterMap) CommandException(org.glassfish.api.admin.CommandException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ActionReport(org.glassfish.api.ActionReport) RestEndpoint(org.glassfish.api.admin.RestEndpoint) CommandException(org.glassfish.api.admin.CommandException) IOException(java.io.IOException) ServiceReference(org.osgi.framework.ServiceReference) ShellService(org.apache.felix.shell.ShellService) CommandSession(org.apache.felix.service.command.CommandSession) CommandProcessor(org.apache.felix.service.command.CommandProcessor) List(java.util.List)

Example 38 with CommandException

use of org.glassfish.api.admin.CommandException in project Payara by payara.

the class AdminMain method readAndMergeOptionsFromAuxInput.

private static void readAndMergeOptionsFromAuxInput(final ProgramOptions progOpts) throws CommandException {
    final String auxInput = progOpts.getAuxInput();
    if (auxInput == null || auxInput.length() == 0) {
        return;
    }
    final ParameterMap newParamMap = new ParameterMap();
    /*
         * We will place the options passed via the aux. input on the command
         * line and we do not want to repeat the read from stdin again, so
         * remove the aux input setting.
         */
    progOpts.setAuxInput(null);
    try {
        final AsadminInput.InputReader reader = AsadminInput.reader(auxInput);
        final Properties newOptions = reader.settings().get("option");
        for (String propName : newOptions.stringPropertyNames()) {
            newParamMap.add(propName, newOptions.getProperty(propName));
        }
        progOpts.updateOptions(newParamMap);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
Also used : ParameterMap(org.glassfish.api.admin.ParameterMap) Properties(java.util.Properties) InvalidCommandException(org.glassfish.api.admin.InvalidCommandException) CommandException(org.glassfish.api.admin.CommandException) IOException(java.io.IOException) CommandValidationException(org.glassfish.api.admin.CommandValidationException) AsadminInput(org.glassfish.common.util.admin.AsadminInput)

Example 39 with CommandException

use of org.glassfish.api.admin.CommandException in project Payara by payara.

the class AdminMain method executeCommand.

public int executeCommand(String[] argv) {
    CLICommand cmd = null;
    try {
        // if the first argument is an option, we're using the new form
        if (argv.length > 0 && argv[0].startsWith("-")) {
            /*
                 * Parse all the admin options, stopping at the first
                 * non-option, which is the command name.
                 */
            Parser rcp = new Parser(argv, 0, ProgramOptions.getValidOptions(), false);
            ParameterMap params = rcp.getOptions();
            po = new ProgramOptions(params, env);
            readAndMergeOptionsFromAuxInput(po);
            List<String> operands = rcp.getOperands();
            argv = operands.toArray(new String[operands.size()]);
        } else {
            po = new ProgramOptions(env);
        }
        po.toEnvironment(env);
        po.setClassPath(classPath);
        po.setClassName(className);
        po.setCommandName(getCommandName());
        if (argv.length == 0) {
            if (po.isHelp()) {
                argv = new String[] { "help" };
            } else {
                argv = new String[] { "multimode" };
            }
        }
        command = argv[0];
        cliContainer.setEnvironment(env);
        cliContainer.setProgramOptions(po);
        cmd = CLICommand.getCommand(cliContainer, command);
        int result = cmd.execute(argv);
        return result;
    } catch (CommandValidationException cve) {
        logger.severe(cve.getMessage());
        if (// error parsing program options
        cmd == null) {
            printUsage();
        } else {
            logger.severe(cmd.getUsage());
        }
        return ERROR;
    } catch (InvalidCommandException ice) {
        // find closest match with local or remote commands
        logger.severe(ice.getMessage());
        try {
            po.setEcho(false);
            CLIUtil.displayClosestMatch(command, CLIUtil.getAllCommands(cliContainer, po, env), strings.get("ClosestMatchedLocalAndRemoteCommands"), logger);
        } catch (InvalidCommandException e) {
        // not a big deal if we cannot help
        }
        return ERROR;
    } catch (CommandException ce) {
        if (ce.getCause() instanceof java.net.ConnectException) {
            // find closest match with local commands
            logger.severe(ce.getMessage());
            try {
                CLIUtil.displayClosestMatch(command, CLIUtil.getLocalCommands(cliContainer), strings.get("ClosestMatchedLocalCommands"), logger);
            } catch (InvalidCommandException e) {
                logger.info(strings.get("InvalidRemoteCommand", command));
            }
        } else {
            logger.severe(ce.getMessage());
        }
        return ERROR;
    }
}
Also used : InvalidCommandException(org.glassfish.api.admin.InvalidCommandException) CommandValidationException(org.glassfish.api.admin.CommandValidationException) ParameterMap(org.glassfish.api.admin.ParameterMap) InvalidCommandException(org.glassfish.api.admin.InvalidCommandException) CommandException(org.glassfish.api.admin.CommandException)

Example 40 with CommandException

use of org.glassfish.api.admin.CommandException in project Payara by payara.

the class DeployerImpl method deploy.

@Override
public String deploy(File file, String... params) throws GlassFishException {
    String[] newParams = new String[params.length + 1];
    System.arraycopy(params, 0, newParams, 0, params.length);
    newParams[params.length] = file.getAbsolutePath();
    CommandExecutorImpl executer = habitat.getService(CommandExecutorImpl.class);
    try {
        String command = "deploy";
        ActionReport actionReport = executer.createActionReport();
        ParameterMap commandParams = executer.getParameters(command, newParams);
        org.glassfish.api.admin.CommandRunner.CommandInvocation inv = executer.getCommandRunner().getCommandInvocation(command, actionReport, kernelIdentity.getSubject());
        inv.parameters(commandParams);
        // set outputbound payload if --retrieve option is specified.
        Payload.Outbound outboundPayload = null;
        String retrieveOpt = commandParams.getOne("retrieve");
        File retrieve = retrieveOpt != null ? new File(retrieveOpt) : null;
        if (retrieve != null && retrieve.exists()) {
            outboundPayload = PayloadImpl.Outbound.newInstance();
            inv.outbound(outboundPayload);
        }
        inv.execute();
        // extract the outbound payload.
        if (outboundPayload != null) {
            extractPayload(outboundPayload, actionReport, retrieve);
        }
        return actionReport.getResultType(String.class);
    } catch (CommandException e) {
        throw new GlassFishException(e);
    }
}
Also used : GlassFishException(org.glassfish.embeddable.GlassFishException) ParameterMap(org.glassfish.api.admin.ParameterMap) CommandException(org.glassfish.api.admin.CommandException) ActionReport(org.glassfish.api.ActionReport) Payload(org.glassfish.api.admin.Payload) File(java.io.File)

Aggregations

CommandException (org.glassfish.api.admin.CommandException)61 File (java.io.File)20 CommandValidationException (org.glassfish.api.admin.CommandValidationException)16 IOException (java.io.IOException)13 ParameterMap (org.glassfish.api.admin.ParameterMap)11 InvalidCommandException (org.glassfish.api.admin.InvalidCommandException)10 ActionReport (org.glassfish.api.ActionReport)9 ArrayList (java.util.ArrayList)6 RemoteCLICommand (com.sun.enterprise.admin.cli.remote.RemoteCLICommand)5 MiniXmlParserException (com.sun.enterprise.universal.xml.MiniXmlParserException)5 HostAndPort (com.sun.enterprise.util.HostAndPort)4 BackupException (com.sun.enterprise.backup.BackupException)3 BackupWarningException (com.sun.enterprise.backup.BackupWarningException)3 SmartFile (com.sun.enterprise.universal.io.SmartFile)3 FileNotFoundException (java.io.FileNotFoundException)3 UnknownHostException (java.net.UnknownHostException)3 Logger (java.util.logging.Logger)3 SFTPClient (org.glassfish.cluster.ssh.sftp.SFTPClient)3 CLIProcessExecutor (com.sun.enterprise.admin.cli.CLIProcessExecutor)2 PEDomainsManager (com.sun.enterprise.admin.servermgmt.pe.PEDomainsManager)2