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

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

Introduction

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

Prototype

public int execute(final CommandLine command) throws ExecuteException, IOException 

Source Link

Usage

From source file:org.jboss.jdocbook.translate.TranslatorImpl.java

private void generateTranslatedXML(File masterFile, File poFile, File translatedFile) {
    if (!masterFile.exists()) {
        log.trace("skipping translation; source file did not exist : {}", masterFile);
        return;//from  www. j av a2 s  .c  o m
    }
    if (!poFile.exists()) {
        log.trace("skipping translation; PO file did not exist : {}", poFile);
        return;
    }

    if (translatedFile.exists() && translatedFile.lastModified() >= masterFile.lastModified()
            && translatedFile.lastModified() >= poFile.lastModified()) {
        log.trace("skipping translation; up-to-date : {0}", translatedFile);
        return;
    }

    if (!translatedFile.getParentFile().exists()) {
        boolean created = translatedFile.getParentFile().mkdirs();
        if (!created) {
            log.info("Unable to create directories for translation");
        }
    }

    CommandLine commandLine = CommandLine.parse("po2xml");
    commandLine.addArgument(FileUtils.resolveFullPathName(masterFile));
    commandLine.addArgument(FileUtils.resolveFullPathName(poFile));

    try {
        final FileOutputStream xmlStream = new FileOutputStream(translatedFile);
        DefaultExecutor executor = new DefaultExecutor();
        try {
            PumpStreamHandler streamDirector = new PumpStreamHandler(xmlStream, System.err);
            executor.setStreamHandler(streamDirector);
            executor.execute(commandLine);
        } catch (IOException ioe) {
            throw new JDocBookProcessException("unable to execute po2xml : " + ioe.getMessage());
        } finally {
            try {
                xmlStream.flush();
                xmlStream.close();
            } catch (IOException ignore) {
                // intentionally empty...
            }
        }
    } catch (IOException e) {
        throw new JDocBookProcessException(
                "unable to open output stream for translated XML file [" + translatedFile + "]");
    }
}

From source file:org.jboss.maven.populator.MavenDeployer.java

public void deploy(final String groupId, final String artifactId, final String version,
        final String artifactPath) throws IOException {
    logger.info("Deploying " + artifactPath);

    final Map<String, String> params = new HashMap<String, String>();
    params.put("settingsUrl", settingsPath);
    params.put("artifactId", artifactId);
    params.put("groupId", groupId);
    params.put("version", version);
    params.put("artifactPath", artifactPath);
    params.put("repositoryUrl", repositoryUrl);
    params.put("repositoryId", repositoryId);

    final CommandLine deployCmd = CommandLine.parse(MVN_DEPLOY);
    deployCmd.setSubstitutionMap(params);

    final DefaultExecutor executor = new DefaultExecutor();
    executor.execute(deployCmd);
}

From source file:org.jboss.windup.decorator.java.decompiler.BackupOfJadretroDecompilerAdapter.java

private void executeJad(File classLocation, File sourceOutputLocation) {

    try {/*  www  .  j  a  va  2 s. c  o  m*/
        // Build command array
        CommandLine cmdLine = new CommandLine(APP_NAME);
        cmdLine.addArgument("-d");
        cmdLine.addArgument("${outputLocation}");
        cmdLine.addArgument("-f");
        cmdLine.addArgument("-o");
        cmdLine.addArgument("-s");
        cmdLine.addArgument("java");
        cmdLine.addArgument("${classLocation}");

        Map<String, Object> argMap = new HashMap<String, Object>();
        argMap.put("outputLocation", sourceOutputLocation);
        argMap.put("classLocation", classLocation);
        cmdLine.setSubstitutionMap(argMap);

        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
        executor.setWatchdog(watchdog);
        int exitValue = executor.execute(cmdLine);

        LOG.debug("Decompiler exited with exit code: " + exitValue);

        if (!sourceOutputLocation.exists()) {
            LOG.error("Expected decompiled source: " + sourceOutputLocation.getAbsolutePath()
                    + "; did not find file.  This likey means that the decompiler did not successfully decompile the class.");
        } else {
            LOG.debug("Decompiled to: " + sourceOutputLocation.getAbsolutePath());
        }

    } catch (IOException e) {
        throw new FatalWindupException(
                "Error running " + APP_NAME + " decompiler.  Validate that " + APP_NAME + " is on your PATH.",
                e);
    } catch (Exception e) {
        throw new FatalWindupException(
                "Error running " + APP_NAME + " decompiler.  Validate that " + APP_NAME + " is on your PATH.",
                e);
    }
}

From source file:org.jboss.windup.decorator.java.decompiler.JadretroDecompilerAdapter.java

private void executeJad(File classLocation, File sourceOutputLocation) {

    try {//  w  w w  . j  ava2s  .  c om
        // Build command array
        CommandLine cmdLine = new CommandLine(APP_NAME);
        cmdLine.addArgument("-d");
        cmdLine.addArgument("${outputLocation}");
        cmdLine.addArgument("-f");
        cmdLine.addArgument("-o");
        cmdLine.addArgument("-s");
        cmdLine.addArgument("java");
        cmdLine.addArgument("${classLocation}");

        Map<String, Object> argMap = new HashMap<String, Object>();
        argMap.put("outputLocation", sourceOutputLocation);
        argMap.put("classLocation", classLocation);
        cmdLine.setSubstitutionMap(argMap);

        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
        executor.setWatchdog(watchdog);
        int exitValue = executor.execute(cmdLine);

        LOG.debug("Decompiler exited with exit code: " + exitValue);

        if (!sourceOutputLocation.exists()) {
            LOG.error("Expected decompiled source: " + sourceOutputLocation.getAbsolutePath()
                    + "; did not find file.  This likey means that the decompiler did not successfully decompile the class.");
        } else {
            LOG.debug("Decompiled to: " + sourceOutputLocation.getAbsolutePath());
        }

    } catch (IOException e) {
        throw new FatalWindupException(
                "Error running " + APP_NAME + " decompiler.  Validate that " + APP_NAME + " is on your PATH.",
                e);
    }
}

From source file:org.jbpm.process.workitem.exec.ExecWorkItemHandler.java

public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
    String command = (String) workItem.getParameter("Command");
    CommandLine commandLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    try {/*w w  w  .  j  av  a2s .c  o  m*/
        executor.execute(commandLine);
        manager.completeWorkItem(workItem.getId(), null);
    } catch (Throwable t) {
        t.printStackTrace();
        manager.abortWorkItem(workItem.getId());
    }
}

From source file:org.jcronjob.agent.AgentProcessor.java

@Override
public Response execute(Request request) throws TException {
    if (!this.password.equalsIgnoreCase(request.getPassword())) {
        return errorPasswordResponse(request);
    }/*from w  w w  .j  a v a 2 s .co m*/

    String command = request.getParams().get("command") + EXITCODE_SCRIPT;

    String pid = request.getParams().get("pid");

    logger.info("[cronjob]:execute:{},pid:{}", command, pid);

    File shellFile = CommandUtils.createShellFile(command, pid);

    Integer exitValue = 1;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Response response = Response.response(request);
    try {
        CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath());
        DefaultExecutor executor = new DefaultExecutor();

        ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream);
        executor.setStreamHandler(stream);
        response.setStartTime(new Date().getTime());
        exitValue = executor.execute(commandLine);
        exitValue = exitValue == null ? 0 : exitValue;
    } catch (Exception e) {
        if (e instanceof ExecuteException) {
            exitValue = ((ExecuteException) e).getExitValue();
        } else {
            exitValue = CronJob.StatusCode.ERROR_EXEC.getValue();
        }
        if (exitValue == CronJob.StatusCode.KILL.getValue()) {
            logger.info("[cronjob]:job has be killed!at pid :{}", request.getParams().get("pid"));
        } else {
            logger.info("[cronjob]:job execute error:{}", e.getCause().getMessage());
        }
    } finally {
        if (outputStream != null) {
            String text = outputStream.toString();
            if (notEmpty(text)) {
                try {
                    response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY)));
                    response.setExitCode(Integer.parseInt(
                            text.substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim()));
                } catch (IndexOutOfBoundsException e) {
                    response.setMessage(text);
                    response.setExitCode(exitValue);
                } catch (NumberFormatException e) {
                    response.setExitCode(exitValue);
                }
            } else {
                response.setExitCode(exitValue);
            }
            try {
                outputStream.close();
            } catch (Exception e) {
                logger.error("[cronjob]:error:{}", e);
            }
        } else {
            response.setExitCode(exitValue);
        }
        response.setSuccess(response.getExitCode() == CronJob.StatusCode.SUCCESS_EXIT.getValue()).end();
        if (shellFile != null) {
            shellFile.delete();//
        }
    }
    logger.info("[cronjob]:execute result:{}", response.toString());
    return response;
}

From source file:org.jlab.clara.std.services.DataManager.java

private void stageInputFile(FilePaths files, EngineData output) {
    Path stagePath = FileUtils.getParent(files.stagedInputFile);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {/*from ww  w  .  j a va2 s.c  om*/
        FileUtils.createDirectories(stagePath);

        CommandLine cmdLine = new CommandLine("cp");
        cmdLine.addArgument(files.inputFile.toString());
        cmdLine.addArgument(files.stagedInputFile.toString());

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

        executor.execute(cmdLine);
        System.out.printf("%s service: input file '%s' copied to '%s'%n", NAME, files.inputFile, stagePath);
        returnFilePaths(output, files);

    } catch (ExecuteException e) {
        ServiceUtils.setError(output, "could not complete request: " + outputStream.toString().trim());
    } catch (IOException e) {
        ServiceUtils.setError(output, "could not complete request: " + e.getMessage());
    }
}

From source file:org.jlab.clara.std.services.DataManager.java

private void removeStagedInputFile(FilePaths files, EngineData output) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {/*from   w w w.j  ava  2 s . com*/
        CommandLine cmdLine = new CommandLine("rm");
        cmdLine.addArgument(files.stagedInputFile.toString());

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

        executor.execute(cmdLine);
        System.out.printf("%s service: staged input file %s removed%n", NAME, files.stagedInputFile);
        returnFilePaths(output, files);

    } catch (ExecuteException e) {
        ServiceUtils.setError(output, "could not complete request: " + outputStream.toString().trim());
    } catch (IOException e) {
        ServiceUtils.setError(output, "could not complete request: " + e.getMessage());
    }
}

From source file:org.jlab.clara.std.services.DataManager.java

private void saveOutputFile(FilePaths files, EngineData output) {
    Path outputPath = FileUtils.getParent(files.outputFile);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {/*from ww w  . j a v  a 2  s.c  om*/
        FileUtils.createDirectories(outputPath);

        CommandLine cmdLine = new CommandLine("mv");

        //            cmdLine.addArgument(files.stagedOutputFile.toString());
        //            cmdLine.addArgument(files.outputFile.toString());

        //             modified 09.12.18. Stage back multiple output files. vg
        Files.list(directoryPaths.stagePath).forEach(name -> {
            name.startsWith(files.stagedOutputFile.toString());
            cmdLine.addArgument(name.toString());
        });
        cmdLine.addArgument(outputPath.toString());
        //                                                                  vg

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

        executor.execute(cmdLine);
        System.out.printf("%s service: output file '%s' saved to '%s'%n", NAME, files.stagedOutputFile,
                outputPath);
        returnFilePaths(output, files);

    } catch (ExecuteException e) {
        ServiceUtils.setError(output, "could not complete request: " + outputStream.toString().trim());
    } catch (IOException e) {
        ServiceUtils.setError(output, "could not complete request: " + e.getMessage());
    }
}

From source file:org.kercoin.magrit.core.build.BuildTask.java

private int build(ByteArrayOutputStream stdout, PrintStream printOut) throws IOException {
    String command = findCommand();
    printOut.println(String.format("Starting build with command '%s'", command));

    CommandLine cmdLine = CommandLine.parse(command);
    DefaultExecutor executable = new DefaultExecutor();
    executable.setWorkingDirectory(repository.getDirectory().getParentFile());
    executable.setStreamHandler(new PumpStreamHandler(stdout));

    return executable.execute(cmdLine);
}