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

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

Introduction

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

Prototype

public DefaultExecutor() 

Source Link

Document

Default constructor creating a default PumpStreamHandler and sets the working directory of the subprocess to the current working directory.

Usage

From source file:net.openbyte.gui.WorkFrame.java

private void menuItem1ActionPerformed(ActionEvent e) {
    if (this.api == ModificationAPI.BUKKIT) {
        showBukkitIncompatibleFeature();
        return;//from   w  ww. j  a  va 2s.  c  o m
    }
    System.out.println("Starting client...");
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            GradleConnector.newConnector().forProjectDirectory(workDirectory).connect().newBuild()
                    .forTasks("runClient").run();
            return null;
        }
    };
    if (this.api == ModificationAPI.MCP) {
        worker = new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() throws Exception {
                if (System.getProperty("os.name").startsWith("Windows")) {
                    Runtime.getRuntime().exec("cmd /c startclient.bat", null, workDirectory);
                    return null;
                }
                try {
                    CommandLine startClient = CommandLine.parse("python "
                            + new File(new File(workDirectory, "runtime"), "startclient.py").getAbsolutePath()
                            + " $@");
                    CommandLine authClient = CommandLine.parse("chmod 755 "
                            + new File(new File(workDirectory, "runtime"), "startclient.py").getAbsolutePath());
                    DefaultExecutor executor = new DefaultExecutor();
                    executor.setWorkingDirectory(workDirectory);
                    executor.execute(authClient);
                    executor.execute(startClient);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        };
    }
    worker.execute();
}

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

private void runCancelJob(Master.Job message) {
    if (getAbortStatus(message.abortUrl, message.trackingId)) {
        CommandLine cmdLine = new CommandLine("/bin/bash");
        cmdLine.addArgument(agentConfig.getJob().getJobArtifact("cancel"));
        cmdLine.addArgument(message.jobId);
        DefaultExecutor killExecutor = new DefaultExecutor();
        ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        killExecutor.setWatchdog(watchdog);
        try {//from w  w  w. j  a v  a2  s  .  c  o m
            log.info("Cancel command: {}", cmdLine);
            killExecutor.execute(cmdLine);
        } catch (IOException e) {
            log.error(e, "Error cancelling job");
        }
    }
}

From source file:modules.NativeProcessMonitoringDaemonModule.java

protected void startNativeMonitor(String command, String options, Path path) throws NativeExecutionException {
    if (command == null || command.equals("")) {
        System.err.println("command null at GeneralNativeCommandModule.extractNative()");
        return;//from w w w .ja v a 2s .  c  om
    }
    CommandLine commandLine = new CommandLine(command);

    if (options != null && !options.equals("")) {
        String[] args = options.split(" ");
        commandLine.addArguments(args);
    }

    if (path != null) {
        commandLine.addArgument(path.toAbsolutePath().toString(), false);
    }
    executor = new DefaultExecutor();
    esh = new MyExecuteStreamHandler();
    executor.setStreamHandler(esh);

    // GeneralExecutableModuleConfig generalExecutableModuleConfig =
    // getConfig();
    executor.setWatchdog(new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT));
    if (getConfig().workingDirectory != null && getConfig().workingDirectory.exists()) {
        executor.setWorkingDirectory(getConfig().workingDirectory);
    }

    try {
        // System.out.println("Now execute: " + commandLine);
        executor.execute(commandLine, this);
    } catch (ExecuteException xs) {
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.exitCode = xs.getExitValue();
        throw n;
    } catch (IOException xs) {
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        throw n;
    }
    return;
}

From source file:net.robyf.dbpatcher.util.MySqlUtil.java

private static void executeWithInput(final CommandLine commandLine, final InputStream input) {
    try {//w  w  w .j a  v a 2 s  .  com
        PumpStreamHandler handler = new PumpStreamHandler(null, null, input);

        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(handler);
        executor.setWatchdog(new ExecuteWatchdog(300000L));
        int returnCode = executor.execute(commandLine);
        if (returnCode != 0) {
            throw new UtilException("Error executing: " + commandLine //NOSONAR
                    + ", return code = " + returnCode); //NOSONAR
        }
    } catch (IOException ioe) {
        throw new UtilException("Error executing: " + commandLine, ioe); //NOSONAR
    }
}

From source file:drat.proteus.DratStartForm.java

private void parseAsVersionControlledRepo(String path, String command, boolean downloadPhase)
        throws IOException {
    if (!downloadPhase) {
        startDrat(path, command);/*  w w w  . ja v a2 s .c om*/
        return;
    }

    String projectName = null;
    boolean git = path.endsWith(".git");
    File tmpDir = new File(System.getProperty("java.io.tmpdir"));
    String tmpDirPath = tmpDir.getCanonicalPath();
    String line = null;
    if (git) {
        projectName = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
        line = "git clone --depth 1 --branch master " + path;
    } else {
        projectName = path.substring(path.lastIndexOf("/") + 1);
        line = "svn export " + path;
    }
    String clonePath = tmpDirPath + File.separator + projectName;
    File cloneDir = new File(clonePath);
    if (cloneDir.isDirectory() && cloneDir.exists()) {
        LOG.info("Git / SVN clone: [" + clonePath + "] already exists, removing it.");
        FileUtils.removeDir(cloneDir);
    }
    LOG.info("Cloning Git / SVN project: [" + projectName + "] remote repo: [" + path + "] into " + tmpDirPath);

    CommandLine cmdLine = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(tmpDir);
    int exitValue = executor.execute(cmdLine);

    if (git) {
        String gitHiddenDirPath = clonePath + File.separator + ".git";
        File gitHiddenDir = new File(gitHiddenDirPath);
        LOG.info("Removing .git directory from " + gitHiddenDirPath);
        FileUtils.removeDir(gitHiddenDir);
    }

    startDrat(clonePath, command);

}

From source file:edu.cornell.med.icb.goby.modes.RunParallelMode.java

public void execute() throws IOException {
    final Slice slices[] = new Slice[numParts];
    File file = new File(input);
    if (!(file.isFile() && file.exists() && file.canRead())) {
        System.err.println("Input file cannot be read: " + input);
        System.exit(1);/*from w w w.j  a  v  a  2  s  . c  om*/
    }
    int i = 0;
    for (final Slice slice : slices) {

        slices[i++] = new Slice();
    }
    final long fileLength = file.length();
    final long sliceLength = fileLength / numParts;
    long currentOffset = 0;

    for (final Slice slice : slices) {

        slice.startOffset = currentOffset;
        slice.endOffset = currentOffset + sliceLength;
        currentOffset = slice.endOffset;
    }

    final ObjectOpenHashSet<String> allOutputs = new ObjectOpenHashSet<String>();
    final ObjectOpenHashSet<String> allFastq = new ObjectOpenHashSet<String>();

    final DoInParallel loop = new DoInParallel(numParts) {
        IsDone done = new IsDone();

        @Override
        public void action(final DoInParallel forDataAccess, final String inputBasename, final int loopIndex) {
            try {

                CompactToFastaMode ctfm = new CompactToFastaMode();
                ctfm.setInputFilename(input);
                ctfm.setOutputFormat(CompactToFastaMode.OutputFormat.FASTQ);
                ctfm.setStartPosition(slices[loopIndex].startOffset);
                ctfm.setEndPosition(slices[loopIndex].endOffset);

                String s = FilenameUtils.getBaseName(FilenameUtils.removeExtension(input)) + "-"
                        + Integer.toString(loopIndex);
                String fastqFilename = s + "-input.fq";
                allFastq.add(fastqFilename);
                File tmp1 = new File(s + "-tmp");
                tmp1.deleteOnExit();
                File output = new File(s + "-out");
                output.deleteOnExit();
                ctfm.setOutputFilename(fastqFilename);
                LOG.info(String.format("Extracting FASTQ for slice [%d-%d] loopIndex=%d %n",
                        slices[loopIndex].startOffset, slices[loopIndex].endOffset, loopIndex));
                ctfm.execute();
                if (loopIndex > 0) {
                    while (!done.isDone()) {
                        // wait a bit to give the first thread the time to load the database and establish shared memory pool
                        //   System.out.println("sleep 5 thread "+loopIndex);
                        sleep(5);
                    }
                    System.out.println("Thread " + loopIndex + " can now start.");
                }
                final Map<String, String> replacements = new HashMap<String, String>();

                final String outputFilename = output.getName();

                replacements.put("%read.fastq%", fastqFilename);
                replacements.put("%tmp1%", tmp1.getName());
                replacements.put("%output%", outputFilename);
                final String transformedCommand = transform(processPartCommand, replacements);
                final DefaultExecutor executor = new DefaultExecutor();
                OutputStream logStream = null;
                try {
                    logStream = new LoggingOutputStream(getClass(), Level.INFO, "");
                    executor.setStreamHandler(
                            new PumpStreamHandler(new StreamSignal(done, "scanning", logStream)));

                    final CommandLine parse = CommandLine.parse(transformedCommand, replacements);
                    LOG.info("About to execute: " + parse);
                    final int exitValue = executor.execute(parse);
                    LOG.info("Exit value = " + exitValue);
                    if (new File(outputFilename + ".header").exists()) {
                        // found output alignment:
                        System.out.println("found output file: " + outputFilename);
                        allOutputs.add(outputFilename + ".header");
                    } else {
                        System.out.println("Warning: did not find output alignment: " + outputFilename);
                    }
                } finally {
                    IOUtils.closeQuietly(logStream);
                    // remove the fastq file
                    new File(fastqFilename).delete();
                }

            } catch (IOException e) {
                LOG.error("Error processing index " + loopIndex + ", " + inputBasename, e);
            }
        }
    };
    String[] parts = new String[numParts];

    for (int j = 0; j < numParts; j++) {
        parts[j] = Integer.toString(j);
    }
    try {
        loop.execute(true, parts);
    } catch (Exception e) {
        System.err.println("An error occurred executing a parallel command: ");
        e.printStackTrace();
    }

    System.out.printf("Preparing to concatenate %d outputs..%n", allOutputs.size());
    final ConcatenateAlignmentMode concat = new ConcatenateAlignmentMode();
    concat.setInputFileNames(allOutputs.toArray(new String[allOutputs.size()]));
    concat.setOutputFilename(output);
    concat.setAdjustQueryIndices(false);
    concat.setAdjustSampleIndices(false);
    concat.execute();

}

From source file:net.openbyte.gui.CreateProjectFrame.java

public void doOperations() {
    createProjectFolder();/*from w w  w  .j ava 2s  .c  om*/
    monitor.setProgress(20);
    monitor.setNote("Creating solution for project...");
    createSolutionFile();
    monitor.setNote("Creating library solution for project...");
    createLibrarySolution();
    monitor.setProgress(60);
    monitor.setNote("Cloning API...");
    cloneAPI();
    monitor.setProgress(90);
    monitor.setNote("Decompiling Minecraft...");
    if (this.api == ModificationAPI.MCP) {
        if (System.getProperty("os.name").startsWith("Windows")) {
            try {
                Runtime.getRuntime().exec("cmd /c decompile.bat", null, projectFolder);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                CommandLine commandLine = CommandLine.parse("python "
                        + new File(new File(projectFolder, "runtime"), "decompile.py").getAbsolutePath()
                        + " $@");
                File runtimePythonDirectory = new File(projectFolder, "runtime");
                File decompilePython = new File(runtimePythonDirectory, "decompile.py");
                CommandLine authPy = CommandLine.parse("chmod 755 " + decompilePython.getAbsolutePath());
                DefaultExecutor executor = new DefaultExecutor();
                executor.setWorkingDirectory(projectFolder);
                executor.execute(authPy);
                executor.execute(commandLine);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    if (this.api == ModificationAPI.MINECRAFT_FORGE) {
        GradleConnector.newConnector().forProjectDirectory(projectFolder).connect().newBuild()
                .setJvmArguments("-XX:-UseGCOverheadLimit").forTasks("setupDecompWorkspace").run();
    }
    monitor.close();
    WelcomeFrame welcomeFrame = new WelcomeFrame();
    welcomeFrame.setVisible(true);
}

From source file:de.torstenwalter.maven.plugins.SQLPlusMojo.java

private void runScriptWithSqlPlus(File file, Map environment)
        throws MojoExecutionException, MojoFailureException {
    checkFileIsReadable(file);//  w w  w .  jav a  2  s.  c o m

    CommandLine commandLine = new CommandLine(sqlplus);
    // logon only once, without this sql*plus would prompt for
    // credentials if given ones are not correct
    commandLine.addArgument("-L");
    StringTokenizer stringTokenizer = new StringTokenizer(getConnectionIdentifier());
    while (stringTokenizer.hasMoreTokens()) {
        commandLine.addArgument(stringTokenizer.nextToken());
    }
    commandLine.addArgument("@" + file.getName());
    if (arguments != null) {
        for (Object argument : arguments) {
            if (argument == null) {
                throw new MojoExecutionException("Misconfigured argument, value is null. "
                        + "Set the argument to an empty value if this is the required behaviour.");
            } else {
                commandLine.addArgument(argument.toString());
            }
        }
    }

    getLog().info("Executing command line: " + obfuscateCredentials(commandLine.toString(), getCredentials()));

    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(file.getParentFile());
    exec.setStreamHandler(new PumpStreamHandler(System.out, System.err));
    try {
        exec.execute(commandLine, environment);
    } catch (ExecuteException e) {
        throw new MojoExecutionException("program exited with exitCode: " + e.getExitValue());
    } catch (IOException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    }
}

From source file:it.drwolf.ridire.index.sketch.AsyncSketchCreator.java

private void compactLines(List<File> tableFile, File finalTable) throws ExecuteException, IOException {
    Executor executor = new DefaultExecutor();
    File tempTabTot = File.createTempFile("ridireTABTOT", ".tbl");
    File tempSh = File.createTempFile("ridireSH", ".sh");
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("export LC_ALL=C\n");
    stringBuffer/*from w ww .  ja va  2  s . c  o  m*/
            .append("cat " + StringUtils.join(tableFile, " ") + " > " + tempTabTot.getAbsolutePath() + "\n");
    stringBuffer.append("awk '{a[$2]+= $1; s+=$1}END{for(i in a){print a[i],i;}; print s \"\t\"}' "
            + tempTabTot.getAbsolutePath() + " | sort -k1nr -k2 > " + finalTable.getAbsolutePath());
    FileUtils.writeStringToFile(tempSh, stringBuffer.toString());
    tempSh.setExecutable(true);
    CommandLine commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    FileUtils.deleteQuietly(tempTabTot);
    FileUtils.deleteQuietly(tempSh);
}

From source file:edu.stolaf.cs.wmrserver.testjob.TestJobTask.java

protected TestJobResult.TransformResult runTransform(long id, File executable, File workingDir,
        InputStream input) throws IOException {
    // Create the result object
    TestJobResult.TransformResult result = new TestJobResult.TransformResult();

    CountingOutputStream output = null;/*from   w  w  w  .  j  a v  a2  s. c o m*/
    CountingOutputStream error = null;
    try {
        // Create and open temporary file for standard output
        File outputFile = File.createTempFile("job-" + Long.toString(_id), "-output", _tempDir);
        output = new CountingOutputStream(new FileOutputStream(outputFile));

        // Create and open temporary file for standard error
        File errorFile = File.createTempFile("job-" + Long.toString(_id), "-error", _tempDir);
        error = new CountingOutputStream(new FileOutputStream(errorFile));

        // If executable is relative, try to resolve in working directory
        // (This emulates the behavior of Streaming)
        if (!executable.isAbsolute()) {
            File resolvedExecutable = new File(workingDir, executable.toString());
            if (resolvedExecutable.isFile()) {
                resolvedExecutable.setExecutable(true);
                executable = resolvedExecutable.getAbsoluteFile();
            }
        }

        // Run the transform

        CommandLine command;
        if (_switchUserCommand == null)
            command = new CommandLine(executable);
        else {
            command = CommandLine.parse(_switchUserCommand);
            HashMap<String, String> substitutionMap = new HashMap<String, String>();
            substitutionMap.put("cmd", executable.toString());
            command.setSubstitutionMap(substitutionMap);
        }

        DefaultExecutor executor = new DefaultExecutor();
        ExecuteWatchdog dog = new ExecuteWatchdog(EXECUTABLE_TIMEOUT);
        PumpStreamHandler pump = new PumpStreamHandler(output, error, input);
        executor.setWorkingDirectory(workingDir);
        executor.setWatchdog(dog);
        executor.setStreamHandler(pump);
        executor.setExitValues(null);

        int exitCode = executor.execute(command);

        result.setExitCode(exitCode);

        // Check whether it produced any output
        if (output.getByteCount() == 0) {
            output.close();
            outputFile.delete();
        } else
            result.setOutputFile(outputFile);

        // Check whether it produced any error output
        if (error.getByteCount() == 0) {
            error.close();
            errorFile.delete();
        } else
            result.setErrorFile(errorFile);
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(error);
    }

    return result;
}