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

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

Introduction

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

Prototype

public CommandLine(final CommandLine other) 

Source Link

Document

Copy constructor.

Usage

From source file:com.alibaba.jstorm.utils.JStormUtils.java

/**
 * If it is backend, please set resultHandler, such as DefaultExecuteResultHandler If it is frontend, ByteArrayOutputStream.toString get the result
 * <p/>//w w w.  j  av a2s.  com
 * This function don't care whether the command is successfully or not
 * 
 * @param command
 * @param environment
 * @param workDir
 * @param resultHandler
 * @return
 * @throws IOException
 */
public static ByteArrayOutputStream launchProcess(String command, final Map environment, final String workDir,
        ExecuteResultHandler resultHandler) throws IOException {

    String[] cmdlist = command.split(" ");

    CommandLine cmd = new CommandLine(cmdlist[0]);
    for (String cmdItem : cmdlist) {
        if (StringUtils.isBlank(cmdItem) == false) {
            cmd.addArgument(cmdItem);
        }
    }

    DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);
    if (StringUtils.isBlank(workDir) == false) {
        executor.setWorkingDirectory(new File(workDir));
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    PumpStreamHandler streamHandler = new PumpStreamHandler(out, out);
    if (streamHandler != null) {
        executor.setStreamHandler(streamHandler);
    }

    try {
        if (resultHandler == null) {
            executor.execute(cmd, environment);
        } else {
            executor.execute(cmd, environment, resultHandler);
        }
    } catch (ExecuteException e) {

        // @@@@
        // failed to run command
    }

    return out;

}

From source file:ddf.content.plugin.video.VideoThumbnailPlugin.java

private CommandLine getFFmpegCreateAnimatedGifCommand() {
    final String framerateFlag = "-framerate";
    final String framerate = "1";
    final String loopFlag = "-loop";
    final String loopValue = "0";

    return new CommandLine(ffmpegPath).addArgument(SUPPRESS_PRINTING_BANNER_FLAG).addArgument(framerateFlag)
            .addArgument(framerate).addArgument(INPUT_FILE_FLAG)
            .addArgument(getThumbnailFilePath(), DONT_HANDLE_QUOTING).addArgument(loopFlag)
            .addArgument(loopValue).addArgument(getGifFilePath(), DONT_HANDLE_QUOTING)
            .addArgument(OVERWRITE_EXISTING_FILE_FLAG);
}

From source file:io.selendroid.android.impl.AbstractDevice.java

private CommandLine adbCommand() {
    CommandLine command = new CommandLine(AndroidSdk.adb());
    if (isSerialConfigured()) {
        command.addArgument("-s", false);
        command.addArgument(serial, false);
    }/*from  w ww  .j  a  va  2 s .  c  o m*/
    return command;
}

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

private void executeCQPQuery(File queryFile, boolean inverse) throws ExecuteException, IOException {
    Executor executor = new DefaultExecutor();
    File tempSh = File.createTempFile("ridireSH", ".sh");
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("export LC_ALL=C\n");
    String corpusName = this.cqpCorpusName;
    if (inverse) {
        corpusName += "INV";
    }//  w  w w . jav a2  s  .c  om
    stringBuffer.append(this.cqpExecutable + " -f " + queryFile.getAbsolutePath() + " -D " + corpusName + " -r "
            + this.cqpRegistry + "\n");
    FileUtils.writeStringToFile(tempSh, stringBuffer.toString());
    tempSh.setExecutable(true);
    CommandLine commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    FileUtils.deleteQuietly(tempSh);
}

From source file:com.github.cshubhamrao.MediaConverter.MainUI.java

/** Runs ffmpeg -version */
@Override//from   w  w  w .  j  ava2 s .  com
protected Void doInBackground() {
    ffmpeg = FFMpegLoader.getFFMpegExecutable();
    if (ffmpeg != null) {
        try {
            cmd = new CommandLine(ffmpeg);
            cmd.addArgument("-version");
            OutputStream outputStream = new ByteArrayOutputStream();
            DefaultExecutor exec = new DefaultExecutor();
            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
            exec.setStreamHandler(streamHandler);
            ExecuteWatchdog watchdog = new ExecuteWatchdog(10000);
            exec.setWatchdog(watchdog);
            exec.execute(cmd);
            publish(outputStream.toString());
        } catch (ExecuteException ex) {
            Logger.getLogger(DisplayVersion.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DisplayVersion.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(DisplayVersion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return null;
}

From source file:com.tupilabs.pbs.PBS.java

/**
 * PBS qsub command./* ww  w  . j a v a  2  s .  c o  m*/
 * <p>
 * Equivalent to qsub [param]
 *
 * @param inputs job input file
 * @param environment environment variables
 * @return job id
 */
public static String qsub(String[] inputs, Map<String, String> environment) {
    final CommandLine cmdLine = new CommandLine(COMMAND_QSUB);
    for (int i = 0; i < inputs.length; ++i) {
        cmdLine.addArgument(inputs[i]);
    }

    final OutputStream out = new ByteArrayOutputStream();
    final OutputStream err = new ByteArrayOutputStream();

    DefaultExecuteResultHandler resultHandler;
    try {
        resultHandler = execute(cmdLine, environment, out, err);
        resultHandler.waitFor(DEFAULT_TIMEOUT);
    } catch (ExecuteException e) {
        throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
    } catch (InterruptedException e) {
        throw new PBSException("Failed to execute qsub command: " + e.getMessage(), e);
    }

    final int exitValue = resultHandler.getExitValue();
    LOGGER.info("qsub exit value: " + exitValue);
    LOGGER.fine("qsub output: " + out.toString());

    if (exitValue != 0) {
        throw new PBSException("Failed to submit job script with command line '" + cmdLine.toString()
                + "'. Error output: " + err.toString());
    }

    String jobId = out.toString();
    return jobId.trim();
}

From source file:io.selendroid.android.impl.DefaultAndroidEmulator.java

private void allAppsGridView() throws AndroidDeviceException {
    String[] dimensions = screenSize.split("x");
    int x = Integer.parseInt(dimensions[0]);
    int y = Integer.parseInt(dimensions[1]);
    if (x > y) {
        y = y / 2;/*from w  w  w.java2  s.  c om*/
        x = x - 30;
    } else {
        x = x / 2;
        y = y - 30;
    }

    List<String> coordinates = new ArrayList<String>();
    coordinates.add("3 0 " + x);
    coordinates.add("3 1 " + y);
    coordinates.add("1 330 1");
    coordinates.add("0 0 0");
    coordinates.add("1 330 0");
    coordinates.add("0 0 0");

    for (String coordinate : coordinates) {
        CommandLine event1 = new CommandLine(AndroidSdk.adb());
        if (isSerialConfigured()) {
            event1.addArgument("-s", false);
            event1.addArgument(serial, false);
        }
        event1.addArgument("shell", false);
        event1.addArgument("sendevent", false);
        event1.addArgument("dev/input/event0", false);
        event1.addArgument(coordinate, false);
        try {
            ShellCommand.exec(event1);
        } catch (ShellCommandException e) {
            throw new AndroidDeviceException(e);
        }
    }

    try {
        Thread.sleep(750);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.boundlessgeo.wps.grass.GrassProcesses.java

/**
 * Define a GISBASE/LOCATION_NAME/PERMANENT for the provided dem.
 *
 * The dem is staged in GISBASE/dem.tif and then moved to
 * GISBASE/LOCATION_NAME/PERMANENT/dem.tif
 *
 * @param operation/*w ww  . j ava 2s  . co m*/
 *            Name used for the location on disk
 * @param dem
 *            File used to establish CRS and Bounds for the location
 * @return Array of files consisting of {GISBASE, LOCATION, MAPSET, dem.tif}
 * @throws Exception
 */
static File[] location(String operation, GridCoverage2D dem) throws Exception {
    File geodb = new File(System.getProperty("user.home"), "grassdata");
    //File location = Files.createTempDirectory(geodb.toPath(),operation).toFile();
    File location = new File(geodb, operation);
    File mapset = new File(location, "PERMANENT");
    File file = new File(geodb, "dem.tif");

    final GeoTiffFormat format = new GeoTiffFormat();
    GridCoverageWriter writer = format.getWriter(file);
    writer.write(dem, null);
    System.out.println("Staging file:" + file);

    // grass70 + ' -c ' + myfile + ' -e ' + location_path
    CommandLine cmd = new CommandLine(EXEC);
    cmd.addArgument("-c");
    cmd.addArgument("${file}");
    cmd.addArgument("-e");
    cmd.addArgument("${location}");
    cmd.setSubstitutionMap(new KVP("file", file, "location", location));
    LOGGER.info(cmd.toString());

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(new PumpStreamHandler(System.out));
    int exitValue = executor.execute(cmd);

    File origional = file;
    file = new File(mapset, file.getName());
    Files.move(origional.toPath(), file.toPath());
    return new File[] { geodb, location, mapset, file };
}

From source file:info.pancancer.arch3.worker.WorkerRunnable.java

/**
 * This function will execute a workflow, based on the content of the Job object that is passed in.
 *
 * @param message/*from www  .  j a  va 2 s.  c  o  m*/
 *            - The message that will be published on the queue when the worker starts running the job.
 * @param job
 *            - The job contains information about what workflow to execute, and how.
 * @return The complete stdout and stderr from the workflow execution will be returned.
 */
private WorkflowResult launchJob(String message, Job job, String seqwareEngine, String seqwareSettingsFile,
        String dockerImage) {
    WorkflowResult workflowResult = null;
    ExecutorService exService = Executors.newFixedThreadPool(2);
    WorkflowRunner workflowRunner = new WorkflowRunner();
    try {

        Path pathToINI = writeINIFile(job);
        resultsChannel.basicPublish(this.resultsQueueName, this.resultsQueueName,
                MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes(StandardCharsets.UTF_8));
        resultsChannel.waitForConfirms();

        //TODO: Parameterize dockerImage
        if (dockerImage == null || dockerImage.trim() == null) {
            dockerImage = "pancancer/seqware_whitestar_pancancer:latest";
        }
        CommandLine cli = new CommandLine("docker");
        cli.addArgument("run");
        List<String> args = new ArrayList<>(
                Arrays.asList("--rm", "-h", "master", "-t", "-v", "/var/run/docker.sock:/var/run/docker.sock",
                        "-v", job.getWorkflowPath() + ":/workflow", "-v", pathToINI + ":/ini", "-v",
                        "/datastore:/datastore", "-v", "/home/" + this.userName + "/.gnos:/home/ubuntu/.gnos"));
        if (seqwareSettingsFile != null) {
            args.addAll(Arrays.asList("-v", seqwareSettingsFile + ":/home/seqware/.seqware/settings"));
        }
        args.addAll(Arrays.asList(dockerImage, "seqware", "bundle", "launch", "--dir", "/workflow", "--ini",
                "/ini", "--no-metadata", "--engine", seqwareEngine));

        String[] argsArray = new String[args.size()];
        cli.addArguments(args.toArray(argsArray));

        WorkerHeartbeat heartbeat = new WorkerHeartbeat();
        heartbeat.setQueueName(this.resultsQueueName);
        // channels should not be shared between threads https://www.rabbitmq.com/api-guide.html#channel-threads
        // heartbeat.setReportingChannel(resultsChannel);
        heartbeat.setSettings(settings);
        heartbeat.setSecondsDelay(
                settings.getDouble(Constants.WORKER_HEARTBEAT_RATE, WorkerHeartbeat.DEFAULT_DELAY));
        heartbeat.setJobUuid(job.getUuid());
        heartbeat.setVmUuid(this.vmUuid);
        heartbeat.setNetworkID(this.networkAddress);
        heartbeat.setStatusSource(workflowRunner);

        long presleep = settings.getLong(Constants.WORKER_PREWORKER_SLEEP, WorkerRunnable.DEFAULT_PRESLEEP);
        long postsleep = settings.getLong(Constants.WORKER_POSTWORKER_SLEEP, WorkerRunnable.DEFAULT_POSTSLEEP);
        long presleepMillis = Base.ONE_SECOND_IN_MILLISECONDS * presleep;
        long postsleepMillis = Base.ONE_SECOND_IN_MILLISECONDS * postsleep;

        workflowRunner.setCli(cli);
        workflowRunner.setPreworkDelay(presleepMillis);
        workflowRunner.setPostworkDelay(postsleepMillis);
        // Submit both
        @SuppressWarnings("unused")
        // We will never actually do submit.get(), because the heartbeat should keep running until it is terminated by
        // exService.shutdownNow().
        Future<?> submit = exService.submit(heartbeat);
        Future<WorkflowResult> workflowResultFuture = exService.submit(workflowRunner);
        // make sure both are complete
        workflowResult = workflowResultFuture.get();
        // don't get the heartbeat if the workflow is complete already

        log.info("Docker execution result: " + workflowResult.getWorkflowStdout());
    } catch (SocketException e) {
        // This comes from trying to get the IP address.
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        // This could be caused by a problem writing the file, or publishing a message to the queue.
        log.error(e.getMessage(), e);
    } catch (ExecutionException e) {
        log.error("Error executing workflow: " + e.getMessage(), e);
    } catch (InterruptedException e) {
        log.error("Workflow may have been interrupted: " + e.getMessage(), e);
    } finally {
        exService.shutdownNow();
    }

    return workflowResult;
}

From source file:io.selendroid.standalone.android.impl.DefaultAndroidEmulator.java

private CommandLine getAdbCommand() {
    CommandLine processListCommand = new CommandLine(AndroidSdk.adb());
    if (isSerialConfigured()) {
        processListCommand.addArgument("-s", false);
        processListCommand.addArgument(serial, false);
    }//from  www .  jav  a2  s.  co  m
    return processListCommand;
}