Search in sources :

Example 1 with ParamModel

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

the class RemoteAdminCommand method executeCommand.

/**
 * Run the command using the specified arguments.
 * Return the output of the command.
 * @param opts
 * @return
 * @throws org.glassfish.api.admin.CommandException
 */
public String executeCommand(ParameterMap opts) throws CommandException {
    // first, make sure we have the command model
    getCommandModel();
    // XXX : This is to take care of camel case from ReST calls that
    // do not go through usual CLI path
    // XXX : This is not clean; this should be handled the same way
    // it is handled for incoming CLI commands
    options = new ParameterMap();
    for (Map.Entry<String, List<String>> o : opts.entrySet()) {
        String key = o.getKey();
        List<String> value = o.getValue();
        options.set(key.toLowerCase(Locale.ENGLISH), value);
    }
    // "DEFAULT".toLowerCase()
    operands = options.get("default");
    try {
        initializeDoUpload();
        // if uploading, we need a payload
        if (doUpload) {
            outboundPayload = PayloadImpl.Outbound.newInstance();
        }
        StringBuilder uriString = getCommandURI();
        ParamModel operandParam = null;
        for (ParamModel opt : commandModel.getParameters()) {
            if (opt.getParam().primary()) {
                operandParam = opt;
                continue;
            }
            String paramName = opt.getName();
            List<String> paramValues = new ArrayList<String>(options.get(paramName.toLowerCase(Locale.ENGLISH)));
            if (!opt.getParam().alias().isEmpty() && !paramName.equalsIgnoreCase(opt.getParam().alias())) {
                paramValues.addAll(options.get(opt.getParam().alias().toLowerCase(Locale.ENGLISH)));
            }
            if (!opt.getParam().multiple() && paramValues.size() > 1) {
                throw new CommandException(strings.get("tooManyOptions", paramName));
            }
            if (paramValues.isEmpty()) {
                // perhaps it's set in the environment?
                String envValue = getFromEnvironment(paramName);
                if (envValue != null) {
                    paramValues.add(envValue);
                }
            }
            if (paramValues.isEmpty()) {
                /*
                     * Option still not set.  Note that we ignore the default
                     * value and don't send it explicitly on the assumption
                     * that the server will supply the default value itself.
                     *
                     * If the missing option is required, that's an error,
                     * which should never happen here because validate()
                     * should check it first.
                     */
                if (!opt.getParam().optional()) {
                    throw new CommandException(strings.get("missingOption", paramName));
                }
                // optional param not set, skip it
                continue;
            }
            for (String paramValue : paramValues) {
                if (opt.getType() == File.class || opt.getType() == File[].class) {
                    addFileOption(uriString, paramName, paramValue);
                } else if (opt.getParam().password()) {
                    addPasswordOption(uriString, paramName, paramValue);
                } else {
                    addStringOption(uriString, paramName, paramValue);
                }
            }
        }
        // add operands
        for (String operand : operands) {
            if (operandParam.getType() == File.class || operandParam.getType() == File[].class) {
                addFileOption(uriString, "DEFAULT", operand);
            } else {
                addStringOption(uriString, "DEFAULT", operand);
            }
        }
        // remove the last character, whether it was "?" or "&"
        uriString.setLength(uriString.length() - 1);
        executeRemoteCommand(uriString.toString());
    } catch (IOException ioex) {
        // possibly an error caused while reading or writing a file?
        throw new CommandException("I/O Error", ioex);
    }
    return output;
}
Also used : ArrayList(java.util.ArrayList) ParamModel(org.glassfish.api.admin.CommandModel.ParamModel) ParameterMap(org.glassfish.api.admin.ParameterMap) List(java.util.List) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) InvalidCommandException(org.glassfish.api.admin.InvalidCommandException) CommandException(org.glassfish.api.admin.CommandException) IOException(java.io.IOException) Map(java.util.Map) ParameterMap(org.glassfish.api.admin.ParameterMap) NamedNodeMap(org.w3c.dom.NamedNodeMap) SmartFile(com.sun.enterprise.universal.io.SmartFile) File(java.io.File)

Example 2 with ParamModel

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

the class CLICommand method prevalidate.

/**
 * The prevalidate method supplies missing options from
 * the environment.  It also supplies passwords from the password
 * file or prompts for them if interactive.
 *
 * @throws CommandException if execution of the command fails
 * @throws CommandValidationException if there's something wrong
 *          with the options or arguments
 */
protected void prevalidate() throws CommandException {
    /*
         * First, check that the command has the proper scope.
         * (Could check this in getCommand(), but at that point we
         * don't have the CommandModel yet.)
         * Remote commands are checked on the server.
         */
    if (!(this instanceof RemoteCommand) && !(this instanceof RemoteCLICommand)) {
        Class<? extends Annotation> myScope = getScope(this.getClass());
        if (myScope == null) {
            throw new CommandException(strings.get("NoScope", name));
        } else if (Singleton.class.equals(myScope)) {
            // check that there are no parameters for this command
            if (commandModel.getParameters().size() > 0) {
                throw new CommandException(strings.get("HasParams", name));
            }
        }
    }
    /*
         * Check for missing options and operands.
         */
    Console cons = programOpts.isInteractive() ? System.console() : null;
    boolean missingOption = false;
    for (ParamModel opt : commandModel.getParameters()) {
        if (opt.getParam().password())
            // passwords are handled later
            continue;
        if (opt.getParam().obsolete() && getOption(opt.getName()) != null)
            logger.info(strings.get("ObsoleteOption", opt.getName()));
        if (opt.getParam().optional())
            continue;
        if (opt.getParam().primary())
            continue;
        // if option isn't set, prompt for it (if interactive)
        if (getOption(opt.getName()) == null && cons != null && !missingOption) {
            cons.printf("%s", strings.get("optionPrompt", lc(opt.getName())));
            String val = cons.readLine();
            if (ok(val))
                options.set(opt.getName(), val);
        }
        // if it's still not set, that's an error
        if (getOption(opt.getName()) == null) {
            missingOption = true;
            logger.info(strings.get("missingOption", "--" + opt.getName()));
        }
        if (// a required obsolete option?
        opt.getParam().obsolete())
            logger.info(strings.get("ObsoleteOption", opt.getName()));
    }
    if (missingOption)
        throw new CommandValidationException(strings.get("missingOptions", name));
    int operandMin = 0;
    int operandMax = 0;
    ParamModel operandParam = getOperandModel();
    if (operandParam != null) {
        operandMin = operandParam.getParam().optional() ? 0 : 1;
        operandMax = operandParam.getParam().multiple() ? Integer.MAX_VALUE : 1;
    }
    if (operands.size() < operandMin && cons != null) {
        cons.printf("%s", strings.get("operandPrompt", operandParam.getName()));
        String val = cons.readLine();
        if (ok(val)) {
            operands = new ArrayList<String>();
            operands.add(val);
        }
    }
    if (operands.size() < operandMin)
        throw new CommandValidationException(strings.get("notEnoughOperands", name, operandParam.getType()));
    if (operands.size() > operandMax) {
        if (operandMax == 0)
            throw new CommandValidationException(strings.get("noOperandsAllowed", name));
        else if (operandMax == 1)
            throw new CommandValidationException(strings.get("tooManyOperands1", name));
        else
            throw new CommandValidationException(strings.get("tooManyOperands", name, operandMax));
    }
    initializeCommandPassword();
}
Also used : Singleton(javax.inject.Singleton) RemoteCommand(com.sun.enterprise.admin.cli.remote.RemoteCommand) ParamModel(org.glassfish.api.admin.CommandModel.ParamModel) RemoteCLICommand(com.sun.enterprise.admin.cli.remote.RemoteCLICommand)

Example 3 with ParamModel

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

the class CLICommand method initializeCommandPassword.

/**
 * Initialize all the passwords required by the command.
 *
 * @throws CommandException
 */
private void initializeCommandPassword() throws CommandException {
    /*
         * Go through all the valid options and check for required password
         * options that weren't specified in the password file.  If option
         * is missing and we're interactive, prompt for it.  Store the
         * password as if it was a parameter.
         */
    for (ParamModel opt : commandModel.getParameters()) {
        if (!opt.getParam().password())
            continue;
        String pwdname = opt.getName();
        char[] pwd = getPassword(opt, null, true);
        if (pwd == null) {
            if (opt.getParam().optional())
                // not required, skip it
                continue;
            // if not terse, provide more advice about what to do
            String msg;
            if (programOpts.isTerse())
                msg = strings.get("missingPassword", name, passwordName(opt));
            else
                msg = strings.get("missingPasswordAdvice", name, passwordName(opt));
            throw new CommandValidationException(msg);
        }
        options.set(pwdname, new String(pwd));
    }
}
Also used : ParamModel(org.glassfish.api.admin.CommandModel.ParamModel)

Example 4 with ParamModel

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

the class CLICommand method generateUsageText.

private String generateUsageText() {
    StringBuilder usageText = new StringBuilder();
    usageText.append(strings.get("Usage", strings.get("Usage.brief", programOpts.getCommandName())));
    usageText.append(" ");
    usageText.append(getName());
    int len = usageText.length();
    StringBuilder optText = new StringBuilder();
    String lsep = System.getProperty("line.separator");
    for (ParamModel opt : usageOptions()) {
        optText.setLength(0);
        final String optName = lc(opt.getName());
        // "--terse" is part of asadmin utility options
        if (optName.equals("terse"))
            continue;
        // skip "hidden" options
        if (optName.startsWith("_"))
            continue;
        // do not want to display password as an option
        if (opt.getParam().password())
            continue;
        // also do not want to display obsolete options
        if (opt.getParam().obsolete())
            continue;
        // primary parameter is the operand, not an option
        if (opt.getParam().primary())
            continue;
        boolean optional = opt.getParam().optional();
        String defValue = opt.getParam().defaultValue();
        if (optional)
            optText.append("[");
        String sn = opt.getParam().shortName();
        if (ok(sn))
            optText.append('-').append(sn).append('|');
        optText.append("--").append(optName);
        if (opt.getType() == Boolean.class || opt.getType() == boolean.class) {
            // canonicalize default value
            if (ok(defValue) && Boolean.parseBoolean(defValue))
                defValue = "true";
            else
                defValue = "false";
            optText.append("[=<").append(optName);
            optText.append(strings.get("Usage.default", defValue));
            optText.append(">]");
        } else {
            // STRING or FILE
            if (ok(defValue)) {
                optText.append(" <").append(optName);
                optText.append(strings.get("Usage.default", defValue));
                optText.append('>');
            } else
                optText.append(" <").append(optName).append('>');
        }
        if (optional)
            optText.append("]");
        if (len + 1 + optText.length() > 80) {
            usageText.append(lsep).append('\t');
            len = 8;
        } else {
            usageText.append(' ');
            len++;
        }
        usageText.append(optText);
        len += optText.length();
    }
    // add --help text
    String helpText = "[-?|--help[=<help(default:false)>]]";
    if (len + 1 + helpText.length() > 80) {
        usageText.append(lsep).append('\t');
        len = 8;
    } else {
        usageText.append(' ');
        len++;
    }
    usageText.append(helpText);
    len += helpText.length();
    optText.setLength(0);
    ParamModel operandParam = getOperandModel();
    String opname = operandParam != null ? lc(operandParam.getName()) : null;
    if (!ok(opname))
        opname = "operand";
    int operandMin = 0;
    int operandMax = 0;
    if (operandParam != null) {
        operandMin = operandParam.getParam().optional() ? 0 : 1;
        operandMax = operandParam.getParam().multiple() ? Integer.MAX_VALUE : 1;
    }
    if (operandMax > 0) {
        if (operandMin == 0) {
            optText.append("[").append(opname);
            if (operandMax > 1)
                optText.append(" ...");
            optText.append("]");
        } else {
            optText.append(opname);
            if (operandMax > 1)
                optText.append(" ...");
        }
    }
    if (len + 1 + optText.length() > 80) {
        usageText.append(lsep).append('\t');
        len = 8;
    } else {
        usageText.append(' ');
        len++;
    }
    usageText.append(optText);
    return usageText.toString();
}
Also used : ParamModel(org.glassfish.api.admin.CommandModel.ParamModel)

Example 5 with ParamModel

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

the class Parser method parseCommandLine.

/**
 * Parse the command line arguments according to CLIP.
 *
 * @param argv  command line arguments
 * @throws CommandValidationException if command line is invalid
 */
private void parseCommandLine(final String[] argv, final int start) throws CommandValidationException {
    for (int si = start; si < argv.length; si++) {
        String arg = argv[si];
        if (arg.equals("--")) {
            // when we process all remaining options
            if (!ignoreUnknown)
                si++;
            while (si < argv.length) operands.add(argv[si++]);
            break;
        }
        // is it an operand or option value?
        if (!arg.startsWith("-") || arg.length() <= 1) {
            operands.add(arg);
            if (ignoreUnknown)
                continue;
            si++;
            while (si < argv.length) operands.add(argv[si++]);
            break;
        }
        // at this point it's got to be an option of some sort
        ParamModel opt = null;
        String name = null;
        String value = null;
        if (arg.charAt(1) == '-') {
            // long option
            int ns = 2;
            boolean sawno = false;
            if (arg.startsWith("--no-")) {
                sawno = true;
                value = "false";
                // skip prefix
                ns = 5;
            }
            // if of the form "--option=value", extract value
            int ne = arg.indexOf('=');
            if (ne < 0)
                name = arg.substring(ns);
            else {
                if (value != null)
                    throw new CommandValidationException(strings.get("parser.noValueAllowed", arg));
                name = arg.substring(ns, ne);
                value = arg.substring(ne + 1);
            }
            opt = lookupLongOption(name);
            if (sawno && optionRequiresOperand(opt))
                throw new CommandValidationException(strings.get("parser.illegalNo", opt.getName()));
        } else {
            /*
                 * possibilities are:
                 *      -f
                 *      -f value
                 *      -f=value
                 *      -fxyz   (multiple single letter boolean options
                 *              with no arguments)
                 */
            if (arg.length() <= 2) {
                // one of the first two cases
                opt = lookupShortOption(arg.charAt(1));
                name = arg.substring(1);
            } else {
                // one of the last two cases
                if (arg.charAt(2) == '=') {
                    // -f=value case
                    opt = lookupShortOption(arg.charAt(1));
                    value = arg.substring(3);
                } else {
                    // -fxyz case
                    for (int i = 1; i < arg.length(); i++) {
                        opt = lookupShortOption(arg.charAt(i));
                        if (opt == null) {
                            if (!ignoreUnknown)
                                throw new CommandValidationException(strings.get("parser.invalidOption", Character.toString(arg.charAt(i))));
                            // unknown option, skip all the rest
                            operands.add(arg);
                            break;
                        }
                        if (opt.getType() == Boolean.class || opt.getType() == boolean.class)
                            setOption(opt, "true");
                        else {
                            if (!ignoreUnknown)
                                throw new CommandValidationException(strings.get("parser.nonbooleanNotAllowed", Character.toString(arg.charAt(i)), arg));
                            // unknown option, skip all the rest
                            operands.add(arg);
                            break;
                        }
                    }
                    continue;
                }
            }
        }
        // is it a known option?
        if (opt == null) {
            if (!ignoreUnknown)
                throw new CommandValidationException(strings.get("parser.invalidOption", arg));
            // unknown option, skip it
            operands.add(arg);
            continue;
        }
        // find option value, if needed
        if (value == null) {
            // as an option as long as it doesn't look like an option
            if (options == null) {
                if (si + 1 < argv.length && !argv[si + 1].startsWith("-"))
                    value = argv[++si];
                else
                    // fake it
                    ((ParamModelData) opt).type = Boolean.class;
            } else if (optionRequiresOperand(opt)) {
                if (++si >= argv.length)
                    throw new CommandValidationException(strings.get("parser.missingValue", name));
                value = argv[si];
            } else if (opt.getType() == Boolean.class || opt.getType() == boolean.class) {
                /*
                     * If it's a boolean option, the following parameter
                     * might be the value for the option; peek ahead to
                     * see if it looks like a boolean value.
                     */
                if (si + 1 < argv.length) {
                    String val = argv[si + 1];
                    if (val.equalsIgnoreCase("true") || val.equalsIgnoreCase("false")) {
                        // yup, it's a boolean value, consume it
                        si++;
                        value = val;
                    }
                }
            }
        }
        setOption(opt, value);
    }
}
Also used : ParamModel(org.glassfish.api.admin.CommandModel.ParamModel) ParamModelData(com.sun.enterprise.admin.util.CommandModelData.ParamModelData)

Aggregations

ParamModel (org.glassfish.api.admin.CommandModel.ParamModel)15 SmartFile (com.sun.enterprise.universal.io.SmartFile)4 ParamModelData (com.sun.enterprise.admin.util.CommandModelData.ParamModelData)3 File (java.io.File)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Map (java.util.Map)2 CommandException (org.glassfish.api.admin.CommandException)2 InvalidCommandException (org.glassfish.api.admin.InvalidCommandException)2 ParameterMap (org.glassfish.api.admin.ParameterMap)2 NamedNodeMap (org.w3c.dom.NamedNodeMap)2 NodeList (org.w3c.dom.NodeList)2 RemoteCLICommand (com.sun.enterprise.admin.cli.remote.RemoteCLICommand)1 RemoteCommand (com.sun.enterprise.admin.cli.remote.RemoteCommand)1 IOException (java.io.IOException)1 LinkedHashSet (java.util.LinkedHashSet)1 Singleton (javax.inject.Singleton)1 Param (org.glassfish.api.Param)1