Example usage for org.apache.commons.exec Executor setWorkingDirectory

List of usage examples for org.apache.commons.exec Executor setWorkingDirectory

Introduction

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

Prototype

void setWorkingDirectory(File dir);

Source Link

Document

Set the working directory of the created process.

Usage

From source file:name.martingeisse.webide.features.verilog.simulator.VerilogSimulatorMenuDelegate.java

@Override
public void invoke(final Object context, final List<ResourceHandle> anchor, final Object parameter) {

    // check anchor
    logger.trace("VerilogSimulatorMenuDelegate invoked...");
    if (anchor.isEmpty()) {
        logger.trace("empty anchor (no file selected for simulation)");
        return;//from  w w w .  ja v a2s  .c  om
    }
    final ResourceHandle inputFile = anchor.get(0);

    // make sure the anchor element is a file
    if (!inputFile.isFile()) {
        logger.trace("selected anchor is not a file");
        return;
    }
    logger.trace("selected file for simulation: " + inputFile.getPath());

    // catch exceptions to cleanly de-allocate the temporary folder
    TemporaryFolder temporaryFolder = null;
    try {

        // allocate a temporary folder for the output files
        temporaryFolder = new TemporaryFolder();
        logger.trace("allocation temporary folder: " + temporaryFolder.getInstanceFolder());

        // build the command line
        final CommandLine commandLine = new CommandLine(Configuration.getBashPath());
        commandLine.addArgument("--login");
        commandLine.addArgument("-c");
        commandLine.addArgument("vvp " + Configuration.getStdinPath(), false);
        logger.trace("command line: " + commandLine);

        // build I/O streams
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(inputFile.readBinaryFile(true));
        final ByteArrayOutputStream outputStream = null;
        final OutputStream errorStream = System.err;
        final ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream,
                inputStream);

        // run Icarus
        final Executor executor = new DefaultExecutor();
        executor.setStreamHandler(streamHandler);
        executor.setWorkingDirectory(temporaryFolder.getInstanceFolder());
        executor.execute(commandLine);
        logger.trace("VVP finished");

        // create the output files
        final ResourceHandle outputFolder = inputFile.getParent();
        logger.trace("creating output files in folder: " + outputFolder);
        for (final File temporaryFile : temporaryFolder.getInstanceFolder().listFiles()) {
            if (temporaryFile.isFile()) {
                final ResourceHandle outputFile = outputFolder.getChild(temporaryFile.getName());
                logger.trace("creating output file " + outputFile + " from " + temporaryFile);
                outputFile.writeFile(temporaryFile, true, true);
                logger.trace("output file created");
            } else {
                logger.trace("skipping (not a file): " + temporaryFile);
            }
        }
        logger.trace("output files created");

    } catch (final IOException e) {
        logger.error("exception during VVP simulation", e);
        return;
    } finally {
        if (temporaryFolder != null) {
            temporaryFolder.dispose();
        }
    }

}

From source file:name.martingeisse.webide.nodejs.AbstractNodejsServer.java

/**
 * Starts this server.//from  ww  w. j a va 2  s .  c o m
 */
public void start() {

    // determine the path of the associated script
    URL url = getScriptUrl();
    if (!url.getProtocol().equals("file")) {
        throw new RuntimeException("unsupported protocol for associated script URL: " + url);
    }
    File scriptFile = new File(url.getPath());

    // build the command line
    CommandLine commandLine = new CommandLine(Configuration.getBashPath());
    commandLine.addArgument("--login");
    commandLine.addArgument("-c");
    commandLine.addArgument("node " + scriptFile.getName(), false);

    // build I/O streams
    ByteArrayInputStream inputStream = null;
    OutputStream outputStream = System.err;
    OutputStream errorStream = System.err;
    ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream, inputStream);

    // build an environment map that contains the path to the node_modules
    Map<String, String> environment = new HashMap<String, String>();
    environment.put("NODE_PATH", new File("lib/node_modules").getAbsolutePath());

    // run Node.js
    Executor executor = new DefaultExecutor();
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    executor.setStreamHandler(streamHandler);
    try {
        executor.setWorkingDirectory(scriptFile.getParentFile());
        executor.execute(commandLine, environment, new ExecuteResultHandler() {

            @Override
            public void onProcessFailed(ExecuteException e) {
            }

            @Override
            public void onProcessComplete(int exitValue) {
            }

        });
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:com.adaptris.core.services.system.DefaultCommandBuilder.java

public Executor configure(Executor exe) {
    if (!isEmpty(getWorkingDirectory())) {
        File wd = new File(getWorkingDirectory());
        exe.setWorkingDirectory(wd);
    }/*  www  . ja v  a 2 s.  c  om*/
    exe.setExitValue(successExitValue());
    return exe;
}

From source file:name.martingeisse.webide.process.NodejsCompanionProcess.java

@Override
protected void configureExecutor(Executor executor) {
    super.configureExecutor(executor);
    ByteArrayInputStream inputStream = null;
    OutputStream outputStream = System.err;
    OutputStream errorStream = System.err;
    executor.setStreamHandler(new PumpStreamHandler(outputStream, errorStream, inputStream));
    executor.setWorkingDirectory(mainFile.getParentFile());
}

From source file:hr.fer.zemris.vhdllab.service.impl.GhdlSimulator.java

private List<String> executeProcess(CommandLine cl, java.io.File tempDirectory)
        throws ExecuteException, IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Executing process: " + cl.toString());
    }//from  w ww  . j a v  a2  s.c om

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ExecuteStreamHandler handler = new PumpStreamHandler(bos);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(PROCESS_TIMEOUT);
    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(tempDirectory);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(handler);
    /*
     * It seems that when ExecuteWatchdog terminates process by invoking
     * destroy method, process terminates with exit code 143. And since we
     * manually ask watchdog if he killed the process, exit code 143 is
     * marked as successful (just so our code can be executed).
     * 
     * Exit code 1 in case of compilation error(s).
     */
    executor.setExitValues(new int[] { 0, 1, 143 });
    try {
        executor.execute(cl);
    } catch (ExecuteException e) {
        LOG.warn("Process output dump:\n" + bos.toString());
        throw e;
    }

    if (watchdog.killedProcess()) {
        throw new SimulatorTimeoutException(PROCESS_TIMEOUT);
    }
    String output;
    try {
        output = bos.toString(IOUtil.DEFAULT_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw new UnhandledException(e);
    }
    if (StringUtils.isBlank(output)) {
        return Collections.emptyList();
    }
    return Arrays.asList(StringUtil.splitToNewLines(output));
}

From source file:cc.arduino.contributions.packages.ContributionInstaller.java

private void executeScripts(File folder, Collection<File> postInstallScripts, boolean trusted, boolean trustAll)
        throws IOException {
    File script = postInstallScripts.iterator().next();

    if (!trusted && !trustAll) {
        System.err.println(//from  www.j  a  v a  2s.c o  m
                I18n.format(tr("Warning: non trusted contribution, skipping script execution ({0})"), script));
        return;
    }

    if (trustAll) {
        System.err.println(I18n.format(tr("Warning: forced untrusted script execution ({0})"), script));
    }

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(stdout, stderr));
    executor.setWorkingDirectory(folder);
    executor.setExitValues(null);
    int exitValue = executor.execute(new CommandLine(script));
    executor.setExitValues(new int[0]);

    System.out.write(stdout.toByteArray());
    System.err.write(stderr.toByteArray());

    if (executor.isFailure(exitValue)) {
        throw new IOException();
    }
}

From source file:com.github.stephenc.mongodb.maven.StartMongoMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {/*from  w w  w  .  j a v a2s .co  m*/
        getLog().info("Skipping mongodb: mongodb.skip==true");
        return;
    }
    if (installation == null) {
        getLog().info("Using mongod from PATH");
    } else {
        getLog().info("Using mongod installed in " + installation);
    }
    getLog().info("Using database root of " + databaseRoot);
    final Logger mongoLogger = Logger.getLogger("com.mongodb");
    Level mongoLevel = mongoLogger.getLevel();
    try {
        mongoLogger.setLevel(Level.SEVERE);
        MongoOptions opts = new MongoOptions();
        opts.autoConnectRetry = false;
        opts.connectionsPerHost = 1;
        opts.connectTimeout = 50;
        opts.socketTimeout = 50;
        Mongo instance;
        try {
            instance = new Mongo(new ServerAddress("localhost", port), opts);
            List<String> databaseNames = instance.getDatabaseNames();
            throw new MojoExecutionException("Port " + port
                    + " is already running a MongoDb instance with the following databases " + databaseNames);
        } catch (MongoException.Network e) {
            // fine... no instance running
        } catch (MongoException e) {
            throw new MojoExecutionException("Port " + port + " is already running a MongoDb instance");
        } catch (UnknownHostException e) {
            // ignore... localhost is always known!
        }
    } finally {
        mongoLogger.setLevel(mongoLevel);
    }

    CommandLine commandLine = null;
    if (installation != null && installation.isDirectory()) {
        File bin = new File(installation, "bin");
        File exe = new File(bin, Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod");
        if (exe.isFile()) {
            commandLine = new CommandLine(exe);
        } else {
            throw new MojoExecutionException("Could not find mongo executables in specified installation: "
                    + installation + " expected to find " + exe + " but it does not exist.");
        }
    }
    if (commandLine == null) {
        commandLine = new CommandLine(Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod");
    }
    if (databaseRoot.isFile()) {
        throw new MojoExecutionException("Database root " + databaseRoot + " is a file and not a directory");
    }
    if (databaseRoot.isDirectory() && cleanDatabaseRoot) {
        getLog().info("Cleaning database root directory: " + databaseRoot);
        try {
            FileUtils.deleteDirectory(databaseRoot);
        } catch (IOException e) {
            throw new MojoExecutionException("Could not clean database root directory " + databaseRoot, e);
        }
    }
    if (!databaseRoot.isDirectory()) {
        getLog().debug("Creating database root directory: " + databaseRoot);
        if (!databaseRoot.mkdirs()) {
            throw new MojoExecutionException("Could not create database root directory " + databaseRoot);
        }
    }

    if (!verbose) {
        commandLine.addArgument("--quiet");
    }

    commandLine.addArgument("--logpath");
    commandLine.addArgument(logPath.getAbsolutePath());
    if (logAppend) {
        commandLine.addArgument("--logappend");
    }

    commandLine.addArgument(auth ? "--auth" : "--noauth");

    commandLine.addArgument("--port");
    commandLine.addArgument(Integer.toString(port));

    commandLine.addArgument("--dbpath");
    commandLine.addArgument(databaseRoot.getAbsolutePath());

    if (additionalArguments != null) {
        for (String aa : additionalArguments) {
            commandLine.addArgument(aa);
        }
    }

    Executor exec = new DefaultExecutor();
    DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler();
    exec.setWorkingDirectory(databaseRoot);
    ProcessObserver processObserver = new ProcessObserver(new ShutdownHookProcessDestroyer());
    exec.setProcessDestroyer(processObserver);

    LogOutputStream stdout = new MavenLogOutputStream(getLog());
    LogOutputStream stderr = new MavenLogOutputStream(getLog());

    getLog().info("Executing command line: " + commandLine);
    exec.setStreamHandler(new PumpStreamHandler(stdout, stderr));
    try {
        exec.execute(commandLine, execHandler);
        getLog().info("Waiting for MongoDB to start...");
        long timeout = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(120);
        mongoLevel = mongoLogger.getLevel();
        try {
            mongoLogger.setLevel(Level.SEVERE);
            while (System.currentTimeMillis() < timeout && !execHandler.hasResult()) {
                MongoOptions opts = new MongoOptions();
                opts.autoConnectRetry = false;
                opts.connectionsPerHost = 1;
                opts.connectTimeout = 250;
                opts.socketTimeout = 250;
                Mongo instance;
                try {
                    instance = new Mongo(new ServerAddress("localhost", port), opts);
                    List<String> databaseNames = instance.getDatabaseNames();
                    getLog().info("MongoDb started.");
                    getLog().info("Databases: " + databaseNames);
                } catch (MongoException.Network e) {
                    // ignore, wait and try again
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e1) {
                        // ignore
                    }
                    continue;
                } catch (MongoException e) {
                    getLog().info("MongoDb started.");
                    getLog().info("Unable to list databases due to " + e.getMessage());
                }
                break;
            }
        } finally {
            mongoLogger.setLevel(mongoLevel);
        }
        if (execHandler.hasResult()) {
            ExecuteException exception = execHandler.getException();
            if (exception != null) {
                throw new MojoFailureException(exception.getMessage(), exception);
            }
            throw new MojoFailureException(
                    "Command " + commandLine + " exited with exit code " + execHandler.getExitValue());
        }
        Map pluginContext = session.getPluginContext(getPluginDescriptor(), project);
        pluginContext.put(ProcessObserver.class.getName() + ":" + Integer.toString(port), processObserver);
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

}

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 w w  .  j a  v  a  2 s . 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;
}

From source file:net.hasor.maven.ExecMojo.java

/**
 * priority in the execute method will be to use System properties arguments over the pom specification.
 *
 * @throws MojoExecutionException if a failure happens
 *///from   w w  w  .j  a v  a2s. com
public void execute() throws MojoExecutionException {
    if (isSkip()) {
        getLog().info("skipping execute as per configuraion");
        return;
    }
    if (basedir == null) {
        throw new IllegalStateException("basedir is null. Should not be possible.");
    }
    try {
        handleWorkingDirectory();
        String argsProp = getSystemProperty("exec.args");
        List<String> commandArguments = new ArrayList<String>();
        if (hasCommandlineArgs()) {
            handleCommandLineArgs(commandArguments);
        } else if (!StringUtils.isEmpty(argsProp)) {
            handleSystemPropertyArguments(argsProp, commandArguments);
        } else {
            if (arguments != null) {
                handleArguments(commandArguments);
            }
        }
        Map<String, String> enviro = handleSystemEnvVariables();
        CommandLine commandLine = getExecutablePath(enviro, workingDirectory);
        String[] args = commandArguments.toArray(new String[commandArguments.size()]);
        commandLine.addArguments(args, false);
        Executor exec = new DefaultExecutor();
        exec.setWorkingDirectory(workingDirectory);
        fillSuccessCodes(exec);
        getLog().debug("Executing command line: " + commandLine);
        try {
            int resultCode;
            if (outputFile != null) {
                if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) {
                    getLog().warn(
                            "Could not create non existing parent directories for log file: " + outputFile);
                }
                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(outputFile);
                    resultCode = executeCommandLine(exec, commandLine, enviro, outputStream);
                } finally {
                    IOUtil.close(outputStream);
                }
            } else {
                resultCode = executeCommandLine(exec, commandLine, enviro, System.out, System.err);
            }
            if (isResultCodeAFailure(resultCode)) {
                throw new MojoExecutionException(
                        "Result of " + commandLine + " execution is: '" + resultCode + "'.");
            }
        } catch (ExecuteException e) {
            throw new MojoExecutionException("Command execution failed.", e);
        } catch (IOException e) {
            throw new MojoExecutionException("Command execution failed.", e);
        }
        registerSourceRoots();
    } catch (IOException e) {
        throw new MojoExecutionException("I/O Error", e);
    }
}

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

/**
 * Invoke TG admin synchronously. //from   w  w w .ja  v  a 2  s .c om
 * Admin operation blocks until it is completed.
 * 
 * @param url Url to connect to TG server
 * @param user User name
 * @param pwd 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 cmdFile TG admin command file - Need to exist before invoking admin
 * @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 String invoke(String url, String user, String pwd, String logFile, String logLevel, String cmdFile,
        int memSize, long timeout) throws TGAdminException {

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

    CommandLine tgCL = new CommandLine((new File(this.home + "/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));
    }
    if (cmdFile == null)
        throw new TGAdminException("TGAdmin - Command file is required.");
    args.add("--file");
    args.add(cmdFile);

    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 startProcTime = 0;
    long endProcTime = 0;
    long totalProcTime = 0;
    try {
        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 (!output.toString().contains("Successfully connected to server"))
        throw new TGAdminException("TGAdmin - Admin could not connect to server", output.toString());
    if (endProcTime != 0)
        totalProcTime = endProcTime - startProcTime;
    System.out.println(
            "TGAdmin - Operation completed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : ""));
    return output.toString();
}