org.sonar.api.utils.command.Command Java Examples

The following examples show how to use org.sonar.api.utils.command.Command. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CommandRunner.java    From sonar-clojure with MIT License 6 votes vote down vote up
CommandStreamConsumer run(String command, CommandStreamConsumer stdout,
                          CommandStreamConsumer stderr, Long timeOut, String... arguments) {
    Command cmd = Command.create(command);
    Arrays.stream(arguments).filter(Objects::nonNull).forEach(cmd::addArgument);

    int returnCode = commandExecutor.execute(cmd, stdout, stderr, fromSecondsToMilliseconds(timeOut));

    logger.debug("command: " + cmd.getArguments());
    logger.debug("stdout: " + String.join(DELIMITER, stdout.getData()));
    logger.debug("stderr: " + String.join(DELIMITER, stderr.getData()));

    if (SUCCESS_RETURN_CODE != returnCode) {
        //TODO A return code different than 0 doesn't mean error for some of the plugins we use.
        logger.warn("Command: " + cmd.getArguments() + " returned a non-zero code." +
                " Please make sure plugin is working" +
                " isolated before running sonar-scanner");
    }

    return stdout;
}
 
Example #2
Source File: CommandRunnerTest.java    From sonar-clojure with MIT License 6 votes vote down vote up
@Test
public void shouldTakeMultipleArgumentsForCommand() {
    commandRunner.run(300L, "echo", "argument1", null, "argument2");

    ArgumentCaptor<Command> commandCaptor = ArgumentCaptor.forClass(Command.class);
    verify(commandExecutor, times(1))
            .execute(
                    commandCaptor.capture(),
                    any(CommandStreamConsumer.class),
                    any(CommandStreamConsumer.class),
                    anyLong());

    Command cmd = commandCaptor.getValue();
    assertThat(cmd.getArguments().size(), is(2));
    assertThat(cmd.getArguments().get(0), is("argument1"));
    assertThat(cmd.getArguments().get(1), is("argument2"));
}
 
Example #3
Source File: RubocopExecutor.java    From sonar-ruby-plugin with MIT License 6 votes vote down vote up
public String execute(RubocopExecutorConfig config, List<String> files) {
    checkNotNull(config, "RubcopExecutorConfig must not be null");
    checkNotNull(files, "List of files must not be null");

    if (config.useExistingRubocopOutput()) {
        LOG.debug("Running with existing JSON file '{}' instead of calling rubocop", config.getPathToRubocopOutput());
        return getFileContent(new File(config.getPathToRubocopOutput()));
    }

    File rubocopOutputFile = tempFolder.newFile();
    String rubocopOutputFilePath = rubocopOutputFile.getAbsolutePath();
    Command baseCommand = getBaseCommand(config, rubocopOutputFilePath);

    StringStreamConsumer stdOutConsumer = new StringStreamConsumer();
    StringStreamConsumer stdErrConsumer = new StringStreamConsumer();
    return getCommandOutput(baseCommand, stdOutConsumer, stdErrConsumer, rubocopOutputFile, config.getTimeoutMs());
}
 
Example #4
Source File: RubocopExecutor.java    From sonar-ruby-plugin with MIT License 6 votes vote down vote up
private Command getBaseCommand(RubocopExecutorConfig config, String tempPath) {
    Command command =
        Command
            .create(config.getPathToRubocop())
            .addArgument(preparePath(config.getPathToRubocop()))
            .addArgument("--format")
            .addArgument("json");

    if (StringUtils.isNotBlank(tempPath)) {
        command
            .addArgument("--out")
            .addArgument(preparePath(tempPath));
    }

    command
        .addArgument("--config")
        .addArgument(preparePath(config.getConfigFile()));

    command.setNewShell(false);

    return command;
}
 
Example #5
Source File: TsLintExecutorImplTest.java    From SonarTsPlugin with MIT License 6 votes vote down vote up
@Test
public void executesCommandWithCorrectArgumentsAndTimeouts() {
    final ArrayList<Command> capturedCommands = new ArrayList<Command>();
    final ArrayList<Long> capturedTimeouts = new ArrayList<Long>();

    Answer<Integer> captureCommand = new Answer<Integer>() {
        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            capturedCommands.add((Command) invocation.getArguments()[0]);
            capturedTimeouts.add((long) invocation.getArguments()[3]);
            return 0;
        }
    };

    when(this.commandExecutor.execute(any(Command.class), any(StreamConsumer.class), any(StreamConsumer.class), any(long.class))).then(captureCommand);
    this.executorImpl.execute(this.config, Arrays.asList(new String[] { "path/to/file", "path/to/another" }));

    assertEquals(1, capturedCommands.size());

    Command theCommand = capturedCommands.get(0);
    long theTimeout = capturedTimeouts.get(0);

    assertEquals("node path/to/tslint --format json --rules-dir path/to/rules --out path/to/temp --config path/to/config path/to/file path/to/another", theCommand.toCommandLine());
    // Expect one timeout period per file processed
    assertEquals(2 * 40000, theTimeout);
}
 
Example #6
Source File: TsLintExecutorImplTest.java    From SonarTsPlugin with MIT License 6 votes vote down vote up
@Test
public void usesTypeCheckParameter_ifConfigSaysToUseTypeCheck() {
    final ArrayList<Command> capturedCommands = new ArrayList<Command>();

    Answer<Integer> captureCommand = new Answer<Integer>() {
        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            capturedCommands.add((Command) invocation.getArguments()[0]);
            return 0;
        }
    };

    this.config.setPathToTsConfig("path/to/tsconfig.json");
    this.config.setShouldPerformTypeCheck(true);

    when(this.commandExecutor.execute(any(Command.class), any(StreamConsumer.class), any(StreamConsumer.class), any(long.class))).then(captureCommand);
    this.executorImpl.execute(this.config, Arrays.asList(new String[] { "path/to/file", "path/to/another" }));

    assertEquals(1, capturedCommands.size());

    Command theCommand = capturedCommands.get(0);

    assertEquals("node path/to/tslint --format json --rules-dir path/to/rules --out path/to/temp --config path/to/config --project path/to/tsconfig.json --type-check", theCommand.toCommandLine());
}
 
Example #7
Source File: TsLintExecutorImplTest.java    From SonarTsPlugin with MIT License 6 votes vote down vote up
@Test
public void DoesNotAddRulesDirParameter_IfNull() {
    final ArrayList<Command> capturedCommands = new ArrayList<Command>();
    final ArrayList<Long> capturedTimeouts = new ArrayList<Long>();

    Answer<Integer> captureCommand = new Answer<Integer>() {
        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            capturedCommands.add((Command) invocation.getArguments()[0]);
            capturedTimeouts.add((long) invocation.getArguments()[3]);
            return 0;
        }
    };

    when(this.commandExecutor.execute(any(Command.class), any(StreamConsumer.class), any(StreamConsumer.class), any(long.class))).then(captureCommand);

    this.config.setRulesDir(null);
    this.executorImpl.execute(this.config, Arrays.asList(new String[] { "path/to/file" }));

    Command theCommand = capturedCommands.get(0);
    assertFalse(theCommand.toCommandLine().contains("--rules-dir"));
}
 
Example #8
Source File: TsLintExecutorImplTest.java    From SonarTsPlugin with MIT License 6 votes vote down vote up
@Test
public void DoesNotAddRulesDirParameter_IfEmptyString() {
    final ArrayList<Command> capturedCommands = new ArrayList<Command>();
    final ArrayList<Long> capturedTimeouts = new ArrayList<Long>();

    Answer<Integer> captureCommand = new Answer<Integer>() {
        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            capturedCommands.add((Command) invocation.getArguments()[0]);
            capturedTimeouts.add((long) invocation.getArguments()[3]);
            return 0;
        }
    };

    when(this.commandExecutor.execute(any(Command.class), any(StreamConsumer.class), any(StreamConsumer.class), any(long.class))).then(captureCommand);

    this.config.setRulesDir("");
    this.executorImpl.execute(this.config, Arrays.asList(new String[] { "path/to/file" }));

    Command theCommand = capturedCommands.get(0);
    assertFalse(theCommand.toCommandLine().contains("--rules-dir"));
}
 
Example #9
Source File: CFLintAnalyzer.java    From sonar-coldfusion with Apache License 2.0 5 votes vote down vote up
public void analyze(File configFile) throws IOException, XMLStreamException {
    File executableJar = null;
    try {
        Command command = Command.create(settings.get(ColdFusionPlugin.CFLINT_JAVA).orElseThrow(
            IllegalStateException::new
        ));
        addCflintJavaOpts(command);
        executableJar = extractCflintJar();
        command.addArgument("-jar")
            .addArgument(executableJar.getPath())
            .addArgument("-xml")
            .addArgument("-folder")
            .addArgument(settings.get("sonar.projectBaseDir").orElseThrow(
                IllegalStateException::new
            ))
            .addArgument("-xmlfile")
            .addArgument(fs.workDir() + File.separator + "cflint-result.xml")
            .addArgument("-configfile")
            .addArgument(configFile.getPath());

        CommandExecutor executor = CommandExecutor.create();
        int exitCode = executor.execute(command, new LogInfoStreamConsumer(), new LogErrorStreamConsumer(), Integer.MAX_VALUE);

        if (exitCode != 0) {
            throw new IllegalStateException("The CFLint analyzer failed with exit code: " + exitCode);
        }
    } finally {
        //cleanup
        if(executableJar!= null && executableJar.exists()) {
            executableJar.deleteOnExit();
        }
    }

}
 
Example #10
Source File: CFLintAnalyzer.java    From sonar-coldfusion with Apache License 2.0 5 votes vote down vote up
protected void addCflintJavaOpts(Command command) {
    final String cflintJavaOpts = settings.get(ColdFusionPlugin.CFLINT_JAVA_OPTS).orElse("");
    if (!Strings.isNullOrEmpty(cflintJavaOpts)) {
        final String[] arguments = cflintJavaOpts.split(" ");
        for (String argument : arguments) {
            command.addArgument(argument);
        }
    }
}
 
Example #11
Source File: TsLintExecutorImpl.java    From SonarTsPlugin with MIT License 5 votes vote down vote up
private Command getBaseCommand(TsLintExecutorConfig config, String tempPath) {
    Command command =
            Command
            .create(config.getPathToNode())
            .addArgument(this.preparePath(config.getPathToTsLint()))
            .addArgument("--format")
            .addArgument("json");

    String rulesDir = config.getRulesDir();
    if (rulesDir != null && rulesDir.length() > 0) {
        command
            .addArgument("--rules-dir")
            .addArgument(this.preparePath(rulesDir));
    }

    if (tempPath != null && tempPath.length() > 0) {
        command
            .addArgument("--out")
            .addArgument(this.preparePath(tempPath));
    }

    command
        .addArgument("--config")
        .addArgument(this.preparePath(config.getConfigFile()));

    if (config.useTsConfigInsteadOfFileList()) {
        command
            .addArgument("--project")
            .addArgument(this.preparePath(config.getPathToTsConfig()));
    }

    if (config.shouldPerformTypeCheck()) {
        command
            .addArgument("--type-check");
    }

    command.setNewShell(false);

    return command;
}
 
Example #12
Source File: TsLintExecutorImplTest.java    From SonarTsPlugin with MIT License 5 votes vote down vote up
@Test
public void doesNotSendFileListToTsLint_ifConfigSaysToUseProjectFile() {
    final ArrayList<Command> capturedCommands = new ArrayList<Command>();
    final ArrayList<Long> capturedTimeouts = new ArrayList<Long>();

    Answer<Integer> captureCommand = new Answer<Integer>() {
        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            capturedCommands.add((Command) invocation.getArguments()[0]);
            capturedTimeouts.add((long) invocation.getArguments()[3]);
            return 0;
        }
    };

    this.config.setPathToTsConfig("path/to/tsconfig.json");

    when(this.commandExecutor.execute(any(Command.class), any(StreamConsumer.class), any(StreamConsumer.class), any(long.class))).then(captureCommand);
    this.executorImpl.execute(this.config, Arrays.asList(new String[] { "path/to/file", "path/to/another" }));

    assertEquals(1, capturedCommands.size());

    Command theCommand = capturedCommands.get(0);
    long theTimeout = capturedTimeouts.get(0);

    assertEquals("node path/to/tslint --format json --rules-dir path/to/rules --out path/to/temp --config path/to/config --project path/to/tsconfig.json", theCommand.toCommandLine());
    // Timeout should be just what we specified since we're not batching

    assertEquals(40000, theTimeout);
}
 
Example #13
Source File: TsLintExecutorImplTest.java    From SonarTsPlugin with MIT License 5 votes vote down vote up
@Test
public void BatchesExecutions_IfTooManyFilesForCommandLine() {
    List<String> filenames = new ArrayList<String>();
    int currentLength = 0;
    int standardCmdLength = "node path/to/tslint --format json --rules-dir path/to/rules --out path/to/temp --config path/to/config".length();

    String firstBatch = "first batch";
    while (currentLength + 12 < TsLintExecutorImpl.MAX_COMMAND_LENGTH - standardCmdLength) {
        filenames.add(firstBatch);
        currentLength += firstBatch.length() + 1; // 1 for the space
    }
    filenames.add("second batch");

    final ArrayList<Command> capturedCommands = new ArrayList<Command>();
    final ArrayList<Long> capturedTimeouts = new ArrayList<Long>();

    Answer<Integer> captureCommand = new Answer<Integer>() {
        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            capturedCommands.add((Command) invocation.getArguments()[0]);
            capturedTimeouts.add((long) invocation.getArguments()[3]);
            return 0;
        }
    };

    when(this.commandExecutor.execute(any(Command.class), any(StreamConsumer.class), any(StreamConsumer.class), any(long.class))).then(captureCommand);
    this.executorImpl.execute(this.config, filenames);

    assertEquals(2, capturedCommands.size());

    Command theSecondCommand = capturedCommands.get(1);

    assertFalse(theSecondCommand.toCommandLine().contains("first batch"));
    assertTrue(theSecondCommand.toCommandLine().contains("second batch"));
}
 
Example #14
Source File: RubocopExecutor.java    From sonar-ruby-plugin with MIT License 4 votes vote down vote up
private String getCommandOutput(Command thisCommand, StreamConsumer stdOutConsumer, StreamConsumer stdErrConsumer, File rubocopOutputFile, Integer timeoutMs) {
    createExecutor().execute(thisCommand, stdOutConsumer, stdErrConsumer, timeoutMs);
    return getFileContent(rubocopOutputFile);
}
 
Example #15
Source File: TsLintExecutorImpl.java    From SonarTsPlugin with MIT License 4 votes vote down vote up
private String getCommandOutput(Command thisCommand, StreamConsumer stdOutConsumer, StreamConsumer stdErrConsumer, File tslintOutputFile, Integer timeoutMs) {
    this.createExecutor().execute(thisCommand, stdOutConsumer, stdErrConsumer, timeoutMs);

    return getFileContent(tslintOutputFile);
}