Example usage for java.lang ProcessBuilder directory

List of usage examples for java.lang ProcessBuilder directory

Introduction

In this page you can find the example usage for java.lang ProcessBuilder directory.

Prototype

File directory

To view the source code for java.lang ProcessBuilder directory.

Click Source Link

Usage

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

private void checkoutEnvironment(Repository repository, String site) {
    Git git = null;/*from w w  w .ja v a 2 s  .com*/
    try {
        Ref branchRef = repository.findRef(environment);
        git = new Git(repository);
        git.checkout().setCreateBranch(true).setName(environment)
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                .setStartPoint("origin/" + environment).call();
        git.fetch().call();
        git.pull().call();
    } catch (RefNotFoundException e) {
        try {
            git.checkout().setOrphan(true).setName(environment).call();
            ProcessBuilder pb = new ProcessBuilder();
            pb.command("git", "rm", "-rf", ".");
            pb.directory(repository.getDirectory().getParentFile());
            Process p = pb.start();
            p.waitFor();

            git.commit().setMessage("initial content").setAllowEmpty(true).call();
        } catch (GitAPIException | InterruptedException | IOException e1) {
            logger.error("Error checking out environment store branch for site " + site + " environment "
                    + environment, e1);
        }
    } catch (IOException | GitAPIException e) {
        logger.error(
                "Error checking out environment store branch for site " + site + " environment " + environment,
                e);
    }
}

From source file:jenkins.plugins.tanaguru.TanaguruRunner.java

public void callTanaguruService() throws IOException, InterruptedException {
    File logFile = TanaguruRunnerBuilder.createTempFile(contextDir, "log-" + new Random().nextInt() + ".log",
            "");//from   w  w w  . j a  va 2s  .  c  o  m
    File scenarioFile = TanaguruRunnerBuilder.createTempFile(contextDir, scenarioName + "_#" + buildNumber,
            TanaguruRunnerBuilder.forceVersion1ToScenario(scenario));

    ProcessBuilder pb = new ProcessBuilder(tgScriptName, "-f", firefoxPath, "-r", referential, "-l", level,
            "-d", displayPort, "-x", xmxValue, "-o", logFile.getAbsolutePath(), "-t", "Scenario",
            scenarioFile.getAbsolutePath());

    pb.directory(contextDir);
    pb.redirectErrorStream(true);
    Process p = pb.start();
    p.waitFor();

    extractDataAndPrintOut(logFile, listener.getLogger());

    if (!isDebug) {
        FileUtils.deleteQuietly(logFile);
    }

    FileUtils.deleteQuietly(scenarioFile);
}

From source file:nz.co.fortytwo.freeboard.server.util.ChartProcessor.java

/**
 * Executes a script which invokes GDAL and imagemagick to process the chart
 * into a tile pyramid/*from w  w w .  ja va 2  s. c om*/
 * 
 * @param config2
 * @param chartFile
 * @param chartName
 * @param list 
 * @throws IOException 
 * @throws InterruptedException 
 */
@SuppressWarnings("static-access")
private void executeGdal(File chartFile, String chartName, List<String> argList, List<String> tilesList)
        throws IOException, InterruptedException {
    File processDir = chartFile.getParentFile();
    //mkdir $1
    //gdal_translate -of vrt -expand rgba $1.kap temp.vrt
    ProcessBuilder pb = new ProcessBuilder(argList);
    pb.directory(processDir);
    //pb.inheritIO();
    if (manager) {
        ForkWorker fork = new ForkWorker(textArea, pb);
        fork.execute();
        while (!fork.isDone()) {
            Thread.currentThread().sleep(500);
            //System.out.print(".");
        }
    } else {
        Process p = pb.start();
        p.waitFor();
        if (p.exitValue() > 0) {
            if (manager) {
                System.out.print("ERROR:gdal_translate did not complete normally\n");
            }
            logger.error("gdal_translate did not complete normally");
            return;
        } else {
            System.out.print("Completed gdal_translate\n");
        }
    }
    //gdal2tiles.py temp.vrt $1
    File tileDir = new File(processDir, chartName);
    tileDir.mkdir();
    pb = new ProcessBuilder("gdal2tiles.py", "temp.vrt", chartName);
    pb.directory(processDir);
    //pb.inheritIO();
    if (manager) {
        ForkWorker fork = new ForkWorker(textArea, pb);
        fork.execute();
        while (!fork.isDone()) {
            Thread.currentThread().sleep(500);
            //System.out.print(".");
        }
        System.out.print("Completed gdal2tiles\n");
    } else {
        Process p = pb.start();
        p.waitFor();
        if (p.exitValue() > 0) {
            if (manager) {
                System.out.print("ERROR:gdal2tiles did not complete normally\n");
            }
            logger.error("gdal2tiles did not complete normally");
            return;
        } else {
            System.out.print("Completed gdal2tiles\n");
        }
    }

    //now make images transparent
    //recurse dirs
    recurseDirs(tileDir);

}

From source file:service.impl.DatabaseBackupServiceImpl.java

/**
 * To be compatible to Windows 7 and 10 (the original function could just work on win 10), 
 * Using the ProcessBuilder as the main class to initialize the process and generate the file.
 * The ProcessBuilder receives the command as the separated string (by space).
 * The backup file couldn't be generated without calling waitFor().
 * After this function, the uploadFtp() will be called, and upload this file to remote, one day one file.
 * The default path of generated file is located on C:\\
 * This path is defined on the properties backup.properties. 
 *  //from w  w w. ja v a  2  s  . c om
 */
@Override
public void backup() throws ServiceException {
    Process proc = null;

    try {
        ProcessBuilder procBuilder = new ProcessBuilder("cmd", "/c", mysqlBinPath + "mysqldump",
                "--lock-all-tables", "--flush-logs", "-h", srcHost, "-u" + srcUsername, "-p" + srcPassword,
                "--databases", srcDbname);

        procBuilder.directory(new File(bakSqlPath));
        File sqlBackupFile = new File(bakSqlPath + System.getProperty("file.separator") + bakSqlFile);
        sqlBackupFile.delete();
        sqlBackupFile.createNewFile();

        procBuilder.redirectErrorStream(true);
        procBuilder.redirectOutput(Redirect.to(sqlBackupFile));
        proc = procBuilder.start();
        proc.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
        throw new ServiceException(e);
    } finally {
        try {
            if (proc != null) {
                proc.destroy();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:eu.excitementproject.eop.distsim.redisinjar.EmbeddedRedisServerRunner.java

private ProcessBuilder createRedisProcessBuilder() {

    ProcessBuilder pb = null;
    if ((rdbDir == null) || (rdbName == null)) {
        pb = new ProcessBuilder(command.getAbsolutePath(), "--maxmemory", REDIS_MAXMEMORY, "--port",
                Integer.toString(port));
        pb.directory(command.getParentFile());
    } else {//from  ww w .j a  va2 s . c  o  m
        pb = new ProcessBuilder(command.getAbsolutePath(), "--maxmemory", REDIS_MAXMEMORY, "--port",
                Integer.toString(port), "--dir", rdbDir, "--dbfilename", rdbName);
        pb.directory(command.getParentFile());
    }
    pb.redirectErrorStream(true); // both STDERR/STDOUT via  getInputStream:  needed for rare cases where run fails due to GLIBC problem, etc. 
    return pb;
}

From source file:com.ecofactor.qa.automation.platform.ops.impl.AndroidOperations.java

/**
 * Start Appium server.//from   ww w . j  a v  a 2  s .c  o  m
 * @see com.ecofactor.qa.automation.mobile.ops.impl.AbstractMobileOperations#startAppiumServer()
 */
@Override
public void startAppiumServer() {

    setLogString(LogSection.START, "Start appium server", true);
    final String deviceId = getDeviceIdParam();
    if (!deviceProps.get(deviceId + DEVICE_STATE).equals("Online")) {
        setLogString("Appium will not be started since the device state is = "
                + deviceProps.get(deviceId + DEVICE_STATE) + ".", true);
        return;
    }
    final String appiumHome = System.getenv("APPIUM_HOME");
    setLogString("APPIUM_HOME : " + appiumHome, true);
    if (appiumHome == null || appiumHome.isEmpty()) {
        setErrorMsg("\033[41;1mPlease set APPIUM_HOME environment variable and try again.");
        setLogString(errorMsg, true);
        hasErrors = true;
        return;
    }
    generateNodeConfig();
    final List<String> commands = arrayToList("node", ".", "-U", deviceId, "-p", DEFAULT_PORT, "--full-reset");
    String listToString = StringUtil.listToString(commands, " ");
    final int indexOfK = listToString.lastIndexOf("/k");
    listToString = listToString.substring(indexOfK + 2, listToString.length());
    setLogString("Command to Start Appium Server:" + listToString, true);

    final ProcessBuilder process = new ProcessBuilder(commands);
    process.directory(new File(appiumHome));
    process.redirectOutput(new File("outPut.txt"));
    process.redirectError(new File("error.txt"));
    startProcessBuilder(process);
    mediumWait();
    setLogString(LogSection.END, "Started appium server", true);
}

From source file:org.openengsb.connector.maven.internal.MavenServiceImpl.java

private Process configureProcess(File dir, List<String> command) throws IOException {
    ProcessBuilder builder = new ProcessBuilder(command);
    Process process = builder.directory(dir).start();
    return process;
}

From source file:org.sonatype.nexus.testsuite.obr.ObrITSupport.java

protected void deployUsingObrIntoFelix(final String repoId) throws Exception {
    final File felixHome = util.resolveFile("target/org.apache.felix.main.distribution-3.2.2");
    final File felixRepo = util.resolveFile("target/felix-local-repository");
    final File felixConfig = testData().resolveFile("felix.properties");

    // ensure we have an obr.xml
    final Content content = content();
    final Location obrLocation = new Location(repoId, ".meta/obr.xml");
    content.download(obrLocation, new File(testIndex().getDirectory("downloads"), repoId + "-obr.xml"));

    FileUtils.deleteDirectory(new File(felixHome, "felix-cache"));
    FileUtils.deleteDirectory(new File(felixRepo, ".meta"));

    final ProcessBuilder pb = new ProcessBuilder("java", "-Dfelix.felix.properties=" + felixConfig.toURI(),
            "-jar", "bin/felix.jar");
    pb.directory(felixHome);
    pb.redirectErrorStream(true);/*from  w  w  w .  j av  a 2s .  c  om*/
    final Process p = pb.start();

    final Object lock = new Object();

    final Thread t = new Thread(new Runnable() {
        public void run() {
            // just a safeguard, if felix get stuck kill everything
            try {
                synchronized (lock) {
                    lock.wait(5 * 1000 * 60);
                }
            } catch (final InterruptedException e) {
                // ignore
            }
            p.destroy();
        }
    });
    t.setDaemon(true);
    t.start();

    synchronized (lock) {
        final InputStream input = p.getInputStream();
        final OutputStream output = p.getOutputStream();
        waitFor(input, "g!");

        output.write(("obr:repos add " + nexus().getUrl() + "content/" + obrLocation.toContentPath() + "\r\n")
                .getBytes());
        output.flush();
        waitFor(input, "g!");

        output.write(("obr:repos remove http://felix.apache.org/obr/releases.xml\r\n").getBytes());
        output.flush();
        waitFor(input, "g!");

        output.write(("obr:repos list\r\n").getBytes());
        output.flush();
        waitFor(input, "g!");

        output.write("obr:deploy -s org.apache.felix.webconsole\r\n".getBytes());
        output.flush();
        waitFor(input, "done.");

        p.destroy();

        lock.notifyAll();
    }
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

private void applyPatch(Repository envStoreRepo, String site) {
    String tempPath = System.getProperty("java.io.tmpdir");
    if (tempPath == null) {
        tempPath = "temp";
    }/*w  w  w. j a  va2s . c  o  m*/
    Path patchPath = Paths.get(tempPath, "patch" + site + ".bin");
    Process p;
    try {
        ProcessBuilder pb = new ProcessBuilder();
        pb.command("git", "apply", patchPath.toAbsolutePath().normalize().toString());
        pb.directory(envStoreRepo.getDirectory().getParentFile());
        p = pb.start();
        p.waitFor();
    } catch (Exception e) {
        logger.error("Error applying patch for site: " + site, e);
    }
}

From source file:org.eclipse.gyrex.jobs.internal.externalprocess.ExternalProcessJob.java

@Override
protected IStatus run(final IProgressMonitor monitor) {
    final ProcessBuilder builder = new ProcessBuilder();

    log.debug("Command: {}", command);
    builder.command(command);//from   w w w.j a v  a 2  s. com

    if (workingDirectory != null) {
        log.debug("Using working directory: {}", workingDirectory);
        builder.directory(workingDirectory);
    }

    if (clearEnvironment) {
        builder.environment().clear();
        log.debug("Cleared environment!");
    } else {
        // remove all Gyrex specific settings for security reasons
        final Iterator<Entry<String, String>> entries = builder.environment().entrySet().iterator();
        while (entries.hasNext()) {
            final Map.Entry<java.lang.String, java.lang.String> e = entries.next();
            if (StringUtils.startsWithIgnoreCase(e.getKey(), "gyrex")) {
                log.debug("Removing Gyrex specific environment variable: {}", e.getKey());
                entries.remove();
            }
        }
    }

    setEnvironmentVariable(builder, "WORKSPACE", Platform.getInstanceLocation().toOSString());
    setEnvironmentVariable(builder, "JOB_ID", jobId);

    if (additionalEnvironment != null) {
        for (final Entry<String, String> e : additionalEnvironment.entrySet()) {
            log.debug("Additional environment variable: {} = {}", e.getKey(), e.getValue());
            builder.environment().put(e.getKey(), e.getValue());
        }
    }

    AsyncLoggingInputStreamReader inputStreamReader = null, errorStreamReader = null;
    try {
        final Process p = builder.start();
        inputStreamReader = new AsyncLoggingInputStreamReader(jobId + " [OUT Reader]", p.getInputStream(), log,
                Level.INFO);
        errorStreamReader = new AsyncLoggingInputStreamReader(jobId + " [ERR Reader]", p.getErrorStream(), log,
                Level.ERROR);

        final int result = p.waitFor();
        if (result != exitValue)
            return new Status(IStatus.ERROR, JobsActivator.SYMBOLIC_NAME,
                    "Process finished with unexpected exit value: " + result);

    } catch (final InterruptedException e) {
        log.warn("Interrupted while waiting for the process to finish.", e);
        Thread.currentThread().interrupt();
        return Status.CANCEL_STATUS;
    } catch (final Exception | AssertionError | LinkageError e) {
        log.error("Error starting process. {} ", e.getMessage(), e);
        return new Status(IStatus.ERROR, JobsActivator.SYMBOLIC_NAME,
                "Error starting process: " + e.getMessage(), e);
    } finally {
        if (inputStreamReader != null) {
            inputStreamReader.close();
        }
        if (errorStreamReader != null) {
            errorStreamReader.close();
        }
    }

    if (StringUtils.isNotBlank(inputStreamReader.getLastLine()))
        return new Status(IStatus.OK, JobsActivator.SYMBOLIC_NAME, inputStreamReader.getLastLine());

    return Status.OK_STATUS;
}