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

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

Introduction

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

Prototype

public CommandLine addArgument(final String argument, final boolean handleQuoting) 

Source Link

Document

Add a single argument.

Usage

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

@Test
public void testShouldBeAbleToResignAnSignedAppWithCustomKeystore() throws Exception {
    SelendroidServerBuilder builder = getDefaultBuilderWithCustomKeystore();
    File androidApp = File.createTempFile("testapp", ".apk");
    System.out.println("App name: " + androidApp.getName());
    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);
    String sigFileName = selendroidConfiguration.getKeystoreAlias().toUpperCase();
    if (sigFileName.length() > 8) {
        sigFileName = sigFileName.substring(0, 8);
    }/*from  www.j a v a 2 s .co  m*/

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

From source file:com.dangdang.ddframe.job.cloud.scheduler.mesos.TaskLaunchProcessor.java

private Protos.CommandInfo buildCommand(final Protos.CommandInfo.URI uri, final String bootstrapScript,
        final ShardingContexts shardingContexts, final boolean useDefaultExecutor) {
    Protos.CommandInfo.Builder result = Protos.CommandInfo.newBuilder().addUris(uri).setShell(true);
    if (useDefaultExecutor) {
        CommandLine commandLine = CommandLine.parse(bootstrapScript);
        commandLine.addArgument(GsonFactory.getGson().toJson(shardingContexts), false);
        result.setValue(Joiner.on(" ").join(commandLine.getExecutable(),
                Joiner.on(" ").join(commandLine.getArguments())));
    } else {/*from  w  w  w.j  a  va  2 s. co m*/
        result.setValue(bootstrapScript);
    }
    return result.build();
}

From source file:com.cws.esolutions.agent.processors.impl.ApplicationManagerProcessorImpl.java

/**
 * @see com.cws.esolutions.agent.processors.interfaces.IApplicationManagerProcessor#installApplication(com.cws.esolutions.agent.processors.dto.ApplicationManagerRequest)
 *///from w  ww .j a v a2  s . c  o m
public ApplicationManagerResponse installApplication(final ApplicationManagerRequest request)
        throws ApplicationManagerException {
    final String methodName = IApplicationManagerProcessor.CNAME
            + "#installApplication(final ApplicationManagerRequest request) throws ApplicationManagerException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ApplicationManagerRequest: {}", request);
    }

    BufferedWriter writer = null;
    ApplicationManagerResponse response = new ApplicationManagerResponse();

    final double version = request.getVersion();
    final DefaultExecutor executor = new DefaultExecutor();
    final String installerOptions = request.getInstallerOptions();
    final File installPath = FileUtils.getFile(request.getInstallPath());
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(CONNECT_TIMEOUT * 1000);
    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    final File packageInstaller = FileUtils.getFile(request.getPackageInstaller());

    if (DEBUG) {
        DEBUGGER.debug("double: {}", version);
        DEBUGGER.debug("DefaultExecutor: {}", executor);
        DEBUGGER.debug("String: {}", installerOptions);
        DEBUGGER.debug("File: {}", installPath);
        DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
        DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
        DEBUGGER.debug("File:{}", packageInstaller);
    }

    try {
        if (!(packageInstaller.canExecute())) {
            throw new ApplicationManagerException("Unable to execute package installer. Cannot continue.");
        }

        if (!(installPath.canWrite()) && (!(installPath.mkdirs()))) {
            throw new ApplicationManagerException("Unable to create installation target. Cannot continue.");
        }

        CommandLine command = CommandLine.parse(packageInstaller.getAbsolutePath());
        command.addArgument(installerOptions, false);
        command.addArgument(request.getPackageLocation(), false);

        if (DEBUG) {
            DEBUGGER.debug("CommandLine: {}", command);
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        streamHandler.start();

        executor.setWatchdog(watchdog);
        executor.setStreamHandler(streamHandler);

        if (DEBUG) {
            DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler);
            DEBUGGER.debug("ExecuteWatchdog: {}", watchdog);
            DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler);
            DEBUGGER.debug("DefaultExecutor: {}", executor);
        }

        executor.execute(command, resultHandler);

        resultHandler.waitFor();
        int exitCode = resultHandler.getExitValue();

        writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + request.getPackageName() + ".log"));
        writer.write(outputStream.toString());
        writer.flush();

        if (DEBUG) {
            DEBUGGER.debug("exitCode: {}", exitCode);
        }

        if (executor.isFailure(exitCode)) {
            throw new ApplicationManagerException("Application installation failed: Result Code: " + exitCode);
        }

        response.setResponse(outputStream.toString());
        response.setRequestStatus(AgentStatus.SUCCESS);
    } catch (ExecuteException eex) {
        ERROR_RECORDER.error(eex.getMessage(), eex);

        throw new ApplicationManagerException(eex.getMessage(), eex);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new ApplicationManagerException(iox.getMessage(), iox);
    } catch (InterruptedException ix) {
        ERROR_RECORDER.error(ix.getMessage(), ix);

        throw new ApplicationManagerException(ix.getMessage(), ix);
    } finally {
        try {
            writer.close();
        } catch (IOException iox) {
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return response;
}

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

public CommandLine createCommandLine(AdaptrisMessage msg) {
    CommandLine commandLine = new CommandLine(getExecutablePath());
    for (CommandArgument argument : getArguments()) {
        commandLine.addArgument(argument.retrieveValue(msg), quoteHandling());
    }/*from w  w  w. j a  v  a2 s. c o  m*/
    return commandLine;
}

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

AndroidApp signTestServer(File customSelendroidServer, File outputFileName)
        throws ShellCommandException, AndroidSdkException {
    if (outputFileName == null) {
        throw new IllegalArgumentException("outputFileName parameter is null.");
    }//from  w  w w .ja va2  s  . c om
    File androidKeyStore = androidDebugKeystore();

    if (androidKeyStore.isFile() == false) {
        // create a new keystore
        CommandLine commandline = new CommandLine(JavaSdk.keytool());

        commandline.addArgument("-genkey", false);
        commandline.addArgument("-v", false);
        commandline.addArgument("-keystore", false);
        commandline.addArgument(androidKeyStore.toString(), false);
        commandline.addArgument("-storepass", false);
        commandline.addArgument("android", false);
        commandline.addArgument("-alias", false);
        commandline.addArgument("androiddebugkey", false);
        commandline.addArgument("-keypass", false);
        commandline.addArgument("android", false);
        commandline.addArgument("-dname", false);
        commandline.addArgument("CN=Android Debug,O=Android,C=US", false);
        commandline.addArgument("-storetype", false);
        commandline.addArgument("JKS", false);
        commandline.addArgument("-sigalg", false);
        commandline.addArgument("MD5withRSA", false);
        commandline.addArgument("-keyalg", false);
        commandline.addArgument("RSA", false);
        commandline.addArgument("-validity", false);
        commandline.addArgument("9999", false);

        String output = ShellCommand.exec(commandline, 20000);
        log.info("A new keystore has been created: " + output);
    }

    // Sign the jar
    CommandLine commandline = new CommandLine(JavaSdk.jarsigner());

    commandline.addArgument("-sigalg", false);
    commandline.addArgument("MD5withRSA", false);
    commandline.addArgument("-digestalg", false);
    commandline.addArgument("SHA1", false);
    commandline.addArgument("-signedjar", false);
    commandline.addArgument(outputFileName.getAbsolutePath(), false);
    commandline.addArgument("-storepass", false);
    commandline.addArgument("android", false);
    commandline.addArgument("-keystore", false);
    commandline.addArgument(androidKeyStore.toString(), false);
    commandline.addArgument(customSelendroidServer.getAbsolutePath(), false);
    commandline.addArgument("androiddebugkey", false);
    String output = ShellCommand.exec(commandline, 20000);
    if (log.isLoggable(Level.INFO)) {
        log.info("App signing output: " + output);
    }
    log.info("The app has been signed: " + outputFileName.getAbsolutePath());
    return new DefaultAndroidApp(outputFileName);
}

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

File createAndAddCustomizedAndroidManifestToSelendroidServer()
        throws IOException, ShellCommandException, AndroidSdkException {
    String targetPackageName = applicationUnderTest.getBasePackage();
    File tempdir = new File(FileUtils.getTempDirectoryPath() + File.separatorChar + targetPackageName
            + System.currentTimeMillis());

    if (!tempdir.exists()) {
        tempdir.mkdirs();//w w w. j a v a 2 s.  co m
    }

    File customizedManifest = new File(tempdir, "AndroidManifest.xml");
    log.info("Adding target package '" + targetPackageName + "' to " + customizedManifest.getAbsolutePath());

    // add target package
    InputStream inputStream = getResourceAsStream(selendroidApplicationXmlTemplate);
    if (inputStream == null) {
        throw new SelendroidException("AndroidApplication.xml template file was not found.");
    }
    String content = IOUtils.toString(inputStream, Charset.defaultCharset().displayName());

    // find the first occurance of "package" and appending the targetpackagename to begining
    int i = content.toLowerCase().indexOf("package");
    int cnt = 0;
    for (; i < content.length(); i++) {
        if (content.charAt(i) == '\"') {
            cnt++;
        }
        if (cnt == 2) {
            break;
        }
    }
    content = content.substring(0, i) + "." + targetPackageName + content.substring(i);
    log.info("Final Manifest File:\n" + content);
    content = content.replaceAll(SELENDROID_TEST_APP_PACKAGE, targetPackageName);
    // Seems like this needs to be done
    if (content.contains(ICON)) {
        content = content.replaceAll(ICON, "");
    }

    OutputStream outputStream = new FileOutputStream(customizedManifest);
    IOUtils.write(content, outputStream, Charset.defaultCharset().displayName());
    IOUtils.closeQuietly(inputStream);
    IOUtils.closeQuietly(outputStream);

    // adding the xml to an empty apk
    CommandLine createManifestApk = new CommandLine(AndroidSdk.aapt());

    createManifestApk.addArgument("package", false);
    createManifestApk.addArgument("-M", false);
    createManifestApk.addArgument(customizedManifest.getAbsolutePath(), false);
    createManifestApk.addArgument("-I", false);
    createManifestApk.addArgument(AndroidSdk.androidJar(), false);
    createManifestApk.addArgument("-F", false);
    createManifestApk.addArgument(tempdir.getAbsolutePath() + File.separatorChar + "manifest.apk", false);
    createManifestApk.addArgument("-f", false);
    log.info(ShellCommand.exec(createManifestApk, 20000L));

    ZipFile manifestApk = new ZipFile(
            new File(tempdir.getAbsolutePath() + File.separatorChar + "manifest.apk"));
    ZipArchiveEntry binaryManifestXml = manifestApk.getEntry("AndroidManifest.xml");

    File finalSelendroidServerFile = new File(tempdir.getAbsolutePath() + "selendroid-server.apk");
    ZipArchiveOutputStream finalSelendroidServer = new ZipArchiveOutputStream(finalSelendroidServerFile);
    finalSelendroidServer.putArchiveEntry(binaryManifestXml);
    IOUtils.copy(manifestApk.getInputStream(binaryManifestXml), finalSelendroidServer);

    ZipFile selendroidPrebuildApk = new ZipFile(selendroidServer.getAbsolutePath());
    Enumeration<ZipArchiveEntry> entries = selendroidPrebuildApk.getEntries();
    for (; entries.hasMoreElements();) {
        ZipArchiveEntry dd = entries.nextElement();
        finalSelendroidServer.putArchiveEntry(dd);

        IOUtils.copy(selendroidPrebuildApk.getInputStream(dd), finalSelendroidServer);
    }

    finalSelendroidServer.closeArchiveEntry();
    finalSelendroidServer.close();
    manifestApk.close();
    log.info("file: " + finalSelendroidServerFile.getAbsolutePath());
    return finalSelendroidServerFile;
}

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

private CommandLine adbCommand(String... args) {
    CommandLine command = adbCommand();
    for (String arg : args) {
        command.addArgument(arg, false);
    }//from w ww .  j  a  va2 s.  c  o m
    return command;
}

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

@Override
public boolean isInstalled(String appBasePackage) throws AndroidSdkException {
    CommandLine command = adbCommand("shell", "pm", "list", "packages");

    command.addArgument(appBasePackage, false);
    String result = null;/*  w  w w .  ja v a2 s.  c o m*/
    try {
        result = ShellCommand.exec(command, 20000);
    } catch (ShellCommandException e) {
    }
    if (result != null && result.contains("package:" + appBasePackage)) {
        return true;
    }

    return false;
}

From source file:eu.crisis_economics.abm.dashboard.cluster.script.BashScheduler.java

/** {@inheritDoc} 
 * @throws SchedulerException //ww w .j a v a 2  s .c  o  m
 */
@Override
public String runParameterSweep(final Model paramSweepConfig, final String timeLimit, final File workDir)
        throws SchedulerException {

    File file = null;
    try {
        //         file = File.createTempFile("paramsweep-", ".xml");
        file = new File(workDir, "paramsweep-config.xml");
        Marshaller marshaller = JAXBContext.newInstance(Model.class).createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(paramSweepConfig, file);
        //      } catch (IOException e) {
        //         throw new SchedulerException("Could not create temporary parameter-sweep configuration xml.", e);
    } catch (JAXBException e) {
        throw new SchedulerException(
                "Could not write temporary parameter-sweep configuration xml: " + file.toString(), e);
    }
    CommandLine cmd = new CommandLine(cmdFile);
    Map<String, Object> substitutions = new HashMap<String, Object>();
    substitutions.put(CMD_SUBSTITUTION_NAME_FILE, file);
    cmd.setSubstitutionMap(substitutions);

    if (timeLimit != null && !timeLimit.isEmpty()) {
        cmd.addArgument("-t", false);
        cmd.addArgument(timeLimit, false);
    }

    // add server port argument
    cmd.addArgument("-p", false);
    cmd.addArgument(String.valueOf(serverPort), false);

    cmd.addArgument("${" + CMD_SUBSTITUTION_NAME_FILE + "}", false);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(workDir);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(byteArrayOutputStream);

    executor.setStreamHandler(streamHandler);

    try {
        executor.execute(cmd);
    } catch (ExecuteException e) {
        throw new SchedulerException(
                paramSweepCmd + " exited with " + e.getExitValue() + ". Output:\n" + byteArrayOutputStream, e);
    } catch (IOException e) {
        throw new SchedulerException(
                "Execution of " + paramSweepCmd + " failed. Output:\n" + byteArrayOutputStream, e);
    }

    // the standard output of the script is the job id
    final String jobId = byteArrayOutputStream.toString();

    return jobId;
}

From source file:modules.GeneralNativeCommandModule.java

protected KeyValueResult 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   w w  w . j ava 2s  .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(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) {
        // System.out.println(commandLine);
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.executionResult = outputStream.toString();
        throw n;
    }
    KeyValueResult t = new KeyValueResult("GeneralNativeCommandResults");
    t.add("fullOutput", outputStream.toString().trim());
    return t;
}