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:io.takari.maven.testing.executor.ForkedLauncher.java

public int run(String[] cliArgs, Map<String, String> envVars, File multiModuleProjectDirectory,
        File workingDirectory, File logFile) throws IOException, LauncherException {
    String javaHome;/*from  w  w w  .ja  v a  2s. c  om*/
    if (envVars == null || envVars.get("JAVA_HOME") == null) {
        javaHome = System.getProperty("java.home");
    } else {
        javaHome = envVars.get("JAVA_HOME");
    }

    File executable = new File(javaHome, Os.isFamily(Os.FAMILY_WINDOWS) ? "bin/javaw.exe" : "bin/java");

    CommandLine cli = new CommandLine(executable);
    cli.addArgument("-classpath").addArgument(classworldsJar.getAbsolutePath());
    cli.addArgument("-Dclassworlds.conf=" + new File(mavenHome, "bin/m2.conf").getAbsolutePath());
    cli.addArgument("-Dmaven.home=" + mavenHome.getAbsolutePath());
    cli.addArgument("-Dmaven.multiModuleProjectDirectory=" + multiModuleProjectDirectory.getAbsolutePath());
    cli.addArgument("org.codehaus.plexus.classworlds.launcher.Launcher");

    cli.addArguments(args.toArray(new String[args.size()]));
    if (extensions != null && !extensions.isEmpty()) {
        cli.addArgument("-Dmaven.ext.class.path=" + toPath(extensions));
    }

    cli.addArguments(cliArgs);

    Map<String, String> env = new HashMap<>();
    if (mavenHome != null) {
        env.put("M2_HOME", mavenHome.getAbsolutePath());
    }
    if (envVars != null) {
        env.putAll(envVars);
    }
    if (envVars == null || envVars.get("JAVA_HOME") == null) {
        env.put("JAVA_HOME", System.getProperty("java.home"));
    }

    DefaultExecutor executor = new DefaultExecutor();
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    executor.setWorkingDirectory(workingDirectory.getAbsoluteFile());

    try (OutputStream log = new FileOutputStream(logFile)) {
        PrintStream out = new PrintStream(log);
        out.format("Maven Executor implementation: %s\n", getClass().getName());
        out.format("Maven home: %s\n", mavenHome);
        out.format("Build work directory: %s\n", workingDirectory);
        out.format("Environment: %s\n", env);
        out.format("Command line: %s\n\n", cli.toString());
        out.flush();

        PumpStreamHandler streamHandler = new PumpStreamHandler(log);
        executor.setStreamHandler(streamHandler);
        return executor.execute(cli, env); // this throws ExecuteException if process return code != 0
    } catch (ExecuteException e) {
        throw new LauncherException("Failed to run Maven: " + e.getMessage() + "\n" + cli, e);
    }
}

From source file:io.selendroid.builder.SelendroidServerBuilderTest.java

@Test
public void testShouldBeAbleToResignAnSignedApp() throws Exception {
    SelendroidServerBuilder builder = getDefaultBuilder();
    File androidApp = File.createTempFile("testapp", ".apk");
    FileUtils.copyFile(new File(APK_FILE), androidApp);
    AndroidApp app = builder.resignApp(androidApp);
    Assert.assertEquals("resigned-" + androidApp.getName(), new File(app.getAbsolutePath()).getName());
    // Verify that apk is signed
    CommandLine cmd = new CommandLine(AndroidSdk.aapt());
    cmd.addArgument("list", false);
    cmd.addArgument(app.getAbsolutePath(), false);

    String output = ShellCommand.exec(cmd);

    assertResultDoesNotContainFile(output, "META-INF/CERT.RSA");
    assertResultDoesNotContainFile(output, "META-INF/CERT.SF");
    assertResultDoesContainFile(output, "META-INF/ANDROIDD.SF");
    assertResultDoesContainFile(output, "META-INF/ANDROIDD.RSA");
    assertResultDoesContainFile(output, "AndroidManifest.xml");
}

From source file:edu.stolaf.cs.wmrserver.testjob.TestJobTask.java

public TestJobResult call() throws IOException {
    // Create the result object
    TestJobResult result = new TestJobResult();

    // Map/*  ww  w .  java2 s  . co  m*/

    CappedInputStream mapInput = null;
    try {
        // List the input files and open a stream
        FileSystem fs = _inputPath.getFileSystem(_conf);
        FileStatus[] files = JobServiceHandler.listInputFiles(fs, _inputPath);
        AggregateInputStream aggregateInput = new AggregateInputStream(fs, files);
        mapInput = new CappedInputStream(aggregateInput, _inputCap);

        // Run the mapper
        result.setMapResult(runTransform(_id, _mapperFile, _packageDir, mapInput));
    } finally {
        IOUtils.closeQuietly(mapInput);
    }

    // Return if mapper failed or did not produce output
    if (result.getMapResult().getExitCode() != 0 || result.getMapResult().getOutputFile() == null)
        return result;

    // Sort
    // While this seems (and is) inefficient for computers, this is
    //actually probably the shortest way to write this code since
    // vanilla Java does not provide an equivalent of sort -n.
    // If you want to write it in Java, use java.util.TreeSet.

    File intermediateFile = null;
    FileOutputStream intermediateOutput = null;
    try {
        // Create and open temporary file for sorted intermediate output
        intermediateFile = File.createTempFile("job-" + Long.toString(_id), "-intermediate", _tempDir);
        intermediateOutput = new FileOutputStream(intermediateFile);

        // Run the sort

        CommandLine sortCommand = new CommandLine("sort");
        //sortCommand.addArgument("--field-separator=\t");
        if (_numericSort)
            sortCommand.addArgument("-n");
        sortCommand.addArgument(result.getMapResult().getOutputFile().getCanonicalPath(), false);
        DefaultExecutor exec = new DefaultExecutor();
        ExecuteWatchdog dog = new ExecuteWatchdog(EXECUTABLE_TIMEOUT);
        PumpStreamHandler pump = new PumpStreamHandler(intermediateOutput);
        exec.setWatchdog(dog);
        exec.setStreamHandler(pump);

        try {
            exec.execute(sortCommand);
        } catch (ExecuteException ex) {
            throw new IOException("Sort process failed while running test jobs", ex);
        }
    } finally {
        IOUtils.closeQuietly(intermediateOutput);
    }

    // Reduce

    FileInputStream reduceInput = null;
    try {
        // Open the intermediate file for reading
        reduceInput = new FileInputStream(intermediateFile);

        // Run the reducer
        result.setReduceResult(runTransform(_id, _reducerFile, _packageDir, reduceInput));
    } finally {
        IOUtils.closeQuietly(reduceInput);

        // Delete intermediate file
        intermediateFile.delete();
    }

    return result;
}

From source file:de.slackspace.wfail2ban.firewall.impl.DefaultFirewallManager.java

private boolean checkFirewallRuleExists(int ruleNumber, String filterName) {
    CommandLine cmdLine = new CommandLine("cmd.exe");
    cmdLine.addArgument("/C");
    cmdLine.addArgument(System.getenv("WINDIR") + "\\system32\\netsh.exe");
    cmdLine.addArgument("advfirewall");
    cmdLine.addArgument("firewall");
    cmdLine.addArgument("show");
    cmdLine.addArgument("rule");
    cmdLine.addArgument(createFinalRuleName(ruleNumber, filterName));

    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);/*from w  w w  .j av  a2s .c  om*/
    try {
        executor.execute(cmdLine);
        return true;
    } catch (ExecuteException e) {
        //rule does not exist
        return false;
    } catch (IOException e) {
        logger.error("Could not list firewall rule. Error was: ", e);
    }
    return false;
}

From source file:ch.ivyteam.ivy.maven.engine.EngineControl.java

private CommandLine toEngineCommand(Command command) {
    String classpath = context.engineClasspathJarPath;
    if (StringUtils.isNotBlank(context.vmOptions.additionalClasspath)) {
        classpath += File.pathSeparator + context.vmOptions.additionalClasspath;
    }//from w w  w.ja va 2s  .  c o m

    CommandLine cli = new CommandLine(new File(getJavaExec())).addArgument("-classpath").addArgument(classpath)
            .addArgument("-Dosgi.install.area=" + context.engineDirectory);
    if (StringUtils.isNotBlank(context.vmOptions.additionalVmOptions)) {
        cli.addArgument(context.vmOptions.additionalVmOptions, false);
    }
    cli.addArgument("org.eclipse.equinox.launcher.Main").addArgument("-application")
            .addArgument("ch.ivyteam.ivy.server.exec.engine").addArgument(command.toString());
    return cli;
}

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

public void testSetCommandBuilder() throws Exception {
    SystemCommandExecutorService service = new SystemCommandExecutorService();
    assertNotNull(service.getCommandBuilder());
    assertEquals(DefaultCommandBuilder.class, service.getCommandBuilder().getClass());

    CommandBuilder dummy = new CommandBuilder() {
        @Override/*from w  ww .java2  s.  c om*/
        public CommandLine createCommandLine(AdaptrisMessage msg) throws CoreException {
            return new CommandLine("echo");
        }

        @Override
        public Executor configure(Executor exec) throws CoreException {
            return exec;
        }

        @Override
        public Map<String, String> createEnvironment(AdaptrisMessage msg) throws CoreException {
            return null;
        }
    };
    service.setCommandBuilder(dummy);
    assertEquals(dummy, service.getCommandBuilder());

    try {
        service.setCommandBuilder(null);
        fail();
    } catch (IllegalArgumentException expected) {

    }
    assertEquals(dummy, service.getCommandBuilder());
}

From source file:modules.NativeProcessIterativeDaemonModule.java

protected String extractNative(String command, String options, Path path) throws NativeExecutionException {
    if (command == null || command.equals("")) {
        System.err.println("command null at GeneralNativeCommandModule.extractNative()");
        return null;
    }/*from ww  w. j a  v  a  2  s.  c om*/
    CommandLine commandLine = new CommandLine(command);

    if (options != null && !options.equals("")) {
        String[] args = options.split(" ");
        commandLine.addArguments(args);
    }

    if (path != null) {
        commandLine.addArgument(path.toAbsolutePath().toString(), false);
    }
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);
    GeneralExecutableModuleConfig generalExecutableModuleConfig = getConfig();
    executor.setWatchdog(new ExecuteWatchdog(generalExecutableModuleConfig.timeout));
    if (getConfig().workingDirectory != null && getConfig().workingDirectory.exists()) {
        executor.setWorkingDirectory(getConfig().workingDirectory);
    }
    try {

        // System.out.println("Now execute " + commandLine);
        executor.execute(commandLine);
    } catch (ExecuteException xs) {
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.executionResult = outputStream.toString();
        n.exitCode = xs.getExitValue();
        throw n;
    } catch (IOException xs) {
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.executionResult = outputStream.toString();
        throw n;
    }
    return outputStream.toString().trim();
}

From source file:com.adaptris.hpcc.SprayToThorTest.java

@Test
public void testCSVFormatMaxRecordSize() throws Exception {
    SprayToThor sprayToThor = new SprayToThor();
    CSVSprayFormat sprayFormat = new CSVSprayFormat();
    sprayFormat.setMaxRecordSize(214);//  w w  w.  jav a 2s.c o m
    sprayToThor.setSprayFormat(sprayFormat);
    CommandLine cmdLine = new CommandLine("/bin/dfuplus");
    sprayToThor.addFormatArguments(cmdLine);
    assertEquals(2, cmdLine.getArguments().length);
    assertEquals("format=csv", cmdLine.getArguments()[0]);
    assertEquals("maxrecordsize=214", cmdLine.getArguments()[1]);
}

From source file:eu.creatingfuture.propeller.blocklyprop.propeller.PropellerLoad.java

protected boolean loadIntoEeprom(String executable, File eepromFile, String comPort) {
    try {//from w ww  .  j  av  a2  s  .  co m
        Map map = new HashMap();
        map.put("eepromFile", eepromFile);

        CommandLine cmdLine = new CommandLine(executable);
        cmdLine.addArgument("-r");
        cmdLine.addArgument("-e");
        if (comPort != null) {
            cmdLine.addArgument("-p").addArgument(comPort);
        }
        cmdLine.addArgument("${eepromFile}");

        cmdLine.setSubstitutionMap(map);
        DefaultExecutor executor = new DefaultExecutor();
        //executor.setExitValues(new int[]{451, 301});

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);

        try {
            exitValue = executor.execute(cmdLine);
        } catch (ExecuteException ee) {
            exitValue = ee.getExitValue();
            logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue);
            success = false;
            return false;
        } finally {
            output = outputStream.toString();
        }

        success = true;
        return true;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        success = false;
        return false;
    }
}

From source file:io.selendroid.standalone.builder.SelendroidServerBuilderTest.java

@Test
public void testShouldBeAbleToResignAnSignedApp() throws Exception {
    SelendroidServerBuilder builder = getDefaultBuilder();
    File androidApp = File.createTempFile("testapp", ".apk");
    FileUtils.copyFile(new File(APK_FILE), androidApp);

    AndroidApp resignedApp = builder.resignApp(androidApp);
    assertResignedApp(resignedApp, androidApp);

    // Verify that apk is signed
    CommandLine cmd = new CommandLine(AndroidSdk.aapt());
    cmd.addArgument("list", false);
    cmd.addArgument(resignedApp.getAbsolutePath(), false);

    String output = ShellCommand.exec(cmd);

    assertResultDoesNotContainFile(output, "META-INF/CERT.RSA");
    assertResultDoesNotContainFile(output, "META-INF/CERT.SF");
    assertResultDoesContainFile(output, "META-INF/ANDROIDD.SF");
    assertResultDoesContainFile(output, "META-INF/ANDROIDD.RSA");
    assertResultDoesContainFile(output, "AndroidManifest.xml");
}