Example usage for org.apache.commons.exec DefaultExecutor isFailure

List of usage examples for org.apache.commons.exec DefaultExecutor isFailure

Introduction

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

Prototype

public boolean isFailure(final int exitValue) 

Source Link

Usage

From source file:com.rest4j.generator.PHPGeneratorTest.java

@Test
public void testPHPClient() throws Exception {
    gen.setStylesheet("com/rest4j/client/php.xslt");
    new File("target/php").mkdir();
    gen.setApiXmlUrl(getClass().getResource("doc-generator-graph.xml"));
    gen.setOutputDir("target/php");
    gen.addParam(new TemplateParam("common-params", "access-token"));
    gen.addParam(new TemplateParam("prefix", "Test"));
    gen.addParam(new TemplateParam("additional-client-code", "// ADDITIONAL CODE"));
    gen.generate();//from  ww  w.j  ava2s  . c o  m

    // check the syntax
    CommandLine cmdLine = CommandLine.parse("php apiclient.php");
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File("target/php"));
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    int exitValue = executor.execute(cmdLine);
    assertFalse(executor.isFailure(exitValue));

    // check existence of Parameter Object class
    String client = IOUtils.toString(new File("target/php/apiclient.php").toURI());
    assertTrue(client, client.contains("class TestPatchBRequest"));

    assertTrue(client.contains("ADDITIONAL CODE"));
}

From source file:com.rest4j.generator.PythonGeneratorTest.java

@Test
public void testPythonClient() throws Exception {
    gen.setStylesheet("com/rest4j/client/python.xslt");
    new File("target/python").mkdir();
    gen.setApiXmlUrl(getClass().getResource("doc-generator-graph.xml"));
    gen.setOutputDir("target/python");
    gen.addParam(new TemplateParam("common-params", "access-token"));
    gen.addParam(new TemplateParam("additional-client-code", "\t# ADDITIONAL CODE"));
    gen.generate();//  w  w w .ja  va  2  s. c  om

    // let's try compiling the damn thing
    CommandLine cmdLine = CommandLine.parse("python apiclient.py");
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File("target/python"));
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    int exitValue = executor.execute(cmdLine);
    assertFalse(executor.isFailure(exitValue));

    String a = IOUtils.toString(new File("target/python/apiclient.py").toURI());

    // check doc comments
    assertTrue(a, a.contains("Some additional client info"));
    assertTrue(a, a.contains("Some additional python client info"));

    // check existence of Parameter Object class
    assertTrue(a, a.contains("class PatchBRequest"));

    // check additional-client-code
    assertTrue(a, a.contains("\t# ADDITIONAL CODE"));
}

From source file:com.rest4j.generator.JavaGeneratorTest.java

@Test
public void testJavaClient() throws Exception {
    gen.setStylesheet("com/rest4j/client/java.xslt");
    new File("target/java").mkdir();
    gen.setApiXmlUrl(getClass().getResource("doc-generator-graph.xml"));
    gen.setOutputDir("target/java");
    gen.addParam(new TemplateParam("common-params", "access-token"));
    gen.addParam(new TemplateParam("additional-client-code", "// ADDITIONAL CODE"));
    gen.generate();//ww w .  java2 s.co  m

    // let's try compiling the damn thing
    CommandLine cmdLine = CommandLine.parse("mvn package");
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File("target/java"));
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    int exitValue = executor.execute(cmdLine);
    assertFalse(executor.isFailure(exitValue));

    // check doc comments in the file A.java
    String a = IOUtils.toString(new File("target/java/src/main/java/api/model/A.java").toURI());
    assertTrue(a, a.contains("Some additional client info"));
    assertFalse(a, a.contains("Some additional python client info"));

    // check existence of Parameter Object class
    a = IOUtils.toString(new File("target/java/src/main/java/api/model/PatchBRequest.java").toURI());
    assertTrue(a, a.contains("class PatchBRequest"));

    // check some file paths
    assertTrue(new File("target/java/src/main/java/api/util/JsonUtil.java").canRead());
    assertTrue(new File("target/java/src/main/java/api/Request.java").canRead());

    String client = IOUtils.toString(new File("target/java/src/main/java/api/Client.java").toURI());
    assertTrue(client.contains("ADDITIONAL CODE"));
}

From source file:hoot.services.nativeinterfaces.CommandRunnerImpl.java

@Override
public CommandResult exec(String[] command) throws IOException {
    logger.debug("Executing the following command: {}", Arrays.toString(command));

    try (OutputStream stdout = new ByteArrayOutputStream(); OutputStream stderr = new ByteArrayOutputStream()) {

        this.stdout = stdout;
        this.stderr = stderr;

        CommandLine cmdLine = new CommandLine(command[0]);
        for (int i = 1; i < command.length; i++) {
            cmdLine.addArgument(command[i], false);
        }//from   w  ww.j ava 2s .c o m

        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(stdout, stderr);
        DefaultExecutor executor = new DefaultExecutor();
        this.watchDog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        executor.setWatchdog(this.watchDog);
        executor.setStreamHandler(executeStreamHandler);

        int exitValue;
        try {
            exitValue = executor.execute(cmdLine);

            if (executor.isFailure(exitValue) && this.watchDog.killedProcess()) {
                // it was killed on purpose by the watchdog
                logger.info("Process for '{}' command was killed!", cmdLine);
            }
        } catch (Exception e) {
            exitValue = -1;
            logger.warn("Error executing: {}", cmdLine, e);
        }

        CommandResult commandResult = new CommandResult(cmdLine.toString(), exitValue, stdout.toString(),
                stderr.toString());

        logger.debug("Finished executing: {}", commandResult);

        return commandResult;
    }
}

From source file:com.walmart.gatling.commons.ScriptExecutor.java

private Object runJob(Object message) {
    Master.Job job = (Master.Job) message;
    TaskEvent taskEvent = (TaskEvent) job.taskEvent;

    CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand());
    log.info("Verified Script worker received task: {}", message);
    Map<String, Object> map = new HashMap<>();

    if (StringUtils.isNotEmpty(agentConfig.getJob().getMainClass()))
        cmdLine.addArgument(agentConfig.getJob().getCpOrJar());

    map.put("path", new File(agentConfig.getJob().getJobArtifact(taskEvent.getJobName())));
    cmdLine.addArgument("${path}");

    if (!StringUtils.isEmpty(agentConfig.getJob().getMainClass())) {
        cmdLine.addArgument(agentConfig.getJob().getMainClass());
    }//from   w  ww . j a v  a2s  . c  o m
    //parameters come from the task event
    for (Pair<String, String> pair : taskEvent.getParameters()) {
        cmdLine.addArgument(pair.getValue());
    }
    cmdLine.addArgument("-rf").addArgument(agentConfig.getJob().getResultPath(job.roleId, job.jobId));

    cmdLine.setSubstitutionMap(map);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(agentConfig.getJob().getExitValues());
    ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);
    executor.setWorkingDirectory(new File(agentConfig.getJob().getPath()));
    FileOutputStream outFile = null;
    FileOutputStream errorFile = null;
    String outPath = "", errPath = "";
    try {
        outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.jobId);
        errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.jobId);
        //create the std and err files
        outFile = FileUtils.openOutputStream(new File(outPath));
        errorFile = FileUtils.openOutputStream(new File(errPath));

        PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(outFile),
                new ExecLogHandler(errorFile));
        executor.setStreamHandler(psh);
        log.info("command: {}", cmdLine);
        int exitResult = executor.execute(cmdLine);
        //executor.getWatchdog().destroyProcess().
        Worker.Result result = new Worker.Result(exitResult, agentConfig.getUrl(errPath),
                agentConfig.getUrl(outPath), null, job);
        log.info("Exit code: {}", exitResult);
        if (executor.isFailure(exitResult) || exitResult == 1) {
            log.info("Script Executor Failed, job: " + job.jobId);
            //getSender().tell(new Worker.WorkFailed(result), getSelf());
            return new Worker.WorkFailed(result);
        } else {
            result = new Worker.Result(exitResult, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath),
                    agentConfig.getUrl(getMetricsPath(job)), job);
            log.info("Script Executor Completed, job: " + result);
            //getSender().tell(new Worker.WorkComplete(result), getSelf());
            return new Worker.WorkComplete(result);
        }

    } catch (IOException e) {
        log.error(e.toString());
        Worker.Result result = new Worker.Result(-1, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath),
                null, job);
        log.info("Executor Encountered run time exception, result: " + result.toString());
        //getSender().tell(new Worker.WorkFailed(result), getSelf());
        return new Worker.WorkFailed(result);
    } finally {
        IOUtils.closeQuietly(outFile);
        IOUtils.closeQuietly(errorFile);
    }
}

From source file:com.walmart.gatling.commons.ReportExecutor.java

private void runJob(Master.GenerateReport job) {
    TaskEvent taskEvent = job.reportJob.taskEvent;
    CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand());
    Map<String, Object> map = new HashMap<>();

    map.put("path", new File(agentConfig.getJob().getJobArtifact(taskEvent.getJobName())));
    cmdLine.addArgument("${path}");

    //parameters come from the task event
    for (Pair<String, String> pair : taskEvent.getParameters()) {
        cmdLine.addArgument(pair.getValue());
    }/*from w ww  .  j  a v a2  s .c  o  m*/
    String dir = agentConfig.getJob().getLogDirectory() + "reports/" + job.reportJob.trackingId + "/";
    cmdLine.addArgument(dir);

    cmdLine.setSubstitutionMap(map);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(agentConfig.getJob().getExitValues());
    ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);
    executor.setWorkingDirectory(new File(agentConfig.getJob().getPath()));
    FileOutputStream outFile = null;
    FileOutputStream errorFile = null;
    try {
        List<String> resultFiles = new ArrayList<>(job.results.size());
        //download all files adn
        /*int i=0;
        for (Worker.Result result : job.results) {
        String destFile = dir  + i++ + ".log";
        resultFiles.add(destFile);
        DownloadFile.downloadFile(result.metrics,destFile);
        }*/
        AtomicInteger index = new AtomicInteger();
        job.results.parallelStream().forEach(result -> {
            String destFile = dir + index.incrementAndGet() + ".log";
            resultFiles.add(destFile);
            DownloadFile.downloadFile(result.metrics, destFile);
        });
        String outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.reportJob.trackingId);
        String errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.reportJob.trackingId);
        //create the std and err files
        outFile = FileUtils.openOutputStream(new File(outPath));
        errorFile = FileUtils.openOutputStream(new File(errPath));

        PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(outFile),
                new ExecLogHandler(errorFile));

        executor.setStreamHandler(psh);
        System.out.println(cmdLine);
        int exitResult = executor.execute(cmdLine);
        ReportResult result;
        if (executor.isFailure(exitResult)) {
            result = new ReportResult(dir, job.reportJob, false);
            log.info("Report Executor Failed, result: " + job.toString());
        } else {
            result = new ReportResult(job.reportJob.getHtml(), job.reportJob, true);
            log.info("Report Executor Completed, result: " + result.toString());
        }
        for (String resultFile : resultFiles) {
            FileUtils.deleteQuietly(new File(resultFile));
        }
        getSender().tell(result, getSelf());

    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(outFile);
        IOUtils.closeQuietly(errorFile);
    }

}

From source file:com.cws.esolutions.agent.processors.impl.ServiceCheckProcessorImpl.java

public ServiceCheckResponse runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException {
    final String methodName = IServiceCheckProcessor.CNAME
            + "#runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException";

    if (DEBUG) {/*from  ww  w . jav  a2  s. c om*/
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ServiceCheckRequest: {}", request);
    }

    int exitCode = -1;
    Socket socket = null;
    File sourceFile = null;
    CommandLine command = null;
    BufferedWriter writer = null;
    ExecuteStreamHandler streamHandler = null;
    ByteArrayOutputStream outputStream = null;
    ServiceCheckResponse response = new ServiceCheckResponse();

    final DefaultExecutor executor = new DefaultExecutor();
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(CONNECT_TIMEOUT * 1000);
    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    try {
        switch (request.getRequestType()) {
        case NETSTAT:
            sourceFile = scriptConfig.getScripts().get("netstat");

            if (DEBUG) {
                DEBUGGER.debug("sourceFile: {}", sourceFile);
            }

            if (!(sourceFile.canExecute())) {
                throw new ServiceCheckException(
                        "Script file either does not exist or cannot be executed. Cannot continue.");
            }

            command = CommandLine.parse(sourceFile.getAbsolutePath());

            if (request.getPortNumber() != 0) {
                command.addArgument(String.valueOf(request.getPortNumber()), true);
            }

            if (DEBUG) {
                DEBUGGER.debug("CommandLine: {}", command);
            }

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

            executor.setWatchdog(watchdog);
            executor.setStreamHandler(streamHandler);

            if (DEBUG) {
                DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler);
                DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
                DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
                DEBUGGER.debug("DefaultExecutor: {}", executor);
            }

            executor.execute(command, resultHandler);

            resultHandler.waitFor();
            exitCode = resultHandler.getExitValue();

            if (DEBUG) {
                DEBUGGER.debug("exitCode: {}", exitCode);
            }

            writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log"));
            writer.write(outputStream.toString());
            writer.flush();

            response.setResponseData(outputStream.toString());

            if (executor.isFailure(exitCode)) {
                response.setRequestStatus(AgentStatus.FAILURE);
            } else {
                response.setRequestStatus(AgentStatus.SUCCESS);
            }

            break;
        case REMOTEDATE:
            response.setRequestStatus(AgentStatus.SUCCESS);
            response.setResponseData(System.currentTimeMillis());

            break;
        case TELNET:
            response = new ServiceCheckResponse();

            int targetPort = request.getPortNumber();
            String targetServer = request.getTargetHost();

            if (DEBUG) {
                DEBUGGER.debug("Target port: {}", targetPort);
                DEBUGGER.debug("Target server: {}", targetServer);
            }

            if (targetPort == 0) {
                throw new ServiceCheckException("Target port number was not assigned. Cannot action request.");
            }

            final String CRLF = "\r\n";
            final String TERMINATE_TELNET = "^]";

            synchronized (new Object()) {
                InetSocketAddress socketAddress = new InetSocketAddress(targetServer, targetPort);

                socket = new Socket();
                socket.setSoTimeout(IServiceCheckProcessor.CONNECT_TIMEOUT);
                socket.setSoLinger(false, 0);
                socket.setKeepAlive(false);

                try {
                    socket.connect(socketAddress, IServiceCheckProcessor.CONNECT_TIMEOUT);

                    if (!(socket.isConnected())) {
                        throw new ConnectException("Failed to connect to host " + targetServer + " on port "
                                + request.getPortNumber());
                    }

                    PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);
                    pWriter.println(TERMINATE_TELNET + CRLF);
                    pWriter.flush();
                    pWriter.close();

                    response.setRequestStatus(AgentStatus.SUCCESS);
                    response.setResponseData("Telnet connection to " + targetServer + " on port "
                            + request.getPortNumber() + " successful.");
                } catch (ConnectException cx) {
                    response.setRequestStatus(AgentStatus.FAILURE);
                    response.setResponseData("Telnet connection to " + targetServer + " on port "
                            + request.getPortNumber() + " failed with message: " + cx.getMessage());
                }
            }

            break;
        case PROCESSLIST:
            sourceFile = scriptConfig.getScripts().get("processList");

            if (DEBUG) {
                DEBUGGER.debug("sourceFile: {}", sourceFile);
            }

            if (!(sourceFile.canExecute())) {
                throw new ServiceCheckException(
                        "Script file either does not exist or cannot be executed. Cannot continue.");
            }

            command = CommandLine.parse(sourceFile.getAbsolutePath());

            if (request.getPortNumber() != 0) {
                command.addArgument(String.valueOf(request.getPortNumber()), true);
            }

            if (DEBUG) {
                DEBUGGER.debug("CommandLine: {}", command);
            }

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

            executor.setWatchdog(watchdog);
            executor.setStreamHandler(streamHandler);

            if (DEBUG) {
                DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler);
                DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
                DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
                DEBUGGER.debug("DefaultExecutor: {}", executor);
            }

            executor.execute(command, resultHandler);

            resultHandler.waitFor();
            exitCode = resultHandler.getExitValue();

            if (DEBUG) {
                DEBUGGER.debug("exitCode: {}", exitCode);
            }

            writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log"));
            writer.write(outputStream.toString());
            writer.flush();

            response.setResponseData(outputStream.toString());

            if (executor.isFailure(exitCode)) {
                response.setRequestStatus(AgentStatus.FAILURE);
            } else {
                response.setRequestStatus(AgentStatus.SUCCESS);
            }

            break;
        default:
            // unknown operation
            throw new ServiceCheckException("No valid operation was specified");
        }
    } catch (UnknownHostException uhx) {
        ERROR_RECORDER.error(uhx.getMessage(), uhx);

        throw new ServiceCheckException(uhx.getMessage(), uhx);
    } catch (SocketException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new ServiceCheckException(sx.getMessage(), sx);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new ServiceCheckException(iox.getMessage(), iox);
    } catch (InterruptedException ix) {
        ERROR_RECORDER.error(ix.getMessage(), ix);

        throw new ServiceCheckException(ix.getMessage(), ix);
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }

            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return response;
}

From source file:com.cws.esolutions.agent.processors.impl.ApplicationManagerProcessorImpl.java

/**
 * @see com.cws.esolutions.agent.processors.interfaces.IApplicationManagerProcessor#installApplication(com.cws.esolutions.agent.processors.dto.ApplicationManagerRequest)
 *///w  w w. j a  v  a 2s .  c o m
public ApplicationManagerResponse installApplication(final ApplicationManagerRequest request)
        throws ApplicationManagerException {
    final String methodName = IApplicationManagerProcessor.CNAME
            + "#installApplication(final ApplicationManagerRequest request) throws ApplicationManagerException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ApplicationManagerRequest: {}", request);
    }

    BufferedWriter writer = null;
    ApplicationManagerResponse response = new ApplicationManagerResponse();

    final double version = request.getVersion();
    final DefaultExecutor executor = new DefaultExecutor();
    final String installerOptions = request.getInstallerOptions();
    final File installPath = FileUtils.getFile(request.getInstallPath());
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(CONNECT_TIMEOUT * 1000);
    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    final File packageInstaller = FileUtils.getFile(request.getPackageInstaller());

    if (DEBUG) {
        DEBUGGER.debug("double: {}", version);
        DEBUGGER.debug("DefaultExecutor: {}", executor);
        DEBUGGER.debug("String: {}", installerOptions);
        DEBUGGER.debug("File: {}", installPath);
        DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
        DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
        DEBUGGER.debug("File:{}", packageInstaller);
    }

    try {
        if (!(packageInstaller.canExecute())) {
            throw new ApplicationManagerException("Unable to execute package installer. Cannot continue.");
        }

        if (!(installPath.canWrite()) && (!(installPath.mkdirs()))) {
            throw new ApplicationManagerException("Unable to create installation target. Cannot continue.");
        }

        CommandLine command = CommandLine.parse(packageInstaller.getAbsolutePath());
        command.addArgument(installerOptions, false);
        command.addArgument(request.getPackageLocation(), false);

        if (DEBUG) {
            DEBUGGER.debug("CommandLine: {}", command);
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        streamHandler.start();

        executor.setWatchdog(watchdog);
        executor.setStreamHandler(streamHandler);

        if (DEBUG) {
            DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler);
            DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
            DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
            DEBUGGER.debug("DefaultExecutor: {}", executor);
        }

        executor.execute(command, resultHandler);

        resultHandler.waitFor();
        int exitCode = resultHandler.getExitValue();

        writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + request.getPackageName() + ".log"));
        writer.write(outputStream.toString());
        writer.flush();

        if (DEBUG) {
            DEBUGGER.debug("exitCode: {}", exitCode);
        }

        if (executor.isFailure(exitCode)) {
            throw new ApplicationManagerException("Application installation failed: Result Code: " + exitCode);
        }

        response.setResponse(outputStream.toString());
        response.setRequestStatus(AgentStatus.SUCCESS);
    } catch (ExecuteException eex) {
        ERROR_RECORDER.error(eex.getMessage(), eex);

        throw new ApplicationManagerException(eex.getMessage(), eex);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new ApplicationManagerException(iox.getMessage(), iox);
    } catch (InterruptedException ix) {
        ERROR_RECORDER.error(ix.getMessage(), ix);

        throw new ApplicationManagerException(ix.getMessage(), ix);
    } finally {
        try {
            writer.close();
        } catch (IOException iox) {
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return response;
}

From source file:fr.gouv.culture.vitam.utils.Executor.java

/**
 * Execute an external command//from w w w  . j  a va 2s. c om
 * @param cmd
 * @param tempDelay
 * @param correctValues
 * @param showOutput
 * @param realCommand
 * @return correctValues if ok, < 0 if an execution error occurs, or other error values
 */
public static int exec(List<String> cmd, long tempDelay, int[] correctValues, boolean showOutput,
        String realCommand) {
    // Create command with parameters
    CommandLine commandLine = new CommandLine(cmd.get(0));
    for (int i = 1; i < cmd.size(); i++) {
        commandLine.addArgument(cmd.get(i));
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    ByteArrayOutputStream outputStream;
    outputStream = new ByteArrayOutputStream();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream);
    defaultExecutor.setStreamHandler(pumpStreamHandler);

    defaultExecutor.setExitValues(correctValues);
    AtomicBoolean isFinished = new AtomicBoolean(false);
    ExecuteWatchdog watchdog = null;
    Timer timer = null;
    if (tempDelay > 0) {
        // If delay (max time), then setup Watchdog
        timer = new Timer(true);
        watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        defaultExecutor.setWatchdog(watchdog);
        CheckEndOfExecute endOfExecute = new CheckEndOfExecute(isFinished, watchdog, realCommand);
        timer.schedule(endOfExecute, tempDelay);
    }
    int status = -1;
    try {
        // Execute the command
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            } catch (IOException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            }
        } else {
            pumpStreamHandler.stop();
            System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                    + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
            status = -2;
            try {
                outputStream.close();
            } catch (IOException e2) {
            }
            return status;
        }
    } catch (IOException e) {
        pumpStreamHandler.stop();
        System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
        status = -2;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
        return status;
    } finally {
        isFinished.set(true);
        if (timer != null) {
            timer.cancel();
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e1) {
        }
    }
    pumpStreamHandler.stop();
    if (defaultExecutor.isFailure(status) && watchdog != null) {
        if (watchdog.killedProcess()) {
            // kill by the watchdoc (time out)
            if (showOutput) {
                System.err.println(StaticValues.LBL.error_error.get() + "Exec is in Time Out");
            }
        }
        status = -3;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    } else {
        if (showOutput) {
            System.out.println("Exec: " + outputStream.toString());
        }
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    }
    return status;
}

From source file:org.evosuite.utils.ProcessLauncher.java

public int launchNewProcess(File baseDir, String cmdString, int timeout)
        throws IOException, ProcessTimeoutException {

    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog timeoutWatchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(timeoutWatchdog);

    PumpStreamHandler streamHandler = new PumpStreamHandler(this.outAndErr, this.outAndErr, this.input);
    executor.setStreamHandler(streamHandler);
    if (baseDir != null) {
        executor.setWorkingDirectory(baseDir);
    }//from   www.  java2  s  .  c o  m

    int exitValue;
    try {
        logger.debug("About to execute command " + cmdString);
        exitValue = executor.execute(CommandLine.parse(cmdString));
        if (executor.isFailure(exitValue) && timeoutWatchdog.killedProcess()) {
            // it was killed on purpose by the watchdog
            logger.debug("A timeout occured while executing a process");
            logger.debug("The command is " + cmdString);
            throw new ProcessTimeoutException("A timeout occurred while executing command " + cmdString);
        }

        return exitValue;
    } catch (ExecuteException e) {
        if (timeoutWatchdog.killedProcess()) {
            logger.debug("A timeout occured while executing a process");
            logger.debug("The command is " + cmdString);
            throw new ProcessTimeoutException("A timeout occurred while executing command " + cmdString);
        } else {
            throw e;
        }

    }

}