Example usage for org.apache.commons.exec CommandLine parse

List of usage examples for org.apache.commons.exec CommandLine parse

Introduction

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

Prototype

public static CommandLine parse(final String line) 

Source Link

Document

Create a command line from a string.

Usage

From source file:net.mymam.fileprocessor.VideoFileGenerator.java

private Path generateFile(String cmdLineTemplate, Path in, Path outDir, String outFile, int maxWidth,
        int maxHeight) throws FileProcessingFailedException {
    try {/*from ww w  . j  ava2 s. com*/
        Path out = Paths.get(outDir.toString(), outFile);
        // TODO: Make sure that weired file names cannot be used to inject shell scripts, like '"; rm -r *;'
        String cmdLine = cmdLineTemplate.replace("$INPUT_FILE", "\"" + in.toString() + "\"")
                .replace("$OUTPUT_FILE", "\"" + out.toString() + "\"")
                .replace("$MAX_WIDTH", Integer.toString(maxWidth))
                .replace("$MAX_HEIGHT", Integer.toString(maxHeight));
        CommandLine cmd = CommandLine.parse(cmdLine);
        System.out.println("Executing " + cmd); // TODO: Use logging.
        new DefaultExecutor().execute(cmd);
        return out;
    } catch (Throwable t) {
        throw new FileProcessingFailedException(t);
    }
}

From source file:io.vertx.config.vault.utils.VaultProcess.java

public boolean run(String args) {
    String cli = executable.getAbsolutePath() + " " + args;
    System.out.println(">> " + cli);
    CommandLine parse = CommandLine.parse(cli);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);//from   w w w .j av  a 2  s .c  o m
    try {
        return executor.execute(parse) == 0;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:edu.kit.dama.dataworkflow.impl.LocalExecutionHandler.java

/**
 * Execute the user application. This method will start a new process running
 * the prepared user application locally. The method will return as soon as
 * the application has terminated. An asnychronous monitoring task my check
 * whether the process is still running or not via {@link #getTaskStatus(edu.kit.dama.mdm.dataworkflow.DataWorkflowTask)
 * } This method will check the runningIndicator file '.RUNNING', which only
 * exists as long as the application is running.
 *
 * @param pTask The task whose application should be executed.
 *
 * @throws DataWorkflowProcessingException If either the startup or the
 * processing fails for any reason, or if the user application returns an exit
 * code != 0.//from  w w  w.  j ava  2  s . co m
 */
@Override
public void startUserApplication(DataWorkflowTask pTask) throws DataWorkflowProcessingException {
    //simply start the process...monitoring will be connected later
    File runningIndicator = getRunningIndicator(pTask);
    FileOutputStream fout = null;
    FileOutputStream ferr = null;
    File executablePath;

    try {
        executablePath = DataWorkflowHelper.getTaskMainExecutable(pTask);
        File executionBasePath = DataWorkflowHelper.getExecutionBasePath(pTask);
        File workingDirectory = DataWorkflowHelper.getTaskWorkingDirectory(executionBasePath);
        File tempDirectory = DataWorkflowHelper.getTaskTempDirectory(executionBasePath);
        File inputDirectory = DataWorkflowHelper.getTaskInputDirectory(executionBasePath);
        File outputDirectory = DataWorkflowHelper.getTaskOutputDirectory(executionBasePath);

        if (!executablePath.canExecute()) {
            LOGGER.debug("Executable at location {} seems not to be executable. Taking care of this...");
            if (executablePath.setExecutable(true)) {
                LOGGER.debug("Executable was successfully set to be executable.");
            } else {
                LOGGER.warn("Failed to set executable to be executable. Trying to continue.");
            }
        }

        String cmdLineString = executablePath.getAbsolutePath() + " "
                + pTask.getConfiguration().getApplicationArguments() + " " + pTask.getApplicationArguments();
        LOGGER.debug("Building up command array from string '{}'", cmdLineString);

        CommandLine cmdLine = CommandLine.parse(cmdLineString);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        Map<String, String> env = new HashMap<>();
        env.put("WORKING_DIR", workingDirectory.getAbsolutePath());
        env.put("TEMP_DIR", tempDirectory.getAbsolutePath());
        env.put("INPUT_DIR", inputDirectory.getAbsolutePath());
        env.put("OUTPUT_DIR", outputDirectory.getAbsolutePath());

        fout = new FileOutputStream(new File(tempDirectory, "stdout.log"));
        ferr = new FileOutputStream(new File(tempDirectory, "stderr.log"));
        LOGGER.debug("Setting stream handler for stdout and stderr.");
        executor.setStreamHandler(new PumpStreamHandler(fout, ferr));
        LOGGER.debug("Creating .RUNNING file for monitoring.");
        FileUtils.touch(runningIndicator);
        LOGGER.debug("Executing process.");
        int exitCode = executor.execute(cmdLine);
        if (exitCode != 0) {
            throw new DataWorkflowProcessingException(
                    "Execution returned exit code " + exitCode + ". See logfiles for details.");
        } else {
            LOGGER.debug("Process successfully finished with exit code {}", exitCode);
        }
    } catch (IOException | UnsupportedOperatingSystemException e) {
        throw new DataWorkflowProcessingException("Failed to start executable for task " + pTask.getId(), e);
    } finally {
        LOGGER.debug("Removing running indicator file {}", runningIndicator);
        FileUtils.deleteQuietly(runningIndicator);
        if (fout != null) {
            try {
                fout.close();
            } catch (IOException ex) {
            }
        }

        if (ferr != null) {
            try {
                ferr.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:com.github.seqware.queryengine.tutorial.PosterSGE.java

/**
 * <p>benchmark.</p>/* ww w.j  av a  2 s.  c  om*/
 *
 * @throws java.io.IOException if any.
 */
public void benchmark() throws IOException {
    if (args.length != 3) {
        System.err.println(args.length + " arguments found");
        System.out.println(
                PosterSGE.class.getSimpleName() + " <outputKeyValueFile> <input file dir> <simultaneous jobs>");
        System.exit(-1);
    }

    File outputFile = Utility.checkOutput(args[0]);

    // check if reference has been properly created
    Reference reference = SWQEFactory.getQueryInterface().getLatestAtomByRowKey("hg_19", Reference.class);
    if (reference == null) {
        SGID refID = ReferenceCreator.mainMethod(new String[] { HG_19 });
        reference = SWQEFactory.getQueryInterface().getAtomBySGID(Reference.class, refID);
    }

    // record reference, starting disk space
    keyValues.put("referenceID", reference.getSGID().getRowKey());
    recordSpace("start");
    Utility.writeKeyValueFile(outputFile, keyValues);
    // create new FeatureSet id and pass it onto our children
    CreateUpdateManager manager = SWQEFactory.getModelManager();
    FeatureSet initialFeatureSet = manager.buildFeatureSet().setReference(reference).build();
    manager.flush();

    int count = 0;
    // go through all input files
    File fileDirectory = new File(args[1]);
    File[] listFiles = fileDirectory.listFiles();

    // record start and finish time
    Date startDate = new Date();
    keyValues.put(count + "-start-date-long", Long.toString(startDate.getTime()));
    keyValues.put(count + "-start-date-human", startDate.toString());

    // submit all jobs in parallel via SGE
    StringBuilder jobNames = new StringBuilder();
    for (File inputFile : listFiles) {
        // run without unnecessary parameters
        String cargs = "-w VCFVariantImportWorker -i " + inputFile.getAbsolutePath() + " -b "
                + String.valueOf(BENCHMARKING_BATCH_SIZE) + " -f " + initialFeatureSet.getSGID().getRowKey()
                + " -r " + reference.getSGID().getRowKey();
        String command = "java -Xmx2048m -classpath " + System.getProperty("user.dir")
                + "/seqware-queryengine-0.12.0-full.jar com.github.seqware.queryengine.system.importers.SOFeatureImporter";
        command = command + " " + cargs;
        command = "qsub -q long -l h_vmem=3G -cwd -N dyuen-" + inputFile.getName() + " -b y " + command;

        jobNames.append("dyuen-").append(inputFile.getName()).append(",");
        System.out.println("Running: " + command);
        CommandLine cmdLine = CommandLine.parse(command);
        DefaultExecutor executor = new DefaultExecutor();
        int exitValue = executor.execute(cmdLine);
    }
    String jobs = jobNames.toString().substring(0, jobNames.length() - 1);

    // submit a job that just waits on all the preceding jobs for synchronization
    String command = "java -Xmx1024m -version";
    command = "qsub -cwd -N dyuen-wait -hold_jid " + jobs + " -b y -sync y " + command;
    System.out.println("Running wait: " + command);

    CommandLine cmdLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(null);
    int exitValue = executor.execute(cmdLine);

    FeatureSet fSet = SWQEFactory.getQueryInterface().getLatestAtomBySGID(initialFeatureSet.getSGID(),
            FeatureSet.class);
    keyValues.put(count + "-featuresSet-id", fSet.getSGID().getRowKey());
    keyValues.put(count + "-featuresSet-id-timestamp",
            Long.toString(fSet.getSGID().getBackendTimestamp().getTime()));

    //        // runs count query, touches everything but does not write
    //
    //        keyValues.put(count + "-start-count-date-long", Long.toString(System.currentTimeMillis()));
    //        long fsetcount = fSet.getCount();
    //        keyValues.put(count + "-features-loaded", Long.toString(fsetcount));
    //        keyValues.put(count + "-end-count-date-long", Long.toString(System.currentTimeMillis()));

    Date endDate = new Date();
    keyValues.put(count + "-end-date-long", Long.toString(endDate.getTime()));
    keyValues.put(count + "-end-date-human", endDate.toString());
    recordSpace(String.valueOf(count));
    Utility.writeKeyValueFile(outputFile, keyValues);
    count++;

}

From source file:com.blackducksoftware.tools.scmconnector.integrations.teamfoundation.TeamFoundationConnector.java

private int workspaceExists() {
    CommandLine command = CommandLine.parse(executable);

    command.addArgument("workspaces", false);
    command.addArgument("-server:" + server + "/" + collection, false);
    command.addArgument("-login:" + user + "," + password, false);

    int commandReturnStatus = 1;
    String commandOutput = null;//from  w ww.  j a va2s. com

    try {
        CommandResults results = commandLineExecutor.executeCommandForOutput(log, command,
                new File(getFinalSourceDirectory()));
        commandReturnStatus = results.getStatus();
        commandOutput = results.getOutput();

        if (commandOutput.contains(workspace)) {
            workspaceExists = true;
            log.info("The workspace exists");
        } else {
            workspaceExists = false;
            log.info("The workspace does not exist");
        }

    } catch (Exception e) {

        log.error("Failure executing TF Command: " + command.toString() + "; output: " + commandOutput);
        workspaceExists = false;
    }

    return commandReturnStatus;
}

From source file:com.blackducksoftware.tools.scmconnector.integrations.git.GitConnector.java

/**
 * Checkout or update from GIT./* ww  w  .jav a 2  s  .  com*/
 */
@Override
public int sync() {
    int exitStatus = -1;
    try {

        CommandLine command = CommandLine.parse(EXECUTABLE);

        String targetRepoParentPath = getFinalSourceDirectory();
        String targetRepoPath = addPathComponentToPath(targetRepoParentPath,
                getModuleNameFromURLGit(repositoryURL));

        File targetRepoParentDir = new File(targetRepoParentPath);
        File targetRepoDir = new File(targetRepoPath);

        boolean cloneExists = doesGitCloneExist(targetRepoDir);

        if (!cloneExists) {
            command.addArgument(GIT_COMMAND_CLONE);
            command.addArgument(repositoryURL);
            command.addArgument(targetRepoDir.getAbsolutePath());
            exitStatus = commandLineExecutor.executeCommand(log, command, targetRepoParentDir, "yes");
        } else {
            command.addArgument(GIT_COMMAND_PULL);
            exitStatus = commandLineExecutor.executeCommand(log, command, targetRepoDir, "yes");
        }

        if (branch != null) {
            gitCheckoutBranchShaOrPrefixedTag(branch);
        } else if (tag != null) {
            gitCheckoutTag(tag);
        } else if (sha != null) {
            gitCheckoutBranchShaOrPrefixedTag(sha);
        }

    } catch (Exception e) {
        log.error("Unable to perform sync: " + e.getMessage(), e);
        log.info("Cause: " + e.getCause());
        exitStatus = -1;
    }
    return exitStatus;

}

From source file:it.drwolf.ridire.utility.RIDIREReTagger.java

public String retagFile(File f) throws ExecuteException, IOException {
    // Map<String, File> map = new HashMap<String, File>();
    String fileIN = f.getAbsolutePath();
    String fileOut = f.getAbsolutePath() + ".iso";
    String posOld = f.getAbsolutePath() + ".iso.pos";
    String posNew = f.getAbsolutePath() + ".pos";
    // first convert from utf8 to iso8859-1
    CommandLine commandLine = CommandLine.parse("iconv");
    commandLine.addArgument("-c").addArgument("-s").addArgument("-f").addArgument("utf8").addArgument("-t")
            .addArgument("iso8859-1//TRANSLIT").addArgument("-o").addArgument(fileOut, false)
            .addArgument(fileIN, false);
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(RIDIREReTagger.TREETAGGER_TIMEOUT);
    executor.setWatchdog(watchdog);/*from w  ww.  j av  a2s.  c  o m*/
    int exitValue = executor.execute(commandLine);
    if (exitValue == 0) {
        // tag using latin1 and Baroni's tagset
        commandLine = CommandLine.parse(this.treeTaggerBin);
        commandLine.addArgument(fileOut, false);
        executor = new DefaultExecutor();
        executor.setExitValue(0);
        watchdog = new ExecuteWatchdog(RIDIREReTagger.TREETAGGER_TIMEOUT);
        executor.setWatchdog(watchdog);
        TreeTaggerLog treeTaggerLog = new TreeTaggerLog();
        PumpStreamHandler executeStreamHandler = new PumpStreamHandler(treeTaggerLog, null);
        executor.setStreamHandler(executeStreamHandler);
        int exitValue2 = executor.execute(commandLine);
        if (exitValue2 == 0) {
            // FileUtils.deleteQuietly(new File(fileOut));
            File posTagFile = new File(posOld);
            FileUtils.writeLines(posTagFile, treeTaggerLog.getLines());
        }
        // reconvert to utf8
        commandLine = CommandLine.parse("iconv");
        commandLine.addArgument("-s").addArgument("-f").addArgument("iso8859-1").addArgument("-t")
                .addArgument("utf8//TRANSLIT").addArgument("-o").addArgument(posNew, false)
                .addArgument(posOld, false);
        executor = new DefaultExecutor();
        watchdog = new ExecuteWatchdog(RIDIREReTagger.TREETAGGER_TIMEOUT);
        executor.setWatchdog(watchdog);
        int exitValue3 = executor.execute(commandLine);
        if (exitValue3 == 0) {
            // FileUtils.deleteQuietly(new File(f.getPath() + ".iso.pos"));
            return new File(posNew).getCanonicalPath();
        }
    }
    return null;
}

From source file:com.k42b3.sacmis.Sacmis.java

private void executeCommand() {
    out.setText("");

    try {/*from www.jav  a  2s.com*/
        // save file
        saveFile();

        CommandLine commandLine = CommandLine.parse(this.path + " " + this.args.getText());

        // set timeout
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);

        // create executor
        DefaultExecutor executor = new DefaultExecutor();

        executor.setExitValue(this.exitCode);

        this.baos = new ByteArrayOutputStream();

        this.baosErr = new ByteArrayOutputStream();

        if (this.writerStdIn) {
            this.bais = new ByteArrayInputStream(in.getText().getBytes());

            executor.setStreamHandler(new PumpStreamHandler(this.baos, this.baosErr, this.bais));
        } else {
            executor.setStreamHandler(new PumpStreamHandler(this.baos, this.baosErr));
        }

        executor.setWatchdog(watchdog);

        executor.execute(commandLine, new ExecuteResultHandler() {

            public void onProcessComplete(int e) {
                out.setText(baos.toString());
            }

            public void onProcessFailed(ExecuteException e) {
                out.setText(baosErr.toString());
            }

        });
    } catch (Exception e) {
        out.setText(e.getMessage());
    }
}

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

private void menuItem1ActionPerformed(ActionEvent e) {
    if (this.api == ModificationAPI.BUKKIT) {
        showBukkitIncompatibleFeature();
        return;//from  w w w. ja  v  a  2 s. 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:net.openbyte.gui.CreateProjectFrame.java

public void doOperations() {
    createProjectFolder();//from   w  w w  .  ja v  a2s  . c  o m
    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);
}