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:com.github.peterjanes.node.NpmPackMojo.java

/**
 *
 * @throws MojoExecutionException if anything unexpected happens.
 *//*from   w  ww. j  av  a  2 s.  co m*/
public void execute() throws MojoExecutionException {
    if (!outputDirectory.exists()) {
        outputDirectory.mkdirs();
    }

    CommandLine commandLine = new CommandLine(executable);
    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(outputDirectory);

    List commandArguments = new ArrayList();
    commandArguments.add("pack");
    commandArguments.add("./commonjs");

    String[] args = new String[commandArguments.size()];
    for (int i = 0; i < commandArguments.size(); i++) {
        args[i] = (String) commandArguments.get(i);
    }

    commandLine.addArguments(args, false);

    OutputStream stdout = System.out;
    OutputStream stderr = System.err;

    try {
        getLog().debug("Executing command line: " + commandLine);
        exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in));

        int resultCode = exec.execute(commandLine);

        if (0 != resultCode) {
            throw new MojoExecutionException(
                    "Result of " + commandLine + " execution is: '" + resultCode + "'.");
        }

        Artifact artifact = mavenProject.getArtifact();
        String fileName = String.format("%s-%s.tgz", artifact.getArtifactId(),
                mavenProject.getProperties().getProperty("node.project.version"));
        artifact.setFile(new File(outputDirectory, fileName));
    } catch (ExecuteException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);
    } catch (IOException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);
    }
}

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

/**
 * Starts this server./*from   w ww  .ja v a 2  s  .  co 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:at.medevit.elexis.gdt.handler.GDTOutputHandler.java

public static void handleOutput(GDTSatzNachricht gdtSatzNachricht, IGDTCommunicationPartner cp) {
    int connectionType = cp.getConnectionType();

    switch (connectionType) {
    case SystemConstants.FILE_COMMUNICATION:
        boolean success = GDTFileHelper.writeGDTSatzNachricht(gdtSatzNachricht, cp);
        if (success) {
            GDTProtokoll.addEntry(GDTProtokoll.MESSAGE_DIRECTION_OUT, cp, gdtSatzNachricht);
        } else {/*from  w ww  .ja  va  2s  .  co  m*/
            String message = "Fehler beim Schreiben der GDT Satznachricht "
                    + gdtSatzNachricht.getValue(GDTConstants.FELDKENNUNG_SATZIDENTIFIKATION) + " auf "
                    + cp.getLabel();
            Status status = new Status(IStatus.WARNING, Activator.PLUGIN_ID, message);
            StatusManager.getManager().handle(status, StatusManager.SHOW);
            logger.log(message, Log.WARNINGS);
        }

        // Update the protokoll view
        final IViewPart protokoll = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
                .findView(GDTProtokollView.ID);
        Display display = PlatformUI.getWorkbench().getDisplay();
        display.asyncExec(new Runnable() {
            @Override
            public void run() {
                if (protokoll != null)
                    protokoll.setFocus();
            }
        });

        // Call the external program to care for the output (if applicable)
        String handlerProgram = cp.getExternalHandlerProgram();
        if (handlerProgram != null) {
            CommandLine cmdLine = CommandLine.parse(handlerProgram);
            try {
                DefaultExecutor executor = new DefaultExecutor();
                executor.setExitValues(null); // Ignore the exit value
                int exitValue = executor.execute(cmdLine);
                logger.log("Return value of " + cmdLine + ": " + exitValue, Log.DEBUGMSG);
            } catch (ExecuteException e) {
                String message = "Fehler beim Ausfhren von " + cmdLine;
                Status status = new Status(IStatus.WARNING, Activator.PLUGIN_ID, message, e);
                StatusManager.getManager().handle(status, StatusManager.SHOW);
                logger.log(e, message, Log.ERRORS);
            } catch (IOException e) {
                String message = "Fehler beim Ausfhren von " + cmdLine;
                Status status = new Status(IStatus.WARNING, Activator.PLUGIN_ID, message, e);
                StatusManager.getManager().handle(status, StatusManager.SHOW);
                logger.log(e, message, Log.ERRORS);
            }
        }
        break;
    case SystemConstants.SERIAL_COMMUNICATION:
        // TODO Serial output implementation
        break;
    default:
        break;
    }
}

From source file:de.akquinet.innovation.play.maven.Play2TestMojo.java

public void execute() throws MojoExecutionException {

    if (isSkipExecution()) {
        getLog().info("Test phase skipped");
        return;/*from   w ww .ja  v a2 s .  c  o  m*/
    }

    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArguments(getPlay2SystemPropertiesArguments(), false);
    cmdLine.addArgument("test");
    DefaultExecutor executor = new DefaultExecutor();

    if (timeout > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
        executor.setWatchdog(watchdog);
    }

    executor.setWorkingDirectory(project.getBasedir());

    executor.setExitValue(0);
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        if (testFailureIgnore) {
            getLog().error("Test execution failures ignored");
        } else {
            throw new MojoExecutionException("Error during compilation", e);
        }
    }
}

From source file:com.github.mjeanroy.maven.plugins.node.commands.CommandExecutor.java

/**
 * Execute command line and return the result status.
 *
 * @param workingDirectory Working directory (i.e where the command line is executed).
 * @param command Command, containing executable path with arguments.
 * @param logger Logger to use to log command output.
 * @return Command result object./*www . j av  a 2  s.co m*/
 */
public CommandResult execute(File workingDirectory, Command command, Log logger) {
    CommandLine commandLine = new CommandLine(command.getExecutable());
    for (String argument : command.getArguments()) {
        commandLine.addArgument(argument);
    }

    try {
        Executor executor = new DefaultExecutor();
        executor.setWorkingDirectory(workingDirectory);
        executor.setExitValue(0);

        // Define custom output stream
        LogStreamHandler stream = new LogStreamHandler(logger);
        PumpStreamHandler handler = new PumpStreamHandler(stream);
        executor.setStreamHandler(handler);

        int status = executor.execute(commandLine);
        return new CommandResult(status);
    } catch (ExecuteException ex) {
        return new CommandResult(ex.getExitValue());
    } catch (IOException ex) {
        throw new CommandException(ex);
    }
}

From source file:com.github.peterjanes.node.AbstractNpmInstallMojo.java

/**
 *
 * @param outputDirectory The working directory for the npm command.
 * @param npmDependencies A comma-separated list of npm packages to install.
 * @param extraArguments Extra arguments to provide to the npm command.
 * @param artifactScope Scope of the artifacts to include.
 * @throws MojoExecutionException if anything unexpected happens.
 *//* www . ja  va 2s. c  o  m*/
void execute(File outputDirectory, String npmDependencies, String extraArguments, ResolutionScope artifactScope)
        throws MojoExecutionException {
    if (!outputDirectory.exists()) {
        outputDirectory.mkdirs();
    }

    CommandLine commandLine = new CommandLine(executable);
    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(outputDirectory);

    List commandArguments = new ArrayList();
    commandArguments.add("install");

    if (null != npmDependencies) {
        String[] packages = npmDependencies.split(",");
        for (String pkg : packages) {
            commandArguments.add(pkg);
        }
    }

    List<Artifact> nodeArtifacts = getNodeArtifacts(artifactScope);
    for (Artifact artifact : nodeArtifacts) {
        commandArguments.add(artifact.getFile().getAbsolutePath());
    }

    if (null != extraArguments) {
        String[] extraArgs = extraArguments.split(" ");
        for (String extraArg : extraArgs) {
            commandArguments.add(extraArg);
        }
    }

    String[] args = new String[commandArguments.size()];
    for (int i = 0; i < commandArguments.size(); i++) {
        args[i] = (String) commandArguments.get(i);
    }

    commandLine.addArguments(args, false);

    OutputStream stdout = getLog().isDebugEnabled() ? System.err : new ByteArrayOutputStream();
    OutputStream stderr = getLog().isDebugEnabled() ? System.err : new ByteArrayOutputStream();

    try {
        getLog().debug(
                "Executing command line " + commandLine + " in directory " + outputDirectory.getAbsolutePath());
        exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in));

        int resultCode = exec.execute(commandLine);

        if (0 != resultCode) {
            System.out.println("STDOUT: " + stdout);
            System.err.println("STDERR: " + stderr);
            throw new MojoExecutionException(
                    "Result of " + commandLine + " execution is: '" + resultCode + "'.");
        }
    } catch (ExecuteException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);

    } catch (IOException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);
    }
}

From source file:com.tribuneqa.utilities.FrameworkUtilities.java

public void appiumStart() throws IOException, InterruptedException {

    // Start command prompt In background.
    CommandLine command = new CommandLine("cmd");

    // Add different arguments In command line which requires to start appium server.
    command.addArgument("/c");

    // Add different arguments In command line which requires to start appium server. 
    command.addArgument("appium");
    command.addArgument("-a");
    command.addArgument("10.20.121.69");
    command.addArgument("-p");
    command.addArgument("8001");
    command.addArgument("-U");
    command.addArgument("4d0081724d5741c7");

    // Execute command line arguments to start appium server. 
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(1);//from  ww  w. j  av a2 s. c  o m
    executor.execute(command, resultHandler);

    Thread.sleep(15000);

}

From source file:de.pawlidi.openaletheia.utils.exec.ProcessExecutor.java

/**
 * Creates executor with system watchdog for given output stream.
 * // w  w  w  .  j  a v a  2s  .c  o  m
 * @param outputStream
 * @return
 */
private static Executor createExecutor(OutputStream outputStream) {

    // create process watchdog with timeout 60000 milliseconds
    ExecuteWatchdog watchdog = new ExecuteWatchdog(WATCHDOG_TIMEOUT);

    // set watchdog and stream handler
    Executor executor = new DefaultExecutor();
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(new PumpStreamHandler(outputStream, outputStream));
    return executor;
}

From source file:com.github.peterjanes.node.NpmTestMojo.java

/**
 *
 * @throws MojoExecutionException if anything unexpected happens.
 *//* w  w  w . j a v a 2  s .c om*/
public void execute() throws MojoExecutionException {
    if (!workingDirectory.exists()) {
        workingDirectory.mkdirs();
    }

    CommandLine commandLine = new CommandLine(executable);
    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(workingDirectory);

    Map env = new HashMap();
    try {
        Map systemEnvVars = EnvironmentUtils.getProcEnvironment();
        env.putAll(systemEnvVars);
    } catch (IOException e) {
        getLog().error("Could not assign default system enviroment variables.", e);
    }
    env.put("NODE_PATH", new File(workingDirectory, "node_modules").getAbsolutePath());
    env.put("XUNIT_FILE", outputFile.getAbsolutePath());

    List commandArguments = new ArrayList();
    commandArguments.add("test");

    String[] args = new String[commandArguments.size()];
    for (int i = 0; i < commandArguments.size(); i++) {
        args[i] = (String) commandArguments.get(i);
    }

    commandLine.addArguments(args, false);

    OutputStream stdout = System.out;
    OutputStream stderr = System.err;

    try {
        outputFile.getParentFile().mkdirs();
        getLog().debug("Executing command line " + commandLine + " in directory "
                + workingDirectory.getAbsolutePath());
        exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in));

        int resultCode = exec.execute(commandLine, env);

        if (0 != resultCode) {
            throw new MojoExecutionException(
                    "Result of " + commandLine + " execution is: '" + resultCode + "'.");
        }
    } catch (ExecuteException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);

    } catch (IOException e) {
        throw new MojoExecutionException(EXECUTION_FAILED, e);
    }
}

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

private void init() {
    String line = executable.getAbsolutePath() + " init -key-shares=1 -key-threshold=1 " + CA_CERT_ARG;
    System.out.println(">> " + line);
    CommandLine parse = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    PumpStreamHandler pump = new PumpStreamHandler(new VaultOutputStream().addExtractor(l -> {
        if (l.contains("Unseal Key 1:")) {
            unseal = l.replace("Unseal Key 1: ", "").trim();
        } else if (l.contains("Initial Root Token:")) {
            token = l.replace("Initial Root Token: ", "").trim();
        }// w  ww  .  j  a v a  2  s .  com
    }), System.err);

    ExecuteWatchdog watchDog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchDog);
    executor.setStreamHandler(pump);
    try {
        executor.execute(parse);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    //    await().until(() -> token != null);
    //    await().until(() -> unseal != null);

    System.out.println("Vault Server initialized (but sealed)");
    System.out.println("Root token: " + token);
    System.out.println("Unseal key: " + unseal);
}