Example usage for org.apache.commons.exec ExecuteException ExecuteException

List of usage examples for org.apache.commons.exec ExecuteException ExecuteException

Introduction

In this page you can find the example usage for org.apache.commons.exec ExecuteException ExecuteException.

Prototype

public ExecuteException(final String message, final int exitValue) 

Source Link

Document

Construct a new exception with the specified detail message.

Usage

From source file:com.creactiviti.piper.core.taskhandler.script.Bash.java

@Override
public String handle(Task aTask) throws Exception {
    File scriptFile = File.createTempFile("_script", ".sh");
    File logFile = File.createTempFile("log", null);
    FileUtils.writeStringToFile(scriptFile, aTask.getRequiredString("script"));
    try (PrintStream stream = new PrintStream(logFile);) {
        Process chmod = Runtime.getRuntime().exec(String.format("chmod u+x %s", scriptFile.getAbsolutePath()));
        int chmodRetCode = chmod.waitFor();
        if (chmodRetCode != 0) {
            throw new ExecuteException("Failed to chmod", chmodRetCode);
        }//from   w  w  w .  ja  va2 s.com
        CommandLine cmd = new CommandLine(scriptFile.getAbsolutePath());
        logger.debug("{}", cmd);
        DefaultExecutor exec = new DefaultExecutor();
        exec.setStreamHandler(new PumpStreamHandler(stream));
        exec.execute(cmd);
        return FileUtils.readFileToString(logFile);
    } catch (ExecuteException e) {
        throw new ExecuteException(e.getMessage(), e.getExitValue(),
                new RuntimeException(FileUtils.readFileToString(logFile)));
    } finally {
        FileUtils.deleteQuietly(logFile);
        FileUtils.deleteQuietly(scriptFile);
    }
}

From source file:com.netflix.genie.core.services.impl.LocalJobKillServiceImplUnitTests.java

/**
 * 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/*from  w  ww  .  j av  a2  s.  c  om*/
 * @throws IOException    on error in execute
 */
@Test
public void cantKillJobIfAlreadyDoneSinceDBCall() throws GenieException, 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.jobSearchService.getJobStatus(ID)).thenReturn(JobStatus.RUNNING);
    Mockito.when(this.jobSearchService.getJobExecution(ID)).thenReturn(jobExecution);
    Mockito.when(this.executor.execute(Mockito.any(CommandLine.class)))
            .thenThrow(new ExecuteException("blah", 1));

    this.service.killJob(ID);

    Mockito.verify(this.executor, Mockito.never()).execute(this.killCommand);
}

From source file:com.netflix.genie.web.services.impl.LocalJobKillServiceImplUnitTests.java

/**
 * 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/*  www  . j  av a2  s .  c  o m*/
 * @throws IOException    on error in execute
 */
@Test
public void cantKillJobIfAlreadyDoneSinceDBCall() throws GenieException, 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.jobSearchService.getJobStatus(ID)).thenReturn(JobStatus.RUNNING);
    Mockito.when(this.jobSearchService.getJobExecution(ID)).thenReturn(jobExecution);
    Mockito.when(this.executor.execute(Mockito.any(CommandLine.class)))
            .thenThrow(new ExecuteException("blah", 1));

    this.service.killJob(ID, KILL_REASON);

    Mockito.verify(this.executor, Mockito.never()).execute(this.killCommand);
}

From source file:com.netflix.genie.web.services.impl.JobKillServiceV3Test.java

/**
 * 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/*  w  ww  .ja  v a  2  s  . c  om*/
 * @throws IOException    on error in execute
 */
@Test
public void cantKillJobIfAlreadyDoneSinceDBCall() throws GenieException, 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.jobSearchService.getJobStatus(ID)).thenReturn(JobStatus.RUNNING);
    Mockito.when(this.jobSearchService.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();
}

From source file:com.netflix.genie.web.tasks.job.JobMonitorTest.java

/**
 * Make sure that a finished process sends event.
 *
 * @throws Exception on error/*from ww  w.  j  ava 2 s . co  m*/
 */
@Test
public void canCheckFinishedProcessOnUnixLikeSystem() throws Exception {
    Assume.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());

    Assert.assertNotNull(captor.getValue());
    final String jobId = this.jobExecution.getId().orElseThrow(IllegalArgumentException::new);
    Assert.assertThat(captor.getValue().getId(), Matchers.is(jobId));
    Assert.assertThat(captor.getValue().getSource(), Matchers.is(this.monitor));
    Mockito.verify(this.finishedRate, Mockito.times(1)).increment();
}

From source file:com.netflix.genie.web.tasks.job.JobMonitorUnitTests.java

/**
 * Make sure that a finished process sends event.
 *
 * @throws IOException on error/*w w  w. j  a va 2s.  com*/
 */
@Test
public void canCheckFinishedProcessOnUnixLikeSystem() throws IOException {
    Assume.assumeTrue(SystemUtils.IS_OS_UNIX);
    Mockito.when(this.executor.execute(Mockito.any(CommandLine.class)))
            .thenThrow(new ExecuteException("done", 1));

    this.monitor.run();

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

    Assert.assertNotNull(captor.getValue());
    final String jobId = this.jobExecution.getId().orElseThrow(IllegalArgumentException::new);
    Assert.assertThat(captor.getValue().getId(), Matchers.is(jobId));
    Assert.assertThat(captor.getValue().getSource(), Matchers.is(this.monitor));
    Mockito.verify(this.finishedRate, Mockito.times(1)).increment();
}

From source file:maker.task.compile.ReplTestPumpStreamHandler.java

/**
 * Stopping a pumper thread. The implementation actually waits
 * longer than specified in 'timeout' to detect if the timeout
 * was indeed exceeded. If the timeout was exceeded an IOException
 * is created to be thrown to the caller.
 *
 * @param thread  the thread to be stopped
 * @param timeout the time in ms to wait to join
 *///  w  w  w .java 2 s.c  o  m
protected void stopThread(final Thread thread, final long timeout) {

    if (thread != null) {
        try {
            if (timeout == 0) {
                thread.join();
            } else {
                final long timeToWait = timeout + STOP_TIMEOUT_ADDITION;
                final long startTime = System.currentTimeMillis();
                thread.join(timeToWait);
                if (!(System.currentTimeMillis() < startTime + timeToWait)) {
                    final String msg = "The stop timeout of " + timeout + " ms was exceeded";
                    caught = new ExecuteException(msg, Executor.INVALID_EXITVALUE);
                }
            }
        } catch (final InterruptedException e) {
            thread.interrupt();
        }
    }
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * <pre>/*from  w  w  w  . j a v  a  2s  . co m*/
 * Kill the TG server.
 * - taskkill on Windows.
 * - kill -9 on Unix.
 * </pre>
 * 
 * @throws Exception
 *             Kill operation fails
 */
public void kill() throws Exception {

    if (this.pid == 0)
        throw new TGGeneralException(
                "TG server does not have a PID - Probably due to a previous start-up failure");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(psh);
    CommandLine cmdLine;
    if (OS.isFamilyWindows())
        cmdLine = CommandLine.parse("taskkill /f /pid " + this.getPid() + " /t");
    else
        cmdLine = CommandLine.parse("kill -9 " + this.getPid() + "");
    try {
        executor.execute(cmdLine);
    } catch (ExecuteException ee) {
        // System.out.println("TGServer with pid " + this.getPid() + " not killed :");
        // System.out.println("\t- " + output.toString().trim().replace("\n","\n\t- "));
        throw new ExecuteException(output.toString().trim(), 1); // re-throw with better message
    }
    System.out.println("TGServer - Server with pid " + this.getPid() + " successfully killed :");
    if (!output.toString().equals(""))
        System.out.println("\t\t- " + output.toString().trim().replace("\n", "\n\t\t- "));
    this.running = false;
    this.pid = 0;
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * <pre>//  w  w  w  .ja va  2  s . com
 * Kill all the TG server processes.
 * Note that this method blindly tries to kill all the servers of the machine 
 * and do not update the running status of those servers.
 * - taskkill on Windows.
 * - kill -9 on Unix.
 * </pre>
 * 
 * @throws Exception Kill operation fails
 */
public static void killAll() throws Exception {

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(psh);
    executor.setWorkingDirectory(new File(System.getProperty("java.io.tmpdir")));
    CommandLine cmdLine;
    if (OS.isFamilyWindows())
        cmdLine = CommandLine.parse("taskkill /f /im " + process + ".exe");
    else { // Unix
        File internalScriptFile = new File(ClassLoader
                .getSystemResource(
                        TGServer.class.getPackage().getName().replace('.', '/') + "/TGKillProcessByName.sh")
                .getFile());
        File finalScriptFile = new File(executor.getWorkingDirectory() + "/" + internalScriptFile.getName());
        Files.copy(internalScriptFile.toPath(), finalScriptFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        cmdLine = CommandLine.parse("sh " + finalScriptFile.getAbsolutePath() + " " + process + "");
    }
    try {
        Thread.sleep(1000);
        executor.execute(cmdLine);
    } catch (ExecuteException ee) {
        if (output.toString().contains(
                "ERROR: The process \"" + process + (OS.isFamilyWindows() ? ".exe\"" : "") + " not found"))
            return;
        throw new ExecuteException(output.toString().trim(), 1); // re-throw with better message
    }
    // Check one more thing :
    // On Windows when some processes do not get killed taskkill still
    // returns exit code
    if (OS.isFamilyWindows()) {
        if (output.toString().contains("ERROR"))
            throw new ExecuteException(output.toString().trim(), 1);
    } else {
        if (output.toString().contains("ERROR: The process \"" + process + "\" not found"))
            return;
    }

    System.out.println("TGServer - Server(s) successfully killed :");
    if (!output.toString().equals(""))
        System.out.println("\t\t- " + output.toString().trim().replace("\n", "\n\t\t- "));
}

From source file:net.sourceforge.vulcan.git.MercurialRepositoryTest.java

public void testInvokeWrapsExecuteException() throws Exception {
    final ExecuteException ee = new ExecuteException("oops", 2);
    expect(invoker.invoke("incoming", workDir)).andThrow(ee);
    expect(invoker.getErrorText()).andReturn("unrecognized option");
    expect(invoker.getOutputText()).andReturn("");
    expect(invoker.getExitCode()).andReturn(2);

    replay();/*from   w w  w  .  ja  va 2s.  c  o  m*/

    try {
        repo.tryInvoke(MercurialRepository.Command.incoming);
        fail("expected RepositoryException");
    } catch (RepositoryException e) {
        assertSame("e.getCause()", ee, e.getCause());
    }

    verify();
}