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: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";
    }//from   w  ww  . j a v  a  2 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:io.selendroid.standalone.android.impl.AbstractDevice.java

private void startLogging() {
    logoutput = new ByteArrayOutputStream();
    DefaultExecutor exec = new DefaultExecutor();
    exec.setStreamHandler(new PumpStreamHandler(logoutput));
    CommandLine command = adbCommand("logcat", "ResourceType:S", "dalvikvm:S", "Trace:S", "SurfaceFlinger:S",
            "StrictMode:S", "ExchangeService:S", "SVGAndroid:S", "skia:S", "LoaderManager:S",
            "ActivityThread:S", "-v", "time");
    log.info("starting logcat:");
    log.fine(command.toString());// w  ww .  j ava2 s .  co  m
    try {
        exec.execute(command, new DefaultExecuteResultHandler());
        logcatWatchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        exec.setWatchdog(logcatWatchdog);
    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
    }
}

From source file:Logi.GSeries.Service.LogiGSKService.java

public String execToString(String command) throws Exception {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine commandline = CommandLine.parse(command);
    DefaultExecutor exec = new DefaultExecutor();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    exec.setStreamHandler(streamHandler);
    exec.execute(commandline);/*  w w  w  .j ava 2s .c  o m*/
    return (outputStream.toString());
}

From source file:com.theoryinpractise.clojure.AbstractClojureCompilerMojo.java

protected void callClojureWith(ExecutionMode executionMode, File[] sourceDirectory, File outputDirectory,
        List<String> compileClasspathElements, String mainClass, String[] clojureArgs)
        throws MojoExecutionException {

    outputDirectory.mkdirs();//w  w w.j  a v a 2s .  com

    String classpath = manifestClasspath(sourceDirectory, outputDirectory, compileClasspathElements);

    final String javaExecutable = getJavaExecutable();
    getLog().debug("Java exectuable used:  " + javaExecutable);
    getLog().debug("Clojure manifest classpath: " + classpath);
    CommandLine cl = null;

    if (ExecutionMode.INTERACTIVE == executionMode && SystemUtils.IS_OS_WINDOWS
            && spawnInteractiveConsoleOnWindows) {
        Scanner sc = new Scanner(windowsConsole);
        Pattern pattern = Pattern.compile("\"[^\"]*\"|'[^']*'|[\\w'/]+");
        cl = new CommandLine(sc.findInLine(pattern));
        String param;
        while ((param = sc.findInLine(pattern)) != null) {
            cl.addArgument(param);
        }
        cl.addArgument(javaExecutable);
    } else {
        cl = new CommandLine(javaExecutable);
    }

    if (vmargs != null) {
        cl.addArguments(vmargs, false);
    }

    cl.addArgument("-Dclojure.compile.path=" + escapeFilePath(outputDirectory), false);

    if (warnOnReflection)
        cl.addArgument("-Dclojure.compile.warn-on-reflection=true");

    cl.addArguments(clojureOptions, false);

    cl.addArgument("-jar");
    File jar;
    if (prependClasses != null && prependClasses.size() > 0) {
        jar = createJar(classpath, prependClasses.get(0));
        cl.addArgument(jar.getAbsolutePath(), false);
        List<String> allButFirst = prependClasses.subList(1, prependClasses.size());
        cl.addArguments(allButFirst.toArray(new String[allButFirst.size()]));
        cl.addArgument(mainClass);
    } else {
        jar = createJar(classpath, mainClass);
        cl.addArgument(jar.getAbsolutePath(), false);
    }

    if (clojureArgs != null) {
        cl.addArguments(clojureArgs, false);
    }

    getLog().debug("Command line: " + cl.toString());

    Executor exec = new DefaultExecutor();
    Map<String, String> env = new HashMap<String, String>(System.getenv());
    //        env.put("path", ";");
    //        env.put("path", System.getProperty("java.home"));

    ExecuteStreamHandler handler = new PumpStreamHandler(System.out, System.err, System.in);
    exec.setStreamHandler(handler);
    exec.setWorkingDirectory(getWorkingDirectory());
    ShutdownHookProcessDestroyer destroyer = new ShutdownHookProcessDestroyer();
    exec.setProcessDestroyer(destroyer);

    int status;
    try {
        status = exec.execute(cl, env);
    } catch (ExecuteException e) {
        status = e.getExitValue();
    } catch (IOException e) {
        status = 1;
    }

    if (status != 0) {
        throw new MojoExecutionException("Clojure failed.");
    }

}

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

/** Runs ffmpeg -version */
@Override/*  w w w  .  j  av a 2  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.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/*from   w  w  w . j  a v a2 s . c o  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:com.virtualparadigm.packman.processor.JPackageManagerBU.java

public static boolean autorun(File autorunDir) {
    logger.info("PackageManager::autorun()");
    boolean status = true;

    if (autorunDir != null && autorunDir.isDirectory()) {
        File[] autorunFiles = autorunDir.listFiles();
        Arrays.sort(autorunFiles);
        String fileExtension = null;
        DefaultExecutor cmdExecutor = new DefaultExecutor();
        for (File autorunFile : autorunFiles) {
            if (!autorunFile.isDirectory()) {
                try {
                    fileExtension = FilenameUtils.getExtension(autorunFile.getAbsolutePath());
                    if (fileExtension != null) {
                        if (fileExtension.equalsIgnoreCase("bat") || fileExtension.equalsIgnoreCase("sh")) {
                            logger.info("  executing autorun file: " + autorunFile.getAbsolutePath());
                            cmdExecutor.execute(CommandLine.parse(autorunFile.getAbsolutePath()));
                        } else if (fileExtension.equalsIgnoreCase("sql")
                                || fileExtension.equalsIgnoreCase("ddl")) {
                            logger.info("  executing autorun file: " + autorunFile.getAbsolutePath());
                        } else if (fileExtension.equalsIgnoreCase("jar")) {
                            logger.info("  executing autorun file: " + autorunFile.getAbsolutePath());
                        }//from  w  ww.  j  av a2s  . c  o  m
                    }
                } catch (Exception e) {
                    logger.error("", e);
                    e.printStackTrace();
                }
            }
        }
    }
    return status;
}

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

/**
 * Define a GISBASE/LOCATION_NAME for the provided dem.
 *
 * @param operation Name used for the location on disk
 * @param dem File used to establish CRS and Bounds for the location
 * @return//from   w  w w  . ja  v a2 s. c o m
 * @throws Exception
 */
static File location(CoordinateReferenceSystem crs) throws Exception {
    String code = CRS.toSRS(crs, true);
    File geodb = new File(System.getProperty("user.home"), "grassdata");
    File location = Files.createTempDirectory(geodb.toPath(), code).toFile();
    KVP kvp = new KVP("geodb", geodb, "location", location);

    // grass70 + ' -c epsg:' + myepsg + ' -e ' + location_path
    CommandLine cmd = new CommandLine(EXEC);
    cmd.addArgument("-c");
    cmd.addArgument("epsg:" + code);
    cmd.addArgument("-e");
    cmd.addArgument("${location}");
    cmd.setSubstitutionMap(kvp);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setWatchdog(new ExecuteWatchdog(60000));
    executor.setStreamHandler(new PumpStreamHandler(System.out));

    int exitValue = executor.execute(cmd);
    return location;
}

From source file:com.tibco.tgdb.test.lib.TGAdmin.java

/**
 * Invoke TG admin synchronously. /*from   ww  w .  ja v  a 2s . com*/
 * Admin operation blocks until it is completed.
 * 
 * @param tgHome TG admin home
 * @param url Url to connect to TG server
 * @param user System User name
 * @param pwd System User password
 * @param logFile TG admin log file location - Generated by admin
 * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire
 * @param cmd TG admin command file or command string
 * @param memSize Specify the maximum memory usage (MB). -1 for default (8 MB)
 * @param timeout Number of milliseconds allowed to complete admin operation
 * 
 * @return Output console of admin operation 
 * @throws TGAdminException Admin execution fails or timeout occurs 
 */
public static String invoke(String tgHome, String url, String user, String pwd, String logFile, String logLevel,
        String cmd, int memSize, long timeout) throws TGAdminException {
    if (tgHome == null)
        throw new TGAdminException("TGAdmin - TGDB home is not defined");
    File ftgHome = new File(tgHome);
    if (!ftgHome.exists())
        throw new TGAdminException("TGAdmin - TGDB home '" + tgHome + "' does not exist");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    Executor tgExec = new DefaultExecutor();
    tgExec.setStreamHandler(psh);
    tgExec.setWorkingDirectory(new File(tgHome + "/bin"));

    CommandLine tgCL = new CommandLine((new File(tgHome + "/bin/" + process)).getAbsolutePath());

    // Define arguments
    List<String> args = new ArrayList<String>();
    if (url != null) {
        args.add("--url");
        args.add(url);
    }
    if (user != null) {
        args.add("--uid");
        args.add(user);
    }
    if (pwd != null) {
        args.add("--pwd");
        args.add(pwd);
    }
    if (logFile != null) {
        args.add("--log");
        args.add(logFile);
    }
    if (logLevel != null) {
        args.add("--log-level");
        args.add(logLevel);
    }
    if (memSize >= 0) {
        args.add("--max-memory");
        args.add(Integer.toString(memSize));
    }

    File cmdFile = null;
    if (cmd == null)
        throw new TGAdminException("TGAdmin - Command is required.");
    if (cmd.matches(
            "(?s)^(kill|show|describe|create|stop|info|checkpoint|dump|set|connect|disconnect|export|import|exit).*$")) {
        try {
            cmdFile = new File(tgHome + "/invokeAdminScript.txt");
            Files.write(Paths.get(cmdFile.toURI()), cmd.getBytes(StandardCharsets.UTF_8));
        } catch (IOException ioe) {
            throw new TGAdminException("TGAdmin - " + ioe.getMessage());
        }
    } else {
        cmdFile = new File(cmd);
    }

    if (!cmdFile.exists()) {
        throw new TGAdminException("TGAdmin - Command file '" + cmdFile + "' does not exist");
    }
    args.add("--file");
    args.add(cmdFile.getAbsolutePath());

    tgCL.addArguments((String[]) args.toArray(new String[args.size()]));

    ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout);
    tgExec.setWatchdog(tgWatch);
    System.out.println("TGAdmin - Invoking " + StringUtils.toString(tgCL.toStrings(), " "));

    long endProcTime = 0;
    long totalProcTime = 0;
    try {
        TGAdmin.startProcTime = System.currentTimeMillis();
        tgExec.execute(tgCL);
        endProcTime = System.currentTimeMillis();
    } catch (IOException ee) {
        if (tgWatch.killedProcess())
            throw new TGAdminException("TGAdmin - Operation did not complete within " + timeout + " ms",
                    output.toString());
        else {
            try {
                Thread.sleep(1000); // make sure output has time to fill up
            } catch (InterruptedException ie) {
                ;
            }
            throw new TGAdminException("TGAdmin - Execution failed: " + ee.getMessage(), output.toString());
        }
    }
    if (url != null && !output.toString().contains("Successfully connected to server"))
        throw new TGAdminException("TGAdmin - Admin could not connect to server " + url + " with user " + user,
                output.toString());
    if (endProcTime != 0)
        totalProcTime = endProcTime - TGAdmin.startProcTime;
    if (TGAdmin.showOperationBanner)
        System.out.println(
                "TGAdmin - Operation completed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));
    return output.toString();
}

From source file:edu.isi.misd.scanner.network.registry.data.service.RegistryServiceImpl.java

@Override
public String convertDataProcessingSpecification(String workingDir, String execName, String args, String input,
        Integer dataSetId) throws Exception {
    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(new File(workingDir));
    CommandLine cl = new CommandLine(execName);
    cl.addArgument(args);/*  w  ww .  j  a va  2s  . c  o  m*/

    ByteArrayInputStream in = new ByteArrayInputStream(input.getBytes("UTF-8"));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayOutputStream err = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(out, err, in);
    exec.setStreamHandler(streamHandler);

    try {
        exec.execute(cl);
    } catch (Exception e) {
        throw new Exception(e.toString() + "\n\n" + err.toString("UTF-8"));
    }
    String output = out.toString("UTF-8");

    if (dataSetId != null) {
        DataSetDefinition dataSet = dataSetDefinitionRepository.findOne(dataSetId);

        if (dataSet == null) {
            throw new ResourceNotFoundException(dataSetId);
        }
        dataSet.setDataProcessingSpecification(input);
        dataSet.setDataProcessingProgram(output);
        dataSetDefinitionRepository.save(dataSet);
    }
    return output;
}