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.selendroid.standalone.builder.SelendroidServerBuilderTest.java

@Test
public void testShouldBeAbleToCreateASignedSelendroidServerWithCustomKeystore() throws Exception {
    SelendroidServerBuilder builder = getDefaultBuilderWithCustomKeystore();
    builder.init(new DefaultAndroidApp(new File(APK_FILE)));
    builder.cleanUpPrebuildServer();//from  w ww. ja  va 2s . c  o  m
    File file = File.createTempFile("testserver1", "apk");
    builder.signTestServer(builder.createAndAddCustomizedAndroidManifestToSelendroidServer(), file);

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

    String output = ShellCommand.exec(cmd);
    String sigFileName = selendroidConfiguration.getKeystoreAlias().toUpperCase();
    if (sigFileName.length() > 8) {
        sigFileName = sigFileName.substring(0, 8);
    }

    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:it.drwolf.ridire.index.sketch.AsyncSketchCreator.java

private void compactLines(List<File> tableFile, File finalTable) throws ExecuteException, IOException {
    Executor executor = new DefaultExecutor();
    File tempTabTot = File.createTempFile("ridireTABTOT", ".tbl");
    File tempSh = File.createTempFile("ridireSH", ".sh");
    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append("export LC_ALL=C\n");
    stringBuffer/*from   w ww. j  a  va2s .c  om*/
            .append("cat " + StringUtils.join(tableFile, " ") + " > " + tempTabTot.getAbsolutePath() + "\n");
    stringBuffer.append("awk '{a[$2]+= $1; s+=$1}END{for(i in a){print a[i],i;}; print s \"\t\"}' "
            + tempTabTot.getAbsolutePath() + " | sort -k1nr -k2 > " + finalTable.getAbsolutePath());
    FileUtils.writeStringToFile(tempSh, stringBuffer.toString());
    tempSh.setExecutable(true);
    CommandLine commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    FileUtils.deleteQuietly(tempTabTot);
    FileUtils.deleteQuietly(tempSh);
}

From source file:com.netflix.genie.web.services.impl.LocalJobKillServiceImpl.java

private void killJobOnUnix(final int pid) throws GenieException {
    try {//from  w w  w . j  av  a 2  s.c o m
        // Ensure this process check can't be timed out
        final Instant tomorrow = Instant.now().plus(1, ChronoUnit.DAYS);
        final ProcessChecker processChecker = new UnixProcessChecker(pid, this.executor, tomorrow);
        processChecker.checkProcess();
    } catch (final ExecuteException ee) {
        // This means the job was done already
        log.debug("Process with pid {} is already done", pid);
        return;
    } catch (final IOException ioe) {
        throw new GenieServerException("Unable to check process status for pid " + pid, ioe);
    }

    // TODO: Do we need retries?
    // This means the job client process is still running
    try {
        final CommandLine killCommand;
        if (this.runAsUser) {
            killCommand = new CommandLine("sudo");
            killCommand.addArgument("kill");
        } else {
            killCommand = new CommandLine("kill");
        }
        killCommand.addArguments(Integer.toString(pid));
        this.executor.execute(killCommand);
    } catch (final IOException ioe) {
        throw new GenieServerException("Unable to kill process " + pid, ioe);
    }
}

From source file:com.tascape.qa.th.android.comm.Adb.java

public List<String> adb(final List<Object> arguments) throws IOException {
    CommandLine cmdLine = new CommandLine(ADB);
    if (!this.serial.isEmpty()) {
        cmdLine.addArgument("-s");
        cmdLine.addArgument(serial);//from  w  w  w  .  j  a v  a2s .c om
    }
    arguments.forEach((arg) -> {
        cmdLine.addArgument(arg + "");
    });
    LOG.debug("[{} {}]", cmdLine.getExecutable(), StringUtils.join(cmdLine.getArguments(), " "));
    List<String> output = new ArrayList<>();
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new ESH(output));
    if (executor.execute(cmdLine) != 0) {
        throw new IOException(cmdLine + " failed");
    }
    return output;
}

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

@DescribeProcess(title = "r.viewshed", description = "Computes the viewshed of a point on an elevation raster map.")
@DescribeResult(description = "area visible from provided location")
public static GridCoverage2D viewshed(
        @DescribeParameter(name = "dem", description = "digitial elevation model") GridCoverage2D dem,
        @DescribeParameter(name = "x", description = "x location in map units") double x,
        @DescribeParameter(name = "y", description = "y location in map units") double y) throws Exception {

    String COMMAND = "viewshed";
    //Stage files in a temporary location
    File geodb = Files.createTempDirectory("grassdata").toFile();
    geodb.deleteOnExit();//from   w w  w .j  a v  a  2s  .co  m
    File location = new File(geodb, COMMAND + Long.toString(random.nextLong()) + "location");

    // stage dem file
    File file = new File(geodb, "dem.tif");
    //The file must exist for FileImageOutputStreamExtImplSpi to create the output stream
    if (!file.exists()) {
        file.getParentFile().mkdirs();
        file.createNewFile();
    }
    final GeoTiffFormat format = new GeoTiffFormat();
    GridCoverageWriter writer = format.getWriter(file);
    writer.write(dem, null);
    LOGGER.info("Staging file:" + file);

    // use file to create location with (returns PERMANENT mapset)
    File mapset = location(location, file);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWatchdog(new ExecuteWatchdog(60000));
    executor.setStreamHandler(new PumpStreamHandler(System.out));
    executor.setWorkingDirectory(mapset);

    Map<String, String> env = customEnv(geodb, location, mapset);

    // EXPORT IMPORT DEM
    // r.in.gdal input=~/grassdata/viewshed/PERMANENT/dem.tif output=dem --overwrite

    File r_in_gdal = bin("r.in.gdal");
    CommandLine cmd = new CommandLine(r_in_gdal);
    cmd.addArgument("input=${file}");
    cmd.addArgument("output=dem");
    cmd.addArgument("--overwrite");
    cmd.setSubstitutionMap(new KVP("file", file));
    try {
        LOGGER.info(cmd.toString());
        executor.setExitValue(0);
        int exitValue = executor.execute(cmd, env);
    } catch (ExecuteException fail) {
        LOGGER.warning(r_in_gdal.getName() + ":" + fail.getLocalizedMessage());
        throw fail;
    }

    // EXECUTE VIEWSHED
    File r_viewshed = bin("r.viewshed");
    cmd = new CommandLine(r_viewshed);
    cmd.addArgument("input=dem");
    cmd.addArgument("output=viewshed");
    cmd.addArgument("coordinates=${x},${y}");
    cmd.addArgument("--overwrite");
    cmd.setSubstitutionMap(new KVP("x", x, "y", y));

    try {
        LOGGER.info(cmd.toString());
        executor.setExitValue(0);
        int exitValue = executor.execute(cmd, env);
    } catch (ExecuteException fail) {
        LOGGER.warning(r_viewshed.getName() + ":" + fail.getLocalizedMessage());
        throw fail;
    }

    // EXECUTE EXPORT VIEWSHED
    // r.out.gdal --overwrite input=viewshed@PERMANENT output=/Users/jody/grassdata/viewshed/viewshed.tif format=GTiff
    File viewshed = new File(location, "viewshed.tif");

    File r_out_gdal = bin("r.out.gdal");
    cmd = new CommandLine(r_out_gdal);
    cmd.addArgument("input=viewshed");
    cmd.addArgument("output=${viewshed}");
    cmd.addArgument("--overwrite");
    cmd.addArgument("format=GTiff");
    cmd.setSubstitutionMap(new KVP("viewshed", viewshed));

    try {
        LOGGER.info(cmd.toString());
        executor.setExitValue(0);
        int exitValue = executor.execute(cmd, env);
    } catch (ExecuteException fail) {
        LOGGER.warning(r_out_gdal.getName() + ":" + fail.getLocalizedMessage());
        throw fail;
    }

    // STAGE RESULT

    if (!viewshed.exists()) {
        throw new IOException("Generated viweshed.tif not found");
    }
    GeoTiffReader reader = format.getReader(viewshed);
    GridCoverage2D coverage = reader.read(null);
    cleanup(new File(env.get("GISRC")));
    return coverage;
}

From source file:com.netflix.genie.web.services.impl.JobKillServiceV3.java

private void killJobOnUnix(final int pid) throws GenieException {
    try {/*from   w  w w .j a v a  2  s .  c o m*/
        // Ensure this process check can't be timed out
        final Instant tomorrow = Instant.now().plus(1, ChronoUnit.DAYS);
        final ProcessChecker processChecker = this.processCheckerFactory.get(pid, tomorrow);
        processChecker.checkProcess();
    } catch (final ExecuteException ee) {
        // This means the job was done already
        log.debug("Process with pid {} is already done", pid);
        return;
    } catch (final IOException ioe) {
        throw new GenieServerException("Unable to check process status for pid " + pid, ioe);
    }

    // TODO: Do we need retries?
    // This means the job client process is still running
    try {
        final CommandLine killCommand;
        if (this.runAsUser) {
            killCommand = new CommandLine("sudo");
            killCommand.addArgument("kill");
        } else {
            killCommand = new CommandLine("kill");
        }
        killCommand.addArguments(Integer.toString(pid));
        this.executor.execute(killCommand);
    } catch (final IOException ioe) {
        throw new GenieServerException("Unable to kill process " + pid, ioe);
    }
}

From source file:com.cip.crane.agent.sheduler.ExecuteTaskThread.java

private void executeJob(ScheduleConf conf, ScheduleStatus status) {
    if (conf == null) {
        LOGGER.error("SchduleConf is empty!");
        status.setStatus(ScheduleStatus.EXECUTE_FAILED);
        status.setFailureInfo("SchduleConf is empty!");
        cs.updateStatus(localIp, taskAttempt, status);
        return;// w  w  w  . java 2s  .  c om
    }
    String attemptID = conf.getAttemptID();
    String taskID = conf.getTaskID();
    String command = conf.getCommand();
    String userName = conf.getUserName();
    String taskType = conf.getTaskType();
    Map<String, String> extendedConfs = conf.getExtendedMap();
    String hadoopName = "hadoop";
    if (extendedConfs != null && extendedConfs.containsKey(HADOOP_NAME)) {
        hadoopName = conf.getExtendedMap().get(HADOOP_NAME);
    }
    if (userName.isEmpty()) {
        userName = "nobody";
    }

    if (attemptID == null || taskID == null || command == null || attemptID.isEmpty() || taskID.isEmpty()
            || command.isEmpty()) {
        LOGGER.error("Configure is not completed!");
        status.setStatus(ScheduleStatus.EXECUTE_FAILED);
        status.setFailureInfo("Configure is not completed!");
        cs.updateStatus(localIp, taskAttempt, status);
        return;
    }

    //create log file stream
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    String date = format.format(new Date());
    String logFilePath = logPath + FILE_SEPRATOR + date + FILE_SEPRATOR + attemptID + ".log";
    String errorFilePath = logPath + FILE_SEPRATOR + date + FILE_SEPRATOR + attemptID + ".error";
    String htmlFileName = attemptID + ".html";
    String htmlFilePath = logPath + FILE_SEPRATOR + date + FILE_SEPRATOR + htmlFileName;
    FileOutputStream logFileStream = null;
    FileOutputStream errorFileStream = null;
    try {
        File logFile = new File(logFilePath);
        File errorFile = new File(errorFilePath);
        logFile.getParentFile().mkdirs();
        logFile.createNewFile();
        errorFile.createNewFile();
        logFileStream = new FileOutputStream(logFilePath);
        errorFileStream = new FileOutputStream(errorFilePath);
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    String path = jobPath + FILE_SEPRATOR + taskID + FILE_SEPRATOR;
    String pidFile = running + FILE_SEPRATOR + '.' + attemptID;
    String returnValueFile = running + FILE_SEPRATOR + "rv." + attemptID;
    int returnCode = 0;
    try {
        LOGGER.debug(taskAttempt + " start execute");

        if (ON_WINDOWS) {
            String escapedCmd = command.replaceAll("\\\\", "\\\\\\\\");
            escapedCmd = escapedCmd.replaceAll("\"", "\\\\\\\"");
            returnCode = executor.execute(attemptID, logFileStream, errorFileStream, escapedCmd);
        } else {
            //hadoop??
            String kdestroyCommand = "";
            String krb5PathCommand = "";
            CommandLine cmdLine;
            if (taskType != null && taskType.equals("hadoop")) {
                krb5PathCommand = String.format(krb5Path, krb5Conf, hadoop, "krb5cc_" + attemptID);
                String kinitCommand = String.format(KINIT_COMMAND_PATTERN, homeDir, hadoopName, hadoopName);
                kinitCommand = String.format(command_pattern, userName, krb5PathCommand, kinitCommand);

                kdestroyCommand = KDESTROY_COMMAND;
                cmdLine = new CommandLine("bash");
                cmdLine.addArgument("-c");
                cmdLine.addArgument(kinitCommand, false);
                int kinitRV = 0;
                try {
                    kinitRV = executor.execute(attemptID, 0, null, cmdLine, logFileStream, errorFileStream);
                } catch (Exception e) {
                    LOGGER.error(e, e);
                    setFailResult(status);
                    return;
                }
                returnCode = kinitRV;
            }
            if (returnCode == 0) {
                //execute cmd
                String escapedCmd = command.replaceAll("\\\\", "\\\\\\\\");
                escapedCmd = escapedCmd.replaceAll("\"", "\\\\\\\"");
                cmdLine = new CommandLine("bash");
                cmdLine.addArgument("-c");
                String mainCmd = String.format(MAIN_COMMAND_PATTERN, pidFile, path, path, env, env, escapedCmd);
                String sotreRvCmd = String.format(STORE_RETURN_VALUE_PATTERN, returnValueFile);
                mainCmd = String.format(command_pattern, userName, krb5PathCommand, mainCmd);
                if (!kdestroyCommand.isEmpty()) {
                    kdestroyCommand = String.format(command_pattern, userName, krb5PathCommand,
                            kdestroyCommand);
                }
                String postCmd = String.format(CLEAN_FILES_PATTERN, pidFile, kdestroyCommand);

                cmdLine.addArgument(mainCmd + " ;" + sotreRvCmd + postCmd, false);

                executor.execute(attemptID, 0, null, cmdLine, logFileStream, errorFileStream);

                try {
                    BufferedReader br = new BufferedReader(new FileReader((new File(returnValueFile))));
                    String returnValStr = br.readLine();
                    br.close();
                    returnCode = Integer.parseInt(returnValStr);
                    new File(returnValueFile).delete();
                } catch (NumberFormatException e) {
                    LOGGER.error(e, e);
                    returnCode = 1;
                } catch (IOException e) {
                    LOGGER.error(e, e);
                    returnCode = 1;
                }
            }
        }
        setResult(returnCode, status);
    } catch (Exception e) {
        LOGGER.error(e, e);
        setFailResult(status);
    }

    try {
        taskHelper.uploadLog(returnCode, errorFilePath, logFilePath, htmlFilePath, htmlFileName);
    } catch (IOException e) {
        LOGGER.error(e, e);
    }

}

From source file:com.dp.bigdata.taurus.agent.sheduler.ExecuteTaskThread.java

private void executeJob(ScheduleConf conf, ScheduleStatus status) {
    if (conf == null) {
        LOGGER.error("SchduleConf is empty!");
        status.setStatus(ScheduleStatus.EXECUTE_FAILED);
        status.setFailureInfo("SchduleConf is empty!");
        cs.updateStatus(localIp, taskAttempt, status);
        return;/*  ww  w.  ja va 2  s .  co  m*/
    }
    String attemptID = conf.getAttemptID();
    String taskID = conf.getTaskID();
    String command = conf.getCommand();
    String userName = conf.getUserName();
    String taskType = conf.getTaskType();
    Map<String, String> extendedConfs = conf.getExtendedMap();
    String hadoopName = "hadoop";
    if (extendedConfs != null && extendedConfs.containsKey(HADOOP_NAME)) {
        hadoopName = conf.getExtendedMap().get(HADOOP_NAME);
    }
    if (userName.isEmpty()) {
        userName = "nobody";
    }

    if (attemptID == null || taskID == null || command == null || attemptID.isEmpty() || taskID.isEmpty()
            || command.isEmpty()) {
        LOGGER.error("Configure is not completed!");
        status.setStatus(ScheduleStatus.EXECUTE_FAILED);
        status.setFailureInfo("Configure is not completed!");
        cs.updateStatus(localIp, taskAttempt, status);
        return;
    }

    //create log file stream
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    String date = format.format(new Date());
    String logFilePath = logPath + FILE_SEPRATOR + date + FILE_SEPRATOR + attemptID + ".log";
    String errorFilePath = logPath + FILE_SEPRATOR + date + FILE_SEPRATOR + attemptID + ".error";
    String htmlFileName = attemptID + ".html";
    String htmlFilePath = logPath + FILE_SEPRATOR + date + FILE_SEPRATOR + htmlFileName;
    FileOutputStream logFileStream = null;
    FileOutputStream errorFileStream = null;
    try {
        File logFile = new File(logFilePath);
        File errorFile = new File(errorFilePath);
        logFile.getParentFile().mkdirs();
        logFile.createNewFile();
        errorFile.createNewFile();
        logFileStream = new FileOutputStream(logFilePath);
        errorFileStream = new FileOutputStream(errorFilePath);
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    String path = jobPath + FILE_SEPRATOR + taskID + FILE_SEPRATOR;
    String pidFile = running + FILE_SEPRATOR + '.' + attemptID;
    String returnValueFile = running + FILE_SEPRATOR + "rv." + attemptID;
    int returnCode = 0;
    try {
        LOGGER.debug(taskAttempt + " start execute");

        if (ON_WINDOWS) {
            String escapedCmd = command.replaceAll("\\\\", "\\\\\\\\");
            escapedCmd = escapedCmd.replaceAll("\"", "\\\\\\\"");
            returnCode = executor.execute(attemptID, logFileStream, errorFileStream, escapedCmd);
        } else {
            //hadoop??
            String kdestroyCommand = "";
            String krb5PathCommand = "";
            CommandLine cmdLine;
            if (taskType != null && taskType.equals("hadoop")) {
                krb5PathCommand = String.format(krb5Path, hadoop, "krb5cc_" + attemptID);
                String kinitCommand = String.format(KINIT_COMMAND_PATTERN, homeDir, hadoopName, hadoopName);
                kinitCommand = String.format(command_pattern, userName, krb5PathCommand, kinitCommand);

                kdestroyCommand = KDESTROY_COMMAND;
                cmdLine = new CommandLine("bash");
                cmdLine.addArgument("-c");
                cmdLine.addArgument(kinitCommand, false);
                int kinitRV = 0;
                try {
                    kinitRV = executor.execute(attemptID, 0, null, cmdLine, logFileStream, errorFileStream);
                } catch (Exception e) {
                    LOGGER.error(e, e);
                    setFailResult(status);
                    return;
                }
                returnCode = kinitRV;
            }
            if (returnCode == 0) {
                //execute cmd
                String escapedCmd = command.replaceAll("\\\\", "\\\\\\\\");
                escapedCmd = escapedCmd.replaceAll("\"", "\\\\\\\"");
                cmdLine = new CommandLine("bash");
                cmdLine.addArgument("-c");
                String mainCmd = String.format(MAIN_COMMAND_PATTERN, pidFile, path, path, env, env, escapedCmd);
                String sotreRvCmd = String.format(STORE_RETURN_VALUE_PATTERN, returnValueFile);
                mainCmd = String.format(command_pattern, userName, krb5PathCommand, mainCmd);
                if (!kdestroyCommand.isEmpty()) {
                    kdestroyCommand = String.format(command_pattern, userName, krb5PathCommand,
                            kdestroyCommand);
                }
                String postCmd = String.format(CLEAN_FILES_PATTERN, pidFile, kdestroyCommand);

                cmdLine.addArgument(mainCmd + ";" + sotreRvCmd + postCmd, false);

                executor.execute(attemptID, 0, null, cmdLine, logFileStream, errorFileStream);

                try {
                    BufferedReader br = new BufferedReader(new FileReader((new File(returnValueFile))));
                    String returnValStr = br.readLine();
                    br.close();
                    returnCode = Integer.parseInt(returnValStr);
                    new File(returnValueFile).delete();
                } catch (NumberFormatException e) {
                    LOGGER.error(e, e);
                    returnCode = 1;
                } catch (IOException e) {
                    LOGGER.error(e, e);
                    returnCode = 1;
                }
            }
        }
        setResult(returnCode, status);
    } catch (Exception e) {
        LOGGER.error(e, e);
        setFailResult(status);
    }

    try {
        taskHelper.uploadLog(returnCode, errorFilePath, logFilePath, htmlFilePath, htmlFileName);
    } catch (IOException e) {
        LOGGER.error(e, e);
    }

}

From source file:com.tupilabs.pbs.PBS.java

/**
 * PBS qstat command for Array Jobs/*from   w ww.j  a  va  2 s .  c  om*/
 * <p>
 * Equivalent to qstat -f -t [param]
 *
 * @param name job name
 * @return list of jobs
 */
public static List<Job> qstatArrayJob(String name) {
    final CommandLine cmdLine = new CommandLine(COMMAND_QSTAT);
    cmdLine.addArgument(PARAMETER_FULL_STATUS);
    cmdLine.addArgument(PARAMETER_ARRAY_JOB_STATUS);
    if (StringUtils.isNotBlank(name)) {
        cmdLine.addArgument(name);
    }

    final OutputStream out = new ByteArrayOutputStream();
    final OutputStream err = new ByteArrayOutputStream();

    DefaultExecuteResultHandler resultHandler;
    try {
        resultHandler = execute(cmdLine, out, err);
        resultHandler.waitFor(DEFAULT_TIMEOUT);
    } catch (ExecuteException e) {
        throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e);
    } catch (InterruptedException e) {
        throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e);
    }

    final int exitValue = resultHandler.getExitValue();
    LOGGER.info("qstat exit value: " + exitValue);

    final List<Job> jobs;
    try {
        jobs = QSTAT_JOBS_PARSER.parse(out.toString());
    } catch (ParseException pe) {
        throw new PBSException("Failed to parse qstat jobs output: " + pe.getMessage(), pe);
    }

    return (jobs == null ? new ArrayList<Job>(0) : jobs);
}

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();//from  w ww  . j  a  va 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;
}