Parse the output of the Redis COMMAND/COMMAND INFO command and convert to a list of {@link CommandDetail}.

@param commandOutput the command output, must not be {@literal null}
@return RedisInstance
494973
public static List<CommandDetail> parse(List<?> commandOutput) {
        LettuceAssert.notNull(commandOutput, "CommandOutput must not be null");

        List<CommandDetail> result = new ArrayList<>();

        for (Object o : commandOutput) {
            if (!(o instanceof Collection<?>)) {
                continue;
            }

            Collection<?> collection = (Collection<?>) o;
            if (collection.size() != COMMAND_INFO_SIZE) {
                continue;
            }

            CommandDetail commandDetail = parseCommandDetail(collection);
            result.add(commandDetail);
        }

        return Collections.unmodifiableList(result);
    }
702556
private OperationResult sequenceCommand(long index, long sequence, RaftSession session) {
    OperationResult result = session.getResult(sequence);
    if (result == null) {
      log.debug("Missing command result at index {}", index);
    }
    return result;
  }
365329
private static List<RedisCommand<?, ?, ?>> drainCommands(Queue<? extends RedisCommand<?, ?, ?>> source) {

        List<RedisCommand<?, ?, ?>> target = new ArrayList<>(source.size());

        RedisCommand<?, ?, ?> cmd;
        while ((cmd = source.poll()) != null) {

            if (!cmd.isDone()) {
                target.add(cmd);
            }
        }

        return target;
    }
492615
public Response doExecute(String name, ExecutionRequest executionRequest, CommandCompletePostProcessor postProcessor, UserDetails userDetails, RestUIContext uiContext) throws Exception {
        try (RestUIContext context = uiContext) {
            UICommand command = getCommandByName(context, name);
            if (command == null) {
                return Response.status(Status.NOT_FOUND).build();
            }
            List<Map<String, Object>> inputList = executionRequest.getInputList();

            // lets ensure a valid targetLocation for new projects
            if (Objects.equal(PROJECT_NEW_COMMAND, name)) {
                if (inputList.size() > 0) {
                    Map<String, Object> map = inputList.get(0);
                    map.put(TARGET_LOCATION_PROPERTY, projectFileSystem.getUserProjectFolderLocation(userDetails));
                }
            }
            CommandController controller = createController(context, command);
            configureAttributeMaps(userDetails, controller, executionRequest);
            ExecutionResult answer = null;
            if (controller instanceof WizardCommandController) {
                WizardCommandController wizardCommandController = (WizardCommandController) controller;
                List<WizardCommandController> controllers = new ArrayList<>();
                List<CommandInputDTO> stepPropertiesList = new ArrayList<>();
                List<ExecutionResult> stepResultList = new ArrayList<>();
                List<ValidationResult> stepValidationList = new ArrayList<>();
                controllers.add(wizardCommandController);
                WizardCommandController lastController = wizardCommandController;
                Result lastResult = null;
                int page = executionRequest.wizardStep();
                int nextPage = page + 1;
                boolean canMoveToNextStep = false;
                for (Map<String, Object> inputs : inputList) {
                    UICommands.populateController(inputs, lastController, getConverterFactory());
                    List<UIMessage> messages = lastController.validate();
                    ValidationResult stepValidation = UICommands.createValidationResult(context, lastController, messages);
                    stepValidationList.add(stepValidation);
                    if (!stepValidation.isValid()) {
                        break;
                    }
                    canMoveToNextStep = lastController.canMoveToNextStep();
                    boolean valid = lastController.isValid();
                    if (!canMoveToNextStep) {
                        if (lastController.canExecute()) {
                            // lets assume we can execute now
                            LOG.info("About to invoked command " + name + " stepValidation: " + stepValidation + " messages: " + messages + " with " + executionRequest);
                            lastResult = lastController.execute();
                            LOG.debug("Invoked command " + name + " with " + executionRequest + " result: " + lastResult);
                            ExecutionResult stepResults = UICommands.createExecutionResult(context, lastResult, false);
                            stepResultList.add(stepResults);
                            break;
                        } else {
                            stepValidation.addValidationError("Forge command failed with an internal error");
                            LOG.warn("Cannot move to next step as canExecute() returns false but the validation seems to be fine!");
                            break;
                        }
                    } else if (!valid) {
                        stepValidation.addValidationError("Forge command is not valid but didn't report any validation errors!");
                        LOG.warn("Cannot move to next step as invalid despite the validation saying otherwise");
                        break;
                    }
                    WizardCommandController nextController = lastController.next();
                    if (nextController != null) {
                        if (nextController == lastController) {
                            LOG.warn("No idea whats going on ;)");
                            break;
                        }
                        lastController = nextController;
                        lastController.initialize();
                        controllers.add(lastController);
                        CommandInputDTO stepDto = UICommands.createCommandInputDTO(context, command, lastController);
                        stepPropertiesList.add(stepDto);
                    } else {
                        int i = 0;
                        for (WizardCommandController stepController : controllers) {
                            Map<String, Object> stepControllerInputs = inputList.get(i++);
                            UICommands.populateController(stepControllerInputs, stepController, getConverterFactory());
                            lastResult = stepController.execute();
                            LOG.debug("Invoked command " + name + " with " + executionRequest + " result: " + lastResult);
                            ExecutionResult stepResults = UICommands.createExecutionResult(context, lastResult, false);
                            stepResultList.add(stepResults);
                        }
                        break;
                    }
                }
                answer = UICommands.createExecutionResult(context, lastResult, canMoveToNextStep);
                WizardResultsDTO wizardResultsDTO = new WizardResultsDTO(stepPropertiesList, stepValidationList, stepResultList);
                answer.setWizardResults(wizardResultsDTO);
            } else {
                Map<String, Object> inputs = inputList.get(0);
                UICommands.populateController(inputs, controller, getConverterFactory());
                Result result = controller.execute();
                LOG.debug("Invoked command " + name + " with " + executionRequest + " result: " + result);
                answer = UICommands.createExecutionResult(context, result, false);
            }
            if (answer.isCommandCompleted() && postProcessor != null) {
                postProcessor.firePostCompleteActions(name, executionRequest, context, controller, answer, request);
            }
            context.setCommitMessage(ExecutionRequest.createCommitMessage(name, executionRequest));
            return Response.ok(answer).build();
        }
    }
164419
@Override
    public Set<URI> listOutputs(URI operationUri) {
        if (operationUri == null) {
            return ImmutableSet.of();
        }

        return ImmutableSet.copyOf(this.opOutputMap.get(operationUri));
    }
249012
public int runCommandLine() throws IOException, InterruptedException
    {
        logRunnerConfiguration();
        
        ProcessBuilder processBuilder = new ProcessBuilder( getCommandLineArguments() );
        processBuilder.directory( workingDirectory );
        processBuilder.environment().putAll( environmentVars );
        Process commandLineProc = processBuilder.start();

        final StreamPumper stdoutPumper = new StreamPumper( commandLineProc.getInputStream(), outputConsumer );
        final StreamPumper stderrPumper = new StreamPumper( commandLineProc.getErrorStream(), errorConsumer );
        stdoutPumper.start();
        stderrPumper.start();
        
        if ( standardInputString != null )
        {
            OutputStream outputStream = commandLineProc.getOutputStream();
            outputStream.write( standardInputString.getBytes() );
            outputStream.close();
        }

        int exitCode = commandLineProc.waitFor();
        stdoutPumper.waitUntilDone();
        stderrPumper.waitUntilDone();
        
        if ( exitCode == 0 )
        {
            LOGGER.fine( processName + " returned zero exit code"  );
        }
        else 
        { 
            LOGGER.severe( processName + " returned non-zero exit code (" + exitCode + ")" );
        }
        
        return exitCode; 
    }
1210294
SecurityUtilityReturnCodes runProgram(String[] args) {
        if (stdin == null) {
            stderr.println(CommandUtils.getMessage("error.missingIO", "stdin"));

            return SecurityUtilityReturnCodes.ERR_GENERIC;
        }
        if (stdout == null) {
            stderr.println(CommandUtils.getMessage("error.missingIO", "stdout"));

            return SecurityUtilityReturnCodes.ERR_GENERIC;
        }
        if (stderr == null) {
            stdout.println(CommandUtils.getMessage("error.missingIO", "stderr"));

            return SecurityUtilityReturnCodes.ERR_GENERIC;
        }

        // Help is always available
        HelpTask help = new HelpTask(SCRIPT_NAME, tasks);
        registerTask(help);

        if (args.length == 0) {
            stdout.println(help.getScriptUsage());
            return SecurityUtilityReturnCodes.OK;
        }

        // Convenience: If the first argument can reasonably be interpreted as "help", do so.
        // Note NLS issue and presumption that none of the other commands rhyme with help...
        // which is part of why I'm checking starts/ends rather than contains.
        if (args[0].toLowerCase().endsWith(help.getTaskName().toLowerCase())) {
            args[0] = help.getTaskName();
        }

        SecurityUtilityTask task = getTask(args[0]);
        if (task == null) {
            stderr.println(CommandUtils.getMessage("task.unknown", args[0]));
            stderr.println(help.getScriptUsage());
            // It is unfortunate that this returns 0 (OK) but that's what it used to do,
            // so don't break anything.
            return SecurityUtilityReturnCodes.OK;
        } else {
            try {
                return task.handleTask(stdin, stdout, stderr, args);
            } catch (IllegalArgumentException e) {
                stderr.println("");
                stderr.println(CommandUtils.getMessage("error", e.getMessage()));
                stderr.println(help.getTaskUsage(task));
                return SecurityUtilityReturnCodes.ERR_GENERIC;
            } catch (Exception e) {
                stderr.println("");
                stderr.println(CommandUtils.getMessage("error", e.toString()));
                stderr.println(help.getTaskUsage(task));
                return SecurityUtilityReturnCodes.ERR_GENERIC;
            }
        }
    }
1329156
def pack_command(self, *args):
        ""
        output = []
        # the client might have included 1 or more literal arguments in
        # the command name, e.g., 'CONFIG GET'. The Redis server expects these
        # arguments to be sent separately, so split the first argument
        # manually. All of these arguements get wrapped in the Token class
        # to prevent them from being encoded.
        command = args[0]
        if ' ' in command:
            args = tuple(Token.get_token(s)
                         for s in command.split()) + args[1:]
        else:
            args = (Token.get_token(command),) + args[1:]

        buff = SYM_EMPTY.join((SYM_STAR, str(len(args)).encode(), SYM_CRLF))

        buffer_cutoff = self._buffer_cutoff
        for arg in imap(self.encoder.encode, args):
            # to avoid large string mallocs, chunk the command into the
            # output list if we're sending large values
            if len(buff) > buffer_cutoff or len(arg) > buffer_cutoff:
                buff = SYM_EMPTY.join(
                    (buff, SYM_DOLLAR, str(len(arg)).encode(), SYM_CRLF))
                output.append(buff)
                output.append(arg)
                buff = SYM_CRLF
            else:
                buff = SYM_EMPTY.join(
                    (buff, SYM_DOLLAR, str(len(arg)).encode(),
                     SYM_CRLF, arg, SYM_CRLF))
        output.append(buff)
        return output
315905
def cli(self, commands):
        """"""
        cli_output = {}

        def _count(txt, none):  # Second arg for consistency only. noqa
            """
            Return the exact output, as Junos displays
            e.g.:
            > show system processes extensive | match root | count
            Count: 113 lines
            """
            count = len(txt.splitlines())
            return "Count: {count} lines".format(count=count)

        def _trim(txt, length):
            """
            Trim specified number of columns from start of line.
            """
            try:
                newlines = []
                for line in txt.splitlines():
                    newlines.append(line[int(length) :])
                return "\n".join(newlines)
            except ValueError:
                return txt

        def _except(txt, pattern):
            """
            Show only text that does not match a pattern.
            """
            rgx = "^.*({pattern}).*$".format(pattern=pattern)
            unmatched = [
                line for line in txt.splitlines() if not re.search(rgx, line, re.I)
            ]
            return "\n".join(unmatched)

        def _last(txt, length):
            """
            Display end of output only.
            """
            try:
                return "\n".join(txt.splitlines()[(-1) * int(length) :])
            except ValueError:
                return txt

        def _match(txt, pattern):
            """
            Show only text that matches a pattern.
            """
            rgx = "^.*({pattern}).*$".format(pattern=pattern)
            matched = [line for line in txt.splitlines() if re.search(rgx, line, re.I)]
            return "\n".join(matched)

        def _find(txt, pattern):
            """
            Search for first occurrence of pattern.
            """
            rgx = "^.*({pattern})(.*)$".format(pattern=pattern)
            match = re.search(rgx, txt, re.I | re.M | re.DOTALL)
            if match:
                return "{pattern}{rest}".format(pattern=pattern, rest=match.group(2))
            else:
                return "\nPattern not found"

        def _process_pipe(cmd, txt):
            """
            Process CLI output from Juniper device that
            doesn't allow piping the output.
            """
            if txt is None:
                return txt
            _OF_MAP = OrderedDict()
            _OF_MAP["except"] = _except
            _OF_MAP["match"] = _match
            _OF_MAP["last"] = _last
            _OF_MAP["trim"] = _trim
            _OF_MAP["count"] = _count
            _OF_MAP["find"] = _find
            # the operations order matter in this case!
            exploded_cmd = cmd.split("|")
            pipe_oper_args = {}
            for pipe in exploded_cmd[1:]:
                exploded_pipe = pipe.split()
                pipe_oper = exploded_pipe[0]  # always there
                pipe_args = "".join(exploded_pipe[1:2])
                # will not throw error when there's no arg
                pipe_oper_args[pipe_oper] = pipe_args
            for oper in _OF_MAP.keys():
                # to make sure the operation sequence is correct
                if oper not in pipe_oper_args.keys():
                    continue
                txt = _OF_MAP[oper](txt, pipe_oper_args[oper])
            return txt

        if not isinstance(commands, list):
            raise TypeError("Please enter a valid list of commands!")
        _PIPE_BLACKLIST = ["save"]
        # Preprocessing to avoid forbidden commands
        for command in commands:
            exploded_cmd = command.split("|")
            command_safe_parts = []
            for pipe in exploded_cmd[1:]:
                exploded_pipe = pipe.split()
                pipe_oper = exploded_pipe[0]  # always there
                if pipe_oper in _PIPE_BLACKLIST:
                    continue
                pipe_args = "".join(exploded_pipe[1:2])
                safe_pipe = (
                    pipe_oper
                    if not pipe_args
                    else "{fun} {args}".format(fun=pipe_oper, args=pipe_args)
                )
                command_safe_parts.append(safe_pipe)
            safe_command = (
                exploded_cmd[0]
                if not command_safe_parts
                else "{base} | {pipes}".format(
                    base=exploded_cmd[0], pipes=" | ".join(command_safe_parts)
                )
            )
            raw_txt = self.device.cli(safe_command, warning=False)
            cli_output[py23_compat.text_type(command)] = py23_compat.text_type(
                _process_pipe(command, raw_txt)
            )
        return cli_output
1110151
private CommandOutput<?, ?> executeSql(List<Command> cmds) {
    String query = null;
    int fetchSize = 0;

    for (Command cmd : cmds) {
      if (cmd instanceof JdbcCommand) {
        JdbcCommandType type = (JdbcCommandType) cmd.getCommandType();
        switch (type) {
          case QUERY:
            query = cmd.getParams().get(0);
            break;
          case FETCHSIZE:
            fetchSize = Integer.parseInt(cmd.getParams().get(0));
            break;
          default:
            this.log.error("Command " + type.toString() + " not recognized");
            break;
        }
      }
    }

    this.log.info("Executing query:" + query);
    ResultSet resultSet = null;
    try {
      this.jdbcSource = createJdbcSource();
      if (this.dataConnection == null) {
        this.dataConnection = this.jdbcSource.getConnection();
      }
      Statement statement = this.dataConnection.createStatement();

      if (fetchSize != 0 && this.getExpectedRecordCount() > 2000) {
        statement.setFetchSize(fetchSize);
      }
      final boolean status = statement.execute(query);
      if (status == false) {
        this.log.error("Failed to execute sql:" + query);
      }
      resultSet = statement.getResultSet();
    } catch (Exception e) {
      this.log.error("Failed to execute sql:" + query + " ;error-" + e.getMessage(), e);
    }

    CommandOutput<JdbcCommand, ResultSet> output = new JdbcCommandOutput();
    output.put((JdbcCommand) cmds.get(0), resultSet);
    return output;
  }
824427
@Then("^the command output contains '(.+?)'$")
    public void findShellOutput(String search) throws Exception {
        assertThat(commonspec.getCommandResult()).as("Contains " + search + ".").contains(search);
    }
428091
public static String getOutputPart(ProcessOutput processOutput,String prefix)
    {
        //get output
        String output=processOutput.getOutputText();

        if(output!=null)
        {
            //set flag
            boolean validOutput=false;

            int index=output.indexOf(prefix);
            if(index!=-1)
            {
                //get index
                index=index+prefix.length();
    
                if(output.length()>index)
                {
                    //get output
                    output=output.substring(index);
                    
                    output=output.trim();
                    index=output.indexOf("\n");
                    if(index!=-1)
                    {
                        output=output.substring(0,index);
                        output=output.trim();
                    }

                    if(output.length()>0)
                    {
                        //set flag
                        validOutput=true;
                    }
                }
            }
            
            if(!validOutput)
            {
                output=null;
            }
        }
        
        return output;
    }
948353
protected void safeSet(CommandOutput<?, ?, ?> output, long integer, RedisCommand<?, ?, ?> command) {

        try {
            output.set(integer);
        } catch (Exception e) {
            command.completeExceptionally(e);
        }
    }
1039867
public static RemoteCommand parse(String inputLine) {
    if (null == inputLine) throw new NullPointerException("inputLine can't be null");
    String[] values = inputLine.split("\\|");
    if (values.length != NUMARGSINCLUDINGBOUNDARIES) {
      throw new IllegalStateException("Cannot parse invalid line: " + inputLine + values.length);
    }
    return new DefaultRemoteCommand(values[FIRSTINDEX], new String[] {values[SECONDINDEX],
        values[THIRDINDEX]});
  }
128372
private static String executePowerShellCommand(String command) {
        try {
            String[] commandList = {POWER_SHELL, POWER_SHELL_COMMAND, command};
            ProcessBuilder pb = new ProcessBuilder(commandList);
            Process process = pb.start();

            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            String line;
            while ((line = br.readLine()) != null) {
                if (line.startsWith(COMMON_NAME_PARAMETER)) {
                    String[] values = line.split(COMMA_SPLIT);
                    return values[0].substring(values[0].indexOf(EQUAL_SPLIT) + 1);
                }
            }
        } catch (Exception e) {
            // do nothing
        }
        return null;
    }
298943
def _parse_show_output(cmd_ret):
    '''
    
    '''
    parsed_data = dict()
    list_key = None

    for line in cmd_ret.splitlines():
        # Skip empty lines.
        if not line.strip():
            continue

        # If there are indented lines below an existing key, assign them as a list value
        # for that key.
        if not salt.utils.stringutils.contains_whitespace(line[0]):
            list_key = None

        if list_key:
            list_value = _convert_to_closest_type(line)
            parsed_data.setdefault(list_key, []).append(list_value)
            continue

        items = [item.strip() for item in line.split(':', 1)]

        key = items[0].lower()
        key = ' '.join(key.split()).replace(' ', '_')

        # Track the current key so that we can use it in instances where the values
        # appear on subsequent lines of the output.
        list_key = key

        try:
            value = items[1]
        except IndexError:
            # If the line doesn't have the separator or is otherwise invalid, skip it.
            log.debug('Skipping line: %s', line)
            continue

        if value:
            parsed_data[key] = _convert_to_closest_type(value)

    return _convert_parsed_show_output(parsed_data=parsed_data)
518047
public CommandOutput<?, ?> getResponse(List<Command> cmds) throws RestApiProcessingException {
    String url = cmds.get(0).getParams().get(0);

    log.info("URL: " + url);
    String jsonStr = null;
    HttpRequestBase httpRequest = new HttpGet(url);
    addHeaders(httpRequest);
    HttpEntity httpEntity = null;
    HttpResponse httpResponse = null;
    try {
      httpResponse = this.httpClient.execute(httpRequest);
      StatusLine status = httpResponse.getStatusLine();
      httpEntity = httpResponse.getEntity();

      if (httpEntity != null) {
        jsonStr = EntityUtils.toString(httpEntity);
      }

      if (status.getStatusCode() >= 400) {
        log.info("Unable to get response using: " + url);
        JsonElement jsonRet = GSON.fromJson(jsonStr, JsonArray.class);
        throw new RestApiProcessingException(getFirstErrorMessage("Failed to retrieve response from", jsonRet));
      }
    } catch (Exception e) {
      throw new RestApiProcessingException("Failed to process rest api request; error - " + e.getMessage(), e);
    } finally {
      try {
        if (httpEntity != null) {
          EntityUtils.consume(httpEntity);
        }
        // httpResponse.close();
      } catch (Exception e) {
        throw new RestApiProcessingException("Failed to consume httpEntity; error - " + e.getMessage(), e);
      }
    }
    CommandOutput<RestApiCommand, String> output = new RestApiCommandOutput();
    output.put((RestApiCommand) cmds.get(0), jsonStr);
    return output;
  }