org.apache.commons.exec.ExecuteException Java Examples

The following examples show how to use org.apache.commons.exec.ExecuteException. 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: AbstractFullIntegrated.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
protected void stopDc(DcMeta dcMeta) throws ExecuteException, IOException {
	
	for(InetSocketAddress address : IpUtils.parse(dcMeta.getZkServer().getAddress())){
		logger.info(remarkableMessage("[stopZkServer]{}"), address);
		stopServerListeningPort(address.getPort());
	}
	
	for(MetaServerMeta metaServerMeta : dcMeta.getMetaServers()){
		logger.info("[stopMetaServer]{}", metaServerMeta);
		stopServerListeningPort(metaServerMeta.getPort());
	}
	
	for (ClusterMeta clusterMeta : dcMeta.getClusters().values()) {
		for (ShardMeta shardMeta : clusterMeta.getShards().values()) {
			for (KeeperMeta keeperMeta : shardMeta.getKeepers()) {
				logger.info("[stopKeeperServer]{}", keeperMeta.getPort());
				stopServerListeningPort(keeperMeta.getPort());
			}
			for(RedisMeta redisMeta : shardMeta.getRedises()){
				logger.info("[stopRedisServer]{}", redisMeta.getPort());
				stopServerListeningPort(redisMeta.getPort());
			}
		}
	}
}
 
Example #2
Source File: GeneratorRunner.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
public static int run(final GeneratorConfig gc, final ExecutionConfig ec) throws IOException, InterruptedException {
	final File configFile = File.createTempFile("trainbenchmark-generator-", ".conf");
	final String configPath = configFile.getAbsolutePath();
	gc.saveToFile(configPath);

	final String projectName = String.format("trainbenchmark-generator-%s", gc.getProjectName());
	final String jarPath = String.format("../%s/build/libs/%s-1.0.0-SNAPSHOT-fat.jar", projectName, projectName);
	final String javaCommand = String.format("java -Xms%s -Xmx%s -server -jar %s %s", ec.getXms(), ec.getXmx(),
			jarPath, configPath);

	final CommandLine cmdLine = CommandLine.parse(javaCommand);
	final DefaultExecutor executor = new DefaultExecutor();
	try {
		final int exitValue = executor.execute(cmdLine);
		System.out.println();
		return exitValue;
	} catch (final ExecuteException e) {
		e.printStackTrace(System.out);
		return e.getExitValue();
	}
}
 
Example #3
Source File: JobKillServiceV3Test.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Make sure that if between the time the job execution was pulled from the database and now the job didn't finish.
 *
 * @throws GenieException        on any error
 * @throws GenieCheckedException on any error
 * @throws IOException           on error in execute
 */
@Test
public void cantKillJobIfAlreadyDoneSinceDBCall() 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))).thenThrow(new ExecuteException("blah", 1));
    Mockito.when(
        this.processCheckerFactory.get(Mockito.eq(PID), Mockito.any(Instant.class))
    ).thenReturn(processChecker);
    Mockito.doThrow(new ExecuteException("No such process", 1)).when(this.processChecker).checkProcess();

    this.service.killJob(ID, KILL_REASON);

    Mockito.verify(this.executor, Mockito.never()).execute(this.killCommand);
    Mockito.verify(this.processChecker, Mockito.times(1)).checkProcess();
}
 
Example #4
Source File: JobMonitorTest.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * Make sure that a finished process sends event.
 *
 * @throws Exception on error
 */
@Test
void canCheckFinishedProcessOnUnixLikeSystem() throws Exception {
    Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX);
    Mockito.doThrow(new ExecuteException("done", 1)).when(processChecker).checkProcess();

    this.monitor.run();

    final ArgumentCaptor<JobFinishedEvent> captor = ArgumentCaptor.forClass(JobFinishedEvent.class);
    Mockito
        .verify(this.genieEventBus, Mockito.times(1))
        .publishAsynchronousEvent(captor.capture());

    Assertions.assertThat(captor.getValue()).isNotNull();
    final String jobId = this.jobExecution.getId().orElseThrow(IllegalArgumentException::new);
    Assertions.assertThat(captor.getValue().getId()).isEqualTo(jobId);
    Assertions.assertThat(captor.getValue().getSource()).isEqualTo(this.monitor);
    Mockito.verify(this.finishedRate, Mockito.times(1)).increment();
}
 
Example #5
Source File: Ffprobe.java    From piper with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String,Object> handle(TaskExecution aTask) throws Exception {
  CommandLine cmd = new CommandLine ("ffprobe");
  cmd.addArgument("-v")
     .addArgument("quiet")
     .addArgument("-print_format")
     .addArgument("json")
     .addArgument("-show_error")
     .addArgument("-show_format")
     .addArgument("-show_streams")
     .addArgument(aTask.getRequiredString("input"));
  log.debug("{}",cmd);
  DefaultExecutor exec = new DefaultExecutor();
  File tempFile = File.createTempFile("log", null);
  try (PrintStream stream = new PrintStream(tempFile);) {
    exec.setStreamHandler(new PumpStreamHandler(stream));
    exec.execute(cmd);
    return parse(FileUtils.readFileToString(tempFile));
  }
  catch (ExecuteException e) {
    throw new ExecuteException(e.getMessage(),e.getExitValue(), new RuntimeException(FileUtils.readFileToString(tempFile)));
  }
  finally {
    FileUtils.deleteQuietly(tempFile);
  }
}
 
Example #6
Source File: AbstractCppcheckCommand.java    From cppcheclipse with Apache License 2.0 6 votes vote down vote up
public void waitForExit(CppcheckProcessResultHandler resultHandler,
		IProgressMonitor monitor) throws InterruptedException,
		ProcessExecutionException, IOException {
	try {
		while (resultHandler.isRunning()) {
			Thread.sleep(SLEEP_TIME_MS);
			if (monitor.isCanceled()) {
				watchdog.destroyProcess();
				throw new InterruptedException("Process killed");
			}
		}
		// called to throw execution in case of invalid exit code
		resultHandler.getExitValue();
	} catch (ExecuteException e) {
		// we need to rethrow the error to include the command line
		// since the error dialog does not display nested exceptions,
		// include original error string
		throw ProcessExecutionException.newException(cmdLine.toString(), e);
	} finally {
		processStdErr.close();
		processStdOut.close();
	}
	long endTime = System.currentTimeMillis();
	console.println("Duration " + String.valueOf(endTime - startTime)
			+ " ms.");
}
 
Example #7
Source File: ProcessExecutor.java    From vespa with Apache License 2.0 6 votes vote down vote up
/**
 * Executes the given command synchronously.
 *
 * @param command The command to execute.
 * @param processInput Input provided to the process.
 * @return The result of the execution, or empty if the process does not terminate within the timeout set for this executor.
 * @throws IOException if the process execution failed.
 */
public Optional<ProcessResult> execute(String command, String processInput) throws IOException {
    ByteArrayOutputStream processErr = new ByteArrayOutputStream();
    ByteArrayOutputStream processOut = new ByteArrayOutputStream();

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(createStreamHandler(processOut, processErr, processInput));
    ExecuteWatchdog watchDog = new ExecuteWatchdog(TimeUnit.SECONDS.toMillis(timeoutSeconds));
    executor.setWatchdog(watchDog);
    executor.setExitValues(successExitCodes);

    int exitCode;
    try {
        exitCode = executor.execute(CommandLine.parse(command));
    } catch (ExecuteException e) {
        exitCode = e.getExitValue();
    }
    return (watchDog.killedProcess()) ?
            Optional.empty() : Optional.of(new ProcessResult(exitCode, processOut.toString(), processErr.toString()));
}
 
Example #8
Source File: Session.java    From poor-man-transcoder with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onTranscodeProcessFailed(ExecuteException e, ExecuteWatchdog watchdog, long timestamp) {
	// TODO Auto-generated method stub
	String cause = null;
	
	if(watchdog != null && watchdog.killedProcess()) cause = FAILURE_BY_TIMEOUT;
	else cause = GENERIC_FAILURE;
	
	if(timestamp - this.resultHandler.getAbortRequestTimestamp()>ABORT_TIMEOUT)
	{
		logger.warn("onTranscodeProcessFailed cause: " + cause);
		notifyObservers(SessionEvent.FAILED, new TranscoderExecutionError(e, cause, timestamp));
	}
	else
	{
		logger.warn("Probable force abort");
		doCleanUp();
	}
}
 
Example #9
Source File: LocalLbAdapter.java    From Baragon with 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 #10
Source File: JavaPythonInteropUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenPythonScript_whenPythonProcessExecuted_thenSuccess() throws ExecuteException, IOException {
    String line = "python " + resolvePythonScriptPath("hello.py");
    CommandLine cmdLine = CommandLine.parse(line);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(streamHandler);

    int exitCode = executor.execute(cmdLine);
    assertEquals("No errors should be detected", 0, exitCode);
    assertEquals("Should contain script output: ", "Hello Baeldung Readers!!", outputStream.toString()
        .trim());
}
 
Example #11
Source File: DynamoDBLocal.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Using apache commons exec for cmd line execution
 *
 * @param command
 * @return exitCode
 * @throws ExecuteException
 * @throws IOException
 * @throws InterruptedException
 */
private void startDynamoLocal() throws ExecuteException, IOException, InterruptedException {
  // java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar
  // -sharedDb
  final CommandLine cmdLine = new CommandLine("java");

  cmdLine.addArgument("-Djava.library.path=" + dynLocalDir + "/DynamoDBLocal_lib");
  cmdLine.addArgument("-jar");
  cmdLine.addArgument(dynLocalDir + "/DynamoDBLocal.jar");
  cmdLine.addArgument("-sharedDb");
  cmdLine.addArgument("-inMemory");
  cmdLine.addArgument("-port");
  cmdLine.addArgument(Integer.toString(port));
  System.setProperty("aws.accessKeyId", "dummy");
  System.setProperty("aws.secretKey", "dummy");

  // Using a result handler makes the emulator run async
  final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

  // watchdog shuts down the emulator, later
  watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
  final Executor executor = new DefaultExecutor();
  executor.setWatchdog(watchdog);
  executor.execute(cmdLine, resultHandler);

  // we need to wait here for a bit, in case the emulator needs to update
  // itself
  Thread.sleep(EMULATOR_SPINUP_DELAY_MS);
}
 
Example #12
Source File: DemoStarter.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
private void startRedises(String dc, String clusterId, String shardId) throws ExecuteException, IOException {
	
	DcMeta dcMeta = getDcMeta(dc);
	for(RedisMeta redisMeta : getDcMeta(dc).getClusters().get(clusterId).getShards().get(shardId).getRedises()){
		startRedis(redisMeta);
	}
}
 
Example #13
Source File: UnixProcessChecker.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void checkProcess() throws GenieTimeoutException, ExecuteException, IOException {
    this.executor.execute(this.commandLine);

    // If we get here the process is still running. Check if it should be killed due to timeout.
    if (Instant.now().isAfter(this.timeout)) {
        throw new GenieTimeoutException(
            "Job has exceeded its timeout time of " + this.timeout
        );
    }
}
 
Example #14
Source File: Utils.java    From leaf-snowflake with Apache License 2.0 5 votes vote down vote up
public static void exec_command(String command) throws ExecuteException, IOException {
	String[] cmdlist = command.split(" ");
	CommandLine cmd = new CommandLine(cmdlist[0]);
	for (int i = 1; i < cmdlist.length; i++) {
		cmd.addArgument(cmdlist[i]);
	}

	DefaultExecutor exec = new DefaultExecutor();
	exec.execute(cmd);
}
 
Example #15
Source File: ScriptExecutor.java    From IGUANA with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Will execute the given file with the provided arguments
 * via Shell.
 * 
 * @param file file to execute
 * @param args arguments to execute file with
 * @throws ExecuteException
 * @throws IOException
 * @return Process return, 0 means everything worked fine
 */
public static int exec(String file, String[] args) throws ExecuteException, IOException{
	String fileName = new File(file).getAbsolutePath();

	String[] shellCommand = new String[1 + (args == null ? 0 : args.length)];
	shellCommand[0] = fileName;

	if(args != null)
	{
		System.arraycopy(args, 0, shellCommand, 1, args.length);
	}

	return execute(shellCommand);
}
 
Example #16
Source File: AbstractRedisTest.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
protected void executeScript(String file, String... args) throws ExecuteException, IOException {

        URL url = getClass().getClassLoader().getResource(file);
        if (url == null) {
            url = getClass().getClassLoader().getResource("scripts/" + file);
            if (url == null) {
                throw new FileNotFoundException(file);
            }
        }
        DefaultExecutor executor = new DefaultExecutor();
        String command = "sh -v " + url.getFile() + " " + StringUtil.join(" ", args);
        executor.execute(CommandLine.parse(command));
    }
 
Example #17
Source File: ExecMojo.java    From exec-maven-plugin with Apache License 2.0 5 votes vote down vote up
protected int executeCommandLine( Executor exec, CommandLine commandLine, Map<String, String> enviro,
                                  FileOutputStream outputFile )
                                      throws ExecuteException, IOException
{
    BufferedOutputStream bos = new BufferedOutputStream( outputFile );
    PumpStreamHandler psh = new PumpStreamHandler( bos );
    return executeCommandLine( exec, commandLine, enviro, psh );
}
 
Example #18
Source File: JavaFXRunMojoTestCase.java    From javafx-maven-plugin with 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 #19
Source File: JStormUtils.java    From jstorm with Apache License 2.0 5 votes vote down vote up
/**
 * If it is backend, please set resultHandler, such as DefaultExecuteResultHandler
 * If it is frontend, ByteArrayOutputStream.toString will return the calling result
 * <p>
 * This function will ignore whether the command is successfully executed or not
 *
 * @param command       command to be executed
 * @param environment   env vars
 * @param workDir       working directory
 * @param resultHandler exec result handler
 * @return output stream
 * @throws IOException
 */
@Deprecated
public static ByteArrayOutputStream launchProcess(
        String command, final Map environment, final String workDir,
        ExecuteResultHandler resultHandler) throws IOException {

    String[] cmdlist = command.split(" ");

    CommandLine cmd = new CommandLine(cmdlist[0]);
    for (String cmdItem : cmdlist) {
        if (!StringUtils.isBlank(cmdItem)) {
            cmd.addArgument(cmdItem);
        }
    }

    DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);
    if (!StringUtils.isBlank(workDir)) {
        executor.setWorkingDirectory(new File(workDir));
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    PumpStreamHandler streamHandler = new PumpStreamHandler(out, out);
    executor.setStreamHandler(streamHandler);

    try {
        if (resultHandler == null) {
            executor.execute(cmd, environment);
        } else {
            executor.execute(cmd, environment, resultHandler);
        }
    } catch (ExecuteException ignored) {
    }

    return out;

}
 
Example #20
Source File: KuduLocal.java    From geowave with Apache License 2.0 5 votes vote down vote up
private void executeAsyncAndWatch(final CommandLine command)
    throws ExecuteException, IOException {
  LOGGER.info("Running async: {}", command.toString());
  final ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
  final DefaultExecutor executor = new DefaultExecutor();
  executor.setWatchdog(watchdog);
  executor.setWorkingDirectory(kuduLocalDir);
  watchdogs.add(watchdog);
  // Using a result handler makes the local instance run async
  executor.execute(command, new DefaultExecuteResultHandler());
}
 
Example #21
Source File: AbstractKeeperIntegratedMultiDc.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
protected void startRedises() throws ExecuteException, IOException{
	
	for(DcMeta dcMeta : getDcMetas()){
		for(RedisMeta redisMeta : getDcRedises(dcMeta.getId(), getClusterId(), getShardId())){
			startRedis(redisMeta);
		}
	}
}
 
Example #22
Source File: KeeperSingleDc.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Test
public void testReFullSync() throws ExecuteException, IOException{
	
	RedisKeeperServer redisKeeperServer = getRedisKeeperServerActive(dc);
	DefaultReplicationStore replicationStore = (DefaultReplicationStore) redisKeeperServer.getReplicationStore();

	DcMeta dcMeta = getDcMeta();

	RedisMeta slave1 = createSlave(activeKeeper.getIp(), activeKeeper.getPort());

	int lastRdbUpdateCount = replicationStore.getRdbUpdateCount();
	logger.info(remarkableMessage("[testReFullSync][sendRandomMessage]"));
	sendRandomMessage(redisMaster, 1, replicationStoreCommandFileSize);
	
	for(int i=0; i < 3 ; i++){
		
		logger.info(remarkableMessage("[testReFullSync]{}"), i);
		startRedis(slave1);
		sleep(3000);
		int currentRdbUpdateCount = replicationStore.getRdbUpdateCount();
		logger.info("[testReFullSync]{},{}", lastRdbUpdateCount, currentRdbUpdateCount);
		Assert.assertEquals(lastRdbUpdateCount + 1, currentRdbUpdateCount);
		lastRdbUpdateCount = currentRdbUpdateCount;
		sendMesssageToMasterAndTest(100, getRedisMaster(), Lists.newArrayList(slave1));
	}
	
}
 
Example #23
Source File: TranscodeSessionResultHandler.java    From poor-man-transcoder with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onProcessFailed(ExecuteException e) {
	// TODO Auto-generated method stub
			
	if(this.callback != null) 
	this.callback.onTranscodeProcessFailed(e, watchdog, System.currentTimeMillis());
	
	super.onProcessFailed(e);
}
 
Example #24
Source File: ExecMojo.java    From exec-maven-plugin with Apache License 2.0 5 votes vote down vote up
protected int executeCommandLine( Executor exec, CommandLine commandLine, Map<String, String> enviro,
                                  OutputStream out, OutputStream err )
                                      throws ExecuteException, IOException
{
    // note: don't use BufferedOutputStream here since it delays the outputs MEXEC-138
    PumpStreamHandler psh = new PumpStreamHandler( out, err, System.in );
    return executeCommandLine( exec, commandLine, enviro, psh );
}
 
Example #25
Source File: AbstractFullIntegrated.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
protected void stopXippe() throws ExecuteException, IOException {
	
	stopConsole();
	//stop all servers
	stopAllRedisServer();
			
	// stop keeper
	for (DcMeta dcMeta : getXpipeMeta().getDcs().values()) {
		stopDc(dcMeta);
	}
}
 
Example #26
Source File: ExecMojoTest.java    From exec-maven-plugin with Apache License 2.0 5 votes vote down vote up
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 #27
Source File: TestServer.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
@Override
public void onProcessFailed(ExecuteException e) {
    synchronized (sync) {
        running = false;
        error = e;
        sync.notifyAll();
    }
}
 
Example #28
Source File: PythonInterpreter.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
public void onProcessFailed(ExecuteException e) {
  super.onProcessFailed(e);
  synchronized (statementFinishedNotifier) {
    statementFinishedNotifier.notify();
  }
}
 
Example #29
Source File: RemoteInterpreterManagedProcess.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
public void onProcessFailed(ExecuteException e) {
  super.onProcessFailed(e);
  synchronized (this) {
    notify();
  }
}
 
Example #30
Source File: MySqlProcess.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
public static void runShell(final String shellCommand) throws ExecuteException, IOException {
	final Executor executor = new DefaultExecutor();
	final CommandLine commandLine = new CommandLine("/bin/bash");
	commandLine.addArgument("-c");
	commandLine.addArgument(shellCommand, false);
	executor.execute(commandLine);
}