Java Code Examples for org.apache.commons.exec.CommandLine

The following examples show how to use org.apache.commons.exec.CommandLine. These examples are extracted from open source projects. 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 Project: p4ic4idea   Source File: SimpleTestServer.java    License: Apache License 2.0 7 votes vote down vote up
public int getVersion() throws Exception {
	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	CommandLine cmdLine = new CommandLine(p4d);
	cmdLine.addArgument("-V");
	DefaultExecutor executor = new DefaultExecutor();
	PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
	executor.setStreamHandler(streamHandler);
	executor.execute(cmdLine);

	int version = 0;
	for (String line : outputStream.toString().split("\\n")) {
		if (line.startsWith("Rev. P4D")) {
			Pattern p = Pattern.compile("\\d{4}\\.\\d{1}");
			Matcher m = p.matcher(line);
			while (m.find()) {
				String found = m.group();
				found = found.replace(".", ""); // strip "."
				version = Integer.parseInt(found);
			}
		}
	}
	logger.info("P4D Version: " + version);
	return version;
}
 
Example 2
Source Project: javafx-maven-plugin   Source File: JavaFXJLinkMojo.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isJLinkVersion13orHigher(String jlinkExePath) {
    CommandLine versionCommandLine = new CommandLine(jlinkExePath)
            .addArgument("--version");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int resultCode = -1;

    try {
        resultCode = executeCommandLine(new DefaultExecutor(), versionCommandLine, null, baos, System.err);
    } catch (IOException e) {
        if (getLog().isDebugEnabled()) {
            getLog().error("Error getting JLink version", e);
        }
    }

    if (resultCode != 0) {
        getLog().error("Unable to get JLink version");
        getLog().error("Result of " + versionCommandLine + " execution is: '" + resultCode + "'");
        return false;
    }

    String versionStr = new String(baos.toByteArray());
    return JLINK_VERSION_PATTERN.matcher(versionStr).lookingAt();
}
 
Example 3
Source Project: javafx-maven-plugin   Source File: JavaFXRunMojoTestCase.java    License: Apache License 2.0 6 votes vote down vote up
private String getCommandLineAsString(CommandLine commandline) {
    // for the sake of the test comparisons, cut out the eventual
    // cmd /c *.bat conversion
    String result = commandline.getExecutable();
    boolean isCmd = false;
    if (OS.isFamilyWindows() && result.equals("cmd")) {
        result = "";
        isCmd = true;
    }
    String[] arguments = commandline.getArguments();
    for (int i = 0; i < arguments.length; i++) {
        String arg = arguments[i];
        if (isCmd && i == 0 && "/c".equals(arg)) {
            continue;
        }
        if (isCmd && i == 1 && arg.endsWith(".bat")) {
            arg = arg.substring(0, arg.length() - ".bat".length());
        }
        result += (result.length() == 0 ? "" : " ") + arg;
    }
    return result;
}
 
Example 4
Source Project: open-capacity-platform   Source File: ScriptUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 日志文件输出方式
 *
 * 优点:支持将目标数据实时输出到指定日志文件中去
 * 缺点:
 *      标准输出和错误输出优先级固定,可能和脚本中顺序不一致
 *      Java无法实时获取
 *
 * @param command
 * @param scriptFile
 * @param logFile
 * @param params
 * @return
 * @throws IOException
 */
public static int execToFile(String command, String scriptFile, String logFile, String... params) throws IOException {
    // 标准输出:print (null if watchdog timeout)
    // 错误输出:logging + 异常 (still exists if watchdog timeout)
    // 标准输入
    try (FileOutputStream fileOutputStream = new FileOutputStream(logFile, true)) {
        PumpStreamHandler streamHandler = new PumpStreamHandler(fileOutputStream, fileOutputStream, null);

        // command
        CommandLine commandline = new CommandLine(command);
        commandline.addArgument(scriptFile);
        if (params!=null && params.length>0) {
            commandline.addArguments(params);
        }

        // exec
        DefaultExecutor exec = new DefaultExecutor();
        exec.setExitValues(null);
        exec.setStreamHandler(streamHandler);
        int exitValue = exec.execute(commandline);  // exit code: 0=success, 1=error
        return exitValue;
    }
}
 
Example 5
Source Project: Baragon   Source File: LocalLbAdapter.java    License: Apache License 2.0 6 votes vote down vote up
private int executeWithTimeout(CommandLine command, int timeout) throws LbAdapterExecuteException, IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  DefaultExecutor executor = new DefaultExecutor();
  executor.setStreamHandler(new PumpStreamHandler(baos));
  DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

  // Start async and do our own time limiting instead of using a watchdog to avoid https://issues.apache.org/jira/browse/EXEC-62
  try {
    long start = System.currentTimeMillis();
    executor.execute(command, resultHandler);
    while (System.currentTimeMillis() - start < timeout && !resultHandler.hasResult()) {
      Thread.sleep(50);
    }
    if (resultHandler.hasResult()) {
      if (resultHandler.getException() != null) {
        throw resultHandler.getException();
      }
      return resultHandler.getExitValue();
    } else {
      CompletableFuture.runAsync(() -> executor.getWatchdog().destroyProcess(), destroyProcessExecutor);
      throw new LbAdapterExecuteException(baos.toString(Charsets.UTF_8.name()), command.toString());
    }
  } catch (ExecuteException|InterruptedException e) {
    throw new LbAdapterExecuteException(baos.toString(Charsets.UTF_8.name()), e, command.toString());
  }
}
 
Example 6
Source Project: genie   Source File: JobKillServiceV3Test.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Make sure that if the job status is one that is already finished there is no attempt made to kill it.
 *
 * @throws GenieException        on any error
 * @throws GenieCheckedException on any error
 * @throws IOException           on error
 */
@Test
public void wontKillJobIfAlreadyFinished() throws GenieException, GenieCheckedException, IOException {
    Mockito
        .when(this.persistenceService.getJobStatus(ID))
        .thenReturn(JobStatus.SUCCEEDED)
        .thenReturn(JobStatus.FAILED)
        .thenReturn(JobStatus.INVALID)
        .thenReturn(JobStatus.KILLED);

    // Run through the four cases
    this.service.killJob(ID, KILL_REASON);
    this.service.killJob(ID, KILL_REASON);
    this.service.killJob(ID, KILL_REASON);
    this.service.killJob(ID, KILL_REASON);

    Mockito.verify(this.persistenceService, Mockito.never()).getJobExecution(ID);
    Mockito.verify(this.executor, Mockito.never()).execute(Mockito.any(CommandLine.class));
}
 
Example 7
Source Project: p4ic4idea   Source File: SimpleTestServer.java    License: Apache License 2.0 6 votes vote down vote up
public int getVersion() throws Exception {
	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	CommandLine cmdLine = new CommandLine(p4d);
	cmdLine.addArgument("-V");
	DefaultExecutor executor = new DefaultExecutor();
	PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
	executor.setStreamHandler(streamHandler);
	executor.execute(cmdLine);

	int version = 0;
	for (String line : outputStream.toString().split("\\n")) {
		if (line.startsWith("Rev. P4D")) {
			Pattern p = Pattern.compile("\\d{4}\\.\\d{1}");
			Matcher m = p.matcher(line);
			while (m.find()) {
				String found = m.group();
				found = found.replace(".", ""); // strip "."
				version = Integer.parseInt(found);
			}
		}
	}
	logger.info("P4D Version: " + version);
	return version;
}
 
Example 8
Source Project: genie   Source File: JobKillServiceV3Test.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Make sure we can kill a job.
 *
 * @throws GenieException        on any error
 * @throws GenieCheckedException on any error
 * @throws IOException           On error in execute
 */
@Test
public void canKillJob() throws GenieException, GenieCheckedException, IOException {
    final JobExecution jobExecution = Mockito.mock(JobExecution.class);
    Mockito.when(jobExecution.getExitCode()).thenReturn(Optional.empty());
    Mockito.when(jobExecution.getHostName()).thenReturn(HOSTNAME);
    Mockito.when(jobExecution.getProcessId()).thenReturn(Optional.of(PID));
    Mockito.when(this.persistenceService.getJobStatus(ID)).thenReturn(JobStatus.RUNNING);
    Mockito.when(this.persistenceService.getJobExecution(ID)).thenReturn(jobExecution);
    Mockito.when(this.executor.execute(Mockito.any(CommandLine.class))).thenReturn(0, 0);
    Mockito.when(
        this.processCheckerFactory.get(Mockito.eq(PID), Mockito.any(Instant.class))
    ).thenReturn(processChecker);

    this.service.killJob(ID, KILL_REASON);

    Mockito.verify(this.executor, Mockito.times(1)).execute(Mockito.any(CommandLine.class));
    Mockito.verify(this.processChecker, Mockito.times(1)).checkProcess();
}
 
Example 9
Source Project: oxTrust   Source File: StatusCheckerTimer.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")
private String getFacterVersion() {
	ByteArrayOutputStream bos = new ByteArrayOutputStream(4096);
	try {
		CommandLine commandLine = new CommandLine(OxTrustConstants.PROGRAM_FACTER);
		commandLine.addArgument("--version");
		ProcessHelper.executeProgram(commandLine, false, 0, bos);
		return new String(bos.toByteArray(), "UTF-8");
	} catch (UnsupportedEncodingException ex) {
		log.error("Failed to parse program {} output", OxTrustConstants.PROGRAM_FACTER, ex);
		return null;
	} finally {
		IOUtils.closeQuietly(bos);
	}

}
 
Example 10
Source Project: logstash   Source File: NetworkUtils.java    License: Apache License 2.0 6 votes vote down vote up
public String getDockerHostIpAddress(Map<String, String> environment) {
    String ipAddress = LOCALHOST; // Default of localhost
    String dockerMachineName = getDockerMachineName(environment);

    if (!dockerMachineName.isEmpty()) {
        LOG.debug("Docker machine name = " + dockerMachineName);
        CommandLine commandline = CommandLine.parse(DOCKER_MACHINE_IP);
        commandline.addArgument(dockerMachineName);
        LOG.debug("Running exec: " + commandline.toString());
        try {
            ipAddress = StringUtils.strip(runCommand(commandline));
        } catch (IOException e) {
            LOG.error("Unable to run exec command to find ip address.", e);
        }
    } else {
        ipAddress = getDocker0AdapterIPAddress();
    }
    LOG.debug("Returned IP address: " + ipAddress);
    return ipAddress;
}
 
Example 11
protected String prepareSegmentDirectory(CommandLine cmdLine, ITranscoderResource output, TokenReplacer tokenReplacer, String masterWorkingDirectory) throws IOException
{	
	// create sub directory for hls output
	String HLS_SAMPLE_PLAYBACK_TEMPLATE = "hls-index-sample.html";
	String OUTPUT_HLS_PLAYBACK_TEMPLATE = "index.html";
	tokenReplacer.setTokenValue(TokenReplacer.TOKEN.HLS_SAMPLE_PLAYBACK_TEMPLATE, HLS_SAMPLE_PLAYBACK_TEMPLATE);
	
	String outName = output.getMediaName();
	String outNameWithOutExt = FilenameUtils.removeExtension(outName);
	
	File sub = new File(masterWorkingDirectory + File.separator + outNameWithOutExt);
	if(!sub.exists()) sub.mkdir();
	
	File indexTemplateSample = new File(Globals.getEnv(Globals.Vars.TEMPLATE_DIRECTORY) + File.separator + HLS_SAMPLE_PLAYBACK_TEMPLATE);
	File indexTemplate = new File(sub.getAbsolutePath() + File.separator + OUTPUT_HLS_PLAYBACK_TEMPLATE);
	if(indexTemplateSample.exists())  FileUtils.copyFile(indexTemplateSample, indexTemplate);
	logger.info("Copying html template for hls playback into " + sub.getAbsolutePath());
	
	String relative = new File(masterWorkingDirectory).toURI().relativize(new File(sub.getAbsolutePath()).toURI()).getPath();
	logger.info("Relative path of segment directory " + relative);
	
	return relative;
	
}
 
Example 12
Source Project: ldbc_graphalytics   Source File: __platform-name__Loader.java    License: Apache License 2.0 6 votes vote down vote up
public int unload(String loadedInputPath) throws Exception {
	String unloaderDir = platformConfig.getUnloaderPath();
	commandLine = new CommandLine(Paths.get(unloaderDir).toFile());

	commandLine.addArgument("--graph-name");
	commandLine.addArgument(formattedGraph.getName());

	commandLine.addArgument("--output-path");
	commandLine.addArgument(loadedInputPath);

	String commandString = StringUtils.toString(commandLine.toStrings(), " ");
	LOG.info(String.format("Execute graph unloader with command-line: [%s]", commandString));

	Executor executor = new DefaultExecutor();
	executor.setStreamHandler(new PumpStreamHandler(System.out, System.err));
	executor.setExitValue(0);

	return executor.execute(commandLine);
}
 
Example 13
Source Project: graphviz-java   Source File: CommandRunnerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testRunEchoHelloWorld() throws IOException, InterruptedException {
    final CommandLine expected = System.getProperty("os.name").contains("Windows")
            ? CommandLine.parse("cmd /C echo hello world")
            : CommandLine.parse("/bin/sh -c").addArgument("echo hello world", false);

    final CommandLineExecutor cmdExecMock = Mockito.mock(CommandLineExecutor.class);
    final CommandRunner cmdRunner = new CommandBuilder()
            .withShellWrapper(true)
            .withCommandExecutor(cmdExecMock)
            .build();

    cmdRunner.exec(CommandLine.parse("echo hello world"), null, 5000);

    verify(cmdExecMock).execute(runEchoCaptor.capture(), (File) isNull(), eq(5000));
    assertEquals(expected.toString(), runEchoCaptor.getValue().toString());
}
 
Example 14
Source Project: app-runner   Source File: GradleRunner.java    License: MIT License 6 votes vote down vote up
private ExecuteWatchdog runJar(LineConsumer buildLogHandler, LineConsumer consoleLogHandler, Map<String, String> envVarsForApp, Waiter startupWaiter) {
    Path libsPath = Paths.get(projectRoot.getPath(), "build", "libs");
    File libsFolder = libsPath.toFile();

    // To simplify implementation, now I assume only 1 uberjar named "artifact-version-all.jar" under libs folder
    // As we clean the project every time, I can't foresee any possibility that will mix up other uberjars.
    File[] files = libsFolder.listFiles();

    if(files == null) {
        throw new ProjectCannotStartException(libsFolder.getPath() + " doesn't exist");
    }

    Optional<File> jar = Stream.of(files).filter((f) -> f.getName().contains("all")).findFirst();

    if (!jar.isPresent() || !jar.get().isFile()) {
        throw new ProjectCannotStartException("Could not find the jar file at " + jar.get().getPath());
    }

    CommandLine command = javaHomeProvider.commandLine(envVarsForApp)
        .addArgument("-Djava.io.tmpdir=" + envVarsForApp.get("TEMP"))
        .addArgument("-jar")
        .addArgument(fullPath(jar.get()));

    return ProcessStarter.startDaemon(buildLogHandler, consoleLogHandler, envVarsForApp, command, projectRoot, startupWaiter);
}
 
Example 15
Source Project: genie   Source File: JobMonitorTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Make sure that a process whose std out file has grown too large will attempt to be killed.
 *
 * @throws IOException on error
 */
@Test
void canKillProcessOnTooLargeStdOut() throws IOException {
    Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
    Mockito
        .when(this.executor.execute(Mockito.any(CommandLine.class)))
        .thenReturn(0)
        .thenReturn(0)
        .thenReturn(0);

    Mockito.when(this.stdOut.exists()).thenReturn(true);
    Mockito.when(this.stdOut.length())
        .thenReturn(MAX_STD_OUT_LENGTH - 1)
        .thenReturn(MAX_STD_OUT_LENGTH)
        .thenReturn(MAX_STD_OUT_LENGTH + 1);
    Mockito.when(this.stdErr.exists()).thenReturn(false);

    for (int i = 0; i < 3; i++) {
        this.monitor.run();
    }

    Mockito.verify(this.successfulCheckRate, Mockito.times(2)).increment();
    Mockito.verify(this.stdOutTooLarge, Mockito.times(1)).increment();
    Mockito.verify(this.genieEventBus, Mockito.times(1)).publishSynchronousEvent(Mockito.any(KillJobEvent.class));
}
 
Example 16
Source Project: moneta   Source File: DropwizardContractTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
	System.out.println("Java Temp Dir: " +System.getProperty("java.io.tmpdir"));
	
	executor = new DefaultExecutor();
	resultHandler = new DefaultExecuteResultHandler();
	String javaHome = System.getProperty("java.home");
	String userDir = System.getProperty("user.dir");
	
	executor.setStreamHandler(new PumpStreamHandler(System.out));
	watchdog = new ExecuteWatchdog(10000);
	executor.setWatchdog(watchdog);
	executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR 
			+ "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe").addArgument("-version"));
	executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR 
			+ "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe")
		.addArgument("-jar")
		.addArgument(userDir + "/../moneta-dropwizard/target/moneta-dropwizard-" + ContractTestSuite.getProjectVersion() + ".jar")
		.addArgument("server")
		.addArgument("src/main/resources/dropwizard/moneta-dropwizard.yaml"), resultHandler);
	Thread.sleep(3000);
	System.out.println("Test sequence starting....");
}
 
Example 17
Source Project: moneta   Source File: SpringBootContractTest.java    License: Apache License 2.0 6 votes vote down vote up
public void run() {
	try {
	executor = new DaemonExecutor();
	resultHandler = new DefaultExecuteResultHandler();
	String javaHome = System.getProperty("java.home");
	String userDir = System.getProperty("user.dir");
	
	executor.setStreamHandler(new PumpStreamHandler(System.out));
	watchdog = new ExecuteWatchdog(15000);
	executor.setWatchdog(watchdog);
	executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR 
			+ "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe").addArgument("-version"));
	executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR 
			+ "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe")
		.addArgument("-jar")
		.addArgument(userDir + "/../moneta-springboot/target/moneta-springboot-" + ContractTestSuite.getProjectVersion() + ".jar"));
	
	}
	catch (Exception e) {
		e.printStackTrace();
	}
	
}
 
Example 18
private CmdResult exec(int maxAttempts, 
					   String desc, 
					   CommandLine cmd, 
					   String retryExistancePathToCheck) {
	
	String cmdStr = null;
	CmdResult result = null;
	try {
		cmdStr = cmd.toString();

		File retryExistanceCheckFile = new File(retryExistancePathToCheck);
		int attempts = 0;
		
		while((attempts < maxAttempts) && 
			  (result == null || result.getExitCode() > 0 || !retryExistanceCheckFile.exists())) {
			
			attempts++;
			logger.debug("exec() attempt#: "+attempts+ " executing "+desc+": " + cmdStr);
			
			result = executor.execute(cmd,maxAttempts);
			
			// if fail, let it breathe
			if (result.getExitCode() > 0) {
				Thread.currentThread().sleep(getRetriesSleepMS());
			} 
		}

	} catch(Exception e) {
		String msg = "exec() "+desc+" unexpected exception: " +cmdStr + " " + e.getMessage();
		logger.error(msg,e);
		result = new CmdResult(5555, null, msg);
	}
	
	return result;
}
 
Example 19
Source Project: javafx-maven-plugin   Source File: JavaFXRunMojoTestCase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected int executeCommandLine(Executor exec, CommandLine commandLine, Map enviro, OutputStream out,
                                 OutputStream err) throws IOException, ExecuteException {
    commandLines.add(commandLine);
    if (failureMsg != null) {
        throw new ExecuteException(failureMsg, executeResult);
    }
    return executeResult;
}
 
Example 20
Source Project: genie   Source File: LocalAgentLauncherImpl.java    License: Apache License 2.0 5 votes vote down vote up
private CommandLine createCommandLine(
    final Map<String, String> argumentValueReplacements
) {
    final List<String> commandLineTemplate = Lists.newArrayList();

    // Run detached with setsid on Linux
    if (SystemUtils.IS_OS_LINUX) {
        commandLineTemplate.add(SETS_ID);
    }

    // Run as different user with sudo
    if (this.launcherProperties.isRunAsUserEnabled()) {
        commandLineTemplate.addAll(Lists.newArrayList("sudo", "-E", "-u", RUN_USER_PLACEHOLDER));
    }

    // Agent  command line to launch agent (i.e. JVM and its options)
    commandLineTemplate.addAll(this.launcherProperties.getLaunchCommandTemplate());

    final CommandLine commandLine = new CommandLine(commandLineTemplate.get(0));

    for (int i = 1; i < commandLineTemplate.size(); i++) {
        final String argument = commandLineTemplate.get(i);
        // If the argument placeholder is a key in the map, replace it with the corresponding value.
        // Otherwise it's not a placeholder, add it as-is to the command-line.
        commandLine.addArgument(argumentValueReplacements.getOrDefault(argument, argument));
    }

    return commandLine;
}
 
Example 21
Source Project: Open-LaTeX-Studio   Source File: CommandLineExecutor.java    License: MIT License 5 votes vote down vote up
public static synchronized void executeGeneratePDF(CommandLineBuilder cmd) {
    String outputDirectory = "--output-directory=" + cmd.getOutputDirectory();
    String outputFormat = "--output-format=pdf";
    String job = cmd.getJobname() == null ? "" : "--jobname=" + cmd.getJobname().replaceAll(" ", "_");
    ByteArrayOutputStream outputStream = null;
    
    try {           
        String[] command =  new String[] {
            outputDirectory, outputFormat, job, cmd.getPathToSource()
        };
     
        CommandLine cmdLine = new CommandLine(ApplicationUtils.getPathToTEX(cmd.getLatexPath()));
        //For windows, we set handling quoting to true
        cmdLine.addArguments(command, ApplicationUtils.isWindows());
        
        outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        EXECUTOR.setStreamHandler(streamHandler);
        
        if (cmd.getWorkingFile() != null) {
            EXECUTOR.setWorkingDirectory(cmd.getWorkingFile().getParentFile().getAbsoluteFile());
        }
        
        EXECUTOR.execute(cmdLine);      

        if (cmd.getLogger() != null) {
            cmd.getLogger().log(cmdLine.toString());
            cmd.getLogger().log(outputStream.toString());
        }
                    
    } catch (IOException e) {
        if (cmd.getLogger() != null) {
            cmd.getLogger().log("The path to the pdflatex tool is incorrect or has not been set.");
        }
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}
 
Example 22
Source Project: arcusplatform   Source File: SounderControl.java    License: Apache License 2.0 5 votes vote down vote up
private Queue<CommandLine> playerV2(SoundFile file) {
    String volume = volumesV2.get(level.get());
    volume = (volume != null) ? volume : "100";
    
    CommandLine cmd = new CommandLine(PLAYTONES);
    cmd.addArgument("-v");
    cmd.addArgument(volume);

    cmd.addArgument("-f");
    cmd.addArgument("/dev/stdin");

    Queue<CommandLine> q = new LinkedList<CommandLine>();
    q.add(cmd);
    return q;
}
 
Example 23
private static CompletableFuture<AbstractSpan<?>> asyncProcessHasTransactionContext() throws Exception {
    final CompletableFuture<AbstractSpan<?>> future = new CompletableFuture<>();
    DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler() {

        // note: calling super is required otherwise process termination is not detected and waits forever

        @Override
        public void onProcessComplete(int exitValue) {
            super.onProcessComplete(exitValue);
            if (exitValue == 0) {
                future.complete(tracer.getActive());
            } else {
                future.completeExceptionally(new IllegalStateException("Exit value is not 0: " + exitValue));
            }
        }

        @Override
        public void onProcessFailed(ExecuteException e) {
            super.onProcessFailed(e);
            future.completeExceptionally(e);
        }
    };

    new DefaultExecutor().execute(new CommandLine(getJavaBinaryPath()).addArgument("-version"), handler);
    handler.waitFor();

    assertThat(future.isCompletedExceptionally())
        .describedAs("async process should have properly executed")
        .isFalse();

    return future;
}
 
Example 24
Source Project: genie   Source File: JobKillServiceV3Test.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test to make sure that if the job is in init state it doesn't do anything but throw a job finished event.
 *
 * @throws GenieException        on any error
 * @throws GenieCheckedException on any error
 * @throws IOException           on error
 */
@Test
public void canKillJobInInitState() throws GenieException, GenieCheckedException, IOException {
    final ArgumentCaptor<JobFinishedEvent> captor = ArgumentCaptor.forClass(JobFinishedEvent.class);
    Mockito.when(this.persistenceService.getJobStatus(ID)).thenReturn(JobStatus.INIT);
    this.service.killJob(ID, KILL_REASON);

    Mockito.verify(this.genieEventBus, Mockito.times(1)).publishSynchronousEvent(captor.capture());
    Assert.assertThat(captor.getValue().getId(), Matchers.is(ID));
    Assert.assertThat(captor.getValue().getReason(), Matchers.is(JobFinishedReason.KILLED));
    Mockito.verify(this.persistenceService, Mockito.never()).getJobExecution(ID);
    Mockito.verify(this.executor, Mockito.never()).execute(Mockito.any(CommandLine.class));
}
 
Example 25
Source Project: feign   Source File: GitHubExampleIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void runMain() throws Exception {
  final String jar = Arrays.stream(new File("target").listFiles())
      .filter(file -> file.getName().startsWith("feign-example-github")
          && file.getName().endsWith(".jar"))
      .findFirst()
      .map(File::getAbsolutePath)
      .get();

  final String line = "java -jar " + jar;
  final CommandLine cmdLine = CommandLine.parse(line);
  final int exitValue = new DefaultExecutor().execute(cmdLine);

  assertThat(exitValue, CoreMatchers.equalTo(0));
}
 
Example 26
private Protos.CommandInfo buildCommand(final Protos.CommandInfo.URI uri, final String script, final ShardingContexts shardingContexts, final boolean isCommandExecutor) {
    Protos.CommandInfo.Builder result = Protos.CommandInfo.newBuilder().addUris(uri).setShell(true);
    if (isCommandExecutor) {
        CommandLine commandLine = CommandLine.parse(script);
        commandLine.addArgument(GsonFactory.getGson().toJson(shardingContexts), false);
        result.setValue(Joiner.on(" ").join(commandLine.getExecutable(), Joiner.on(" ").join(commandLine.getArguments())));
    } else {
        result.setValue(script);
    }
    return result.build();
}
 
Example 27
private void executeScript(final ShardingContext shardingContext, final String scriptCommandLine) {
    CommandLine commandLine = CommandLine.parse(scriptCommandLine);
    commandLine.addArgument(GsonFactory.getGson().toJson(shardingContext), false);
    try {
        new DefaultExecutor().execute(commandLine);
    } catch (final IOException ex) {
        throw new JobConfigurationException("Execute script failure.", ex);
    }
}
 
Example 28
Source Project: genie   Source File: UNIXUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test the create user method for user already exists but swallow genie exception.
 *
 * @throws IOException If there is any problem.
 */
@Test(expected = IOException.class)
public void testCreateUserMethodSuccessDoesNotExist2() throws IOException {
    final String user = "user";
    final String group = "group";

    Mockito.when(this.executor.execute(Mockito.any(CommandLine.class))).thenThrow(new IOException());
    UNIXUtils.createUser(user, group, executor);
}
 
Example 29
Source Project: graphviz-java   Source File: SystemUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static Function<CommandLine, CommandLine> getLinuxShellWrapperFunc() {
    return (cmd) -> {
        final String originalCmd = Stream.concat(
                Arrays.stream(new String[]{cmd.getExecutable()}),
                Arrays.stream(cmd.getArguments())
        ).collect(Collectors.joining(" "));

        return new CommandLine("/bin/sh")
                .addArgument("-c")
                .addArgument(originalCmd, false);
    };
}
 
Example 30
Source Project: Panako   Source File: Store.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private void extractMetaData(File audioFile){
	Strategy strategy = Strategy.getInstance();
	String identifier = strategy.resolve(file.getAbsolutePath());
	String dir = Config.get(Key.META_DATA_DIRECTORY);
	File metaDataFile = new File(dir,identifier+".json");
	String command = Config.get(Key.META_DATA_COMMAND);
	Map<String,File> map = new HashMap<String,File>();
	map.put("audiofile", audioFile);
	map.put("metadatafile", metaDataFile);
	CommandLine cmdLine = new CommandLine(command);
	cmdLine.addArgument("${audiofile}");
	cmdLine.addArgument("${metadatafile}");
	cmdLine.setSubstitutionMap(map);
	DefaultExecutor executor = new DefaultExecutor();
	//executor.setExitValue(1);
	ExecuteWatchdog watchdog = new ExecuteWatchdog(1000000);
	executor.setWatchdog(watchdog);
	try {
		int exitValue = executor.execute(cmdLine);
		if(exitValue==0){
			System.out.println("Extracted metadata successfully");
		}else{
			System.err.println("Failed to extract metadata for:" + audioFile);
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
	
}