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:dk.netarkivet.harvester.harvesting.controller.AbstractJMXHeritrixController.java

/**
 * Create a BnfHeritrixController object.
 *
 * @param files//from  w ww .  j av  a 2s  .  co m
 *            Files that are used to set up Heritrix.
 */
public AbstractJMXHeritrixController(HeritrixFiles files) {
    ArgumentNotValid.checkNotNull(files, "HeritrixFile files");
    this.files = files;

    SystemUtils.checkPortNotUsed(guiPort);
    SystemUtils.checkPortNotUsed(jmxPort);

    hostName = SystemUtils.getLocalHostName();

    try {
        log.info("Starting Heritrix for " + this);
        /*
         * To start Heritrix, we need to do the following (taken from the
         * Heritrix startup shell script): - set heritrix.home to base dir
         * of Heritrix stuff - set com.sun.management.jmxremote.port to JMX
         * port - set com.sun.management.jmxremote.ssl to false - set
         * com.sun.management.jmxremote.password.file to JMX password file -
         * set heritrix.out to heritrix_out.log - set
         * java.protocol.handler.pkgs=org.archive.net - send processOutput &
         * stderr into heritrix.out - let the Heritrix GUI-webserver listen
         * on all available network interfaces: This is done with argument
         * "--bind /" (default is 127.0.0.1) - listen on a specific port
         * using the port argument: --port <GUI port>
         *
         * We also need to output something like the following to
         * heritrix.out: `date Starting heritrix uname -a java -version
         * JAVA_OPTS ulimit -a
         */
        File heritrixOutputFile = files.getHeritrixOutput();
        StringBuilder settingProperty = new StringBuilder();
        for (File file : Settings.getSettingsFiles()) {
            settingProperty.append(File.pathSeparator);

            String absolutePath = file.getAbsolutePath();
            // check that the settings files not only exist but
            // are readable
            boolean readable = new File(absolutePath).canRead();
            if (!readable) {
                final String errMsg = "The file '" + absolutePath + "' is missing. ";
                log.warn(errMsg);
                throw new IOFailure("Failed to read file '" + absolutePath + "'");
            }
            settingProperty.append(absolutePath);
        }
        if (settingProperty.length() > 0) {
            // delete last path-separator
            settingProperty.deleteCharAt(0);
        }

        List<String> allOpts = new LinkedList<String>();
        allOpts.add(new File(new File(System.getProperty("java.home"), "bin"), "java").getAbsolutePath());
        allOpts.add("-Xmx" + Settings.get(HarvesterSettings.HERITRIX_HEAP_SIZE));
        allOpts.add("-Dheritrix.home=" + files.getCrawlDir().getAbsolutePath());

        String jvmOptsStr = Settings.get(HarvesterSettings.HERITRIX_JVM_OPTS);
        if ((jvmOptsStr != null) && (!jvmOptsStr.isEmpty())) {
            String[] add = jvmOptsStr.split(" ");
            allOpts.addAll(Arrays.asList(add));
        }

        allOpts.add("-Dcom.sun.management.jmxremote.port=" + jmxPort);
        allOpts.add("-Dcom.sun.management.jmxremote.ssl=false");
        // check that JMX password and access files are readable.
        // TODO This should probably be extracted to a method?
        File passwordFile = files.getJmxPasswordFile();
        String pwAbsolutePath = passwordFile.getAbsolutePath();
        if (!passwordFile.canRead()) {
            final String errMsg = "Failed to read the password file '" + pwAbsolutePath
                    + "'. It is possibly missing.";
            log.warn(errMsg);
            throw new IOFailure(errMsg);
        }
        File accessFile = files.getJmxAccessFile();
        String acAbsolutePath = accessFile.getAbsolutePath();
        if (!accessFile.canRead()) {
            final String errMsg = "Failed to read the access file '" + acAbsolutePath
                    + "'. It is possibly missing.";
            log.warn(errMsg);
            throw new IOFailure(errMsg);
        }
        allOpts.add("-Dcom.sun.management.jmxremote.password.file=" + new File(pwAbsolutePath));
        allOpts.add("-Dcom.sun.management.jmxremote.access.file=" + new File(acAbsolutePath));
        allOpts.add("-Dheritrix.out=" + heritrixOutputFile.getAbsolutePath());
        allOpts.add("-Djava.protocol.handler.pkgs=org.archive.net");
        allOpts.add("-Ddk.netarkivet.settings.file=" + settingProperty);
        allOpts.add(Heritrix.class.getName());
        allOpts.add("--bind");
        allOpts.add("/");
        allOpts.add("--port=" + guiPort);
        allOpts.add("--admin=" + getHeritrixAdminName() + ":" + getHeritrixAdminPassword());

        String[] args = allOpts.toArray(new String[allOpts.size()]);
        log.info("Starting Heritrix process with args" + Arrays.toString(args));
        log.debug("The JMX timeout is set to " + TimeUtils.readableTimeInterval(JMXUtils.getJmxTimeout()));

        ProcessBuilder builder = new ProcessBuilder(args);

        updateEnvironment(builder.environment());
        FileUtils.copyDirectory(new File("lib/heritrix"), files.getCrawlDir());
        builder.directory(files.getCrawlDir());
        builder.redirectErrorStream(true);
        writeSystemInfo(heritrixOutputFile, builder);
        FileUtils.appendToFile(heritrixOutputFile, "Working directory: " + files.getCrawlDir());
        addProcessKillerHook();
        heritrixProcess = builder.start();
        ProcessUtils.writeProcessOutput(heritrixProcess.getInputStream(), heritrixOutputFile,
                collectionThreads);
    } catch (IOException e) {
        throw new IOFailure("Error starting Heritrix process", e);
    }
}

From source file:org.pepstock.jem.node.tasks.JobTask.java

/**
 * Internal method which creates the process, preparing environment
 * variables, creating directories, setting listener of output and error
 * log, and wait for end of job execution.
 * //from  w  w  w .  j a  v a  2 s  . com
 * @return return code of execution
 * @throws NodeMessageException 
 * @throws InterruptedException 
 * @throws Exception occurs if there is any error
 */

private int launchProcess() throws IOException, NodeMessageException, InterruptedException {
    int returnCode = 0;
    Process process = null;
    try {
        String user = job.isUserSurrogated() ? job.getJcl().getUser() : job.getUser();
        AbstractFactory currFactory = (AbstractFactory) getFactory();
        boolean useSudo = currFactory.isUseSudo() && !user.equalsIgnoreCase(Main.getNode().getUser());

        // create a process builder
        ProcessBuilder builder = new ProcessBuilder();
        Shell shell = CurrentPlatform.getInstance().getShell();
        String command = CurrentPlatform.getInstance().getCommand(job, getCommand(), useSudo);
        builder.command(shell.getName(), shell.getParameters(), command);

        // set directory where execute process
        if (getStartDir() != null) {
            builder.directory(new File(getStartDir()));
        }

        // load variable environment from a temporary maps that you can use
        // inside of configure method.
        Map<String, String> env = getEnv();
        Map<String, String> map = builder.environment();
        for (Map.Entry<String, String> e : env.entrySet()) {
            map.put(e.getKey(), e.getValue());
        }

        // writes JEM log with headers
        JobLogManager.printHeader(job);

        // start process and save instance
        process = builder.start();
        // wait for end of job execution
        returnCode = process.waitFor();

        // check if cancelled, setting the return code 222
        if (isCancelled) {
            returnCode = Result.CANCELED;
        }
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
    return returnCode;
}

From source file:com.photon.phresco.plugins.xcode.CodeValidation.java

public void execute() throws MojoExecutionException {

    try {/*from w  w  w. jav a2  s.co m*/
        ProcessBuilder pb = new ProcessBuilder(check);
        // Include errors in output
        pb.redirectErrorStream(true);

        List<String> commands = pb.command();

        commands.add("-o");
        commands.add("make");
        commands.add("xcodebuild");
        commands.add("-scheme");
        commands.add(scheme);
        commands.add("-project");
        commands.add(xcodeProject);
        commands.add("build");
        getLog().info("List of commands" + pb.command());
        // pb.command().add("install");
        pb.directory(new File(basedir));
        Process child = pb.start();

        // Consume subprocess output and write to stdout for debugging
        InputStream is = new BufferedInputStream(child.getInputStream());
        int singleByte = 0;
        while ((singleByte = is.read()) != -1) {
            // output.write(buffer, 0, bytesRead);
            System.out.write(singleByte);
        }

        child.waitFor();
        int exitValue = child.exitValue();
        getLog().info("Exit Value: " + exitValue);
        if (exitValue != 0) {
            throw new MojoExecutionException("Compilation error occured. Resolve the error(s) and try again!");
        }

    } catch (IOException e) {
        getLog().error("An IOException occured.");
        throw new MojoExecutionException("An IOException occured", e);
    } catch (InterruptedException e) {
        getLog().error("The clean process was been interrupted.");
        throw new MojoExecutionException("The clean process was been interrupted", e);
    }
    createreport();
}

From source file:org.neo4j.io.pagecache.impl.SingleFilePageSwapperTest.java

@Test(expected = FileLockException.class)
public void creatingSwapperForExternallyLockedFileMustThrow() throws Exception {
    assumeFalse("No file locking on Windows", SystemUtils.IS_OS_WINDOWS); // no file locking on Windows.

    PageSwapperFactory factory = swapperFactory();
    DefaultFileSystemAbstraction fs = new DefaultFileSystemAbstraction();
    factory.setFileSystemAbstraction(fs);
    File file = testDir.file("file");

    fs.create(file).close();//from   ww w .  ja va  2  s.  co  m

    ProcessBuilder pb = new ProcessBuilder(ProcessUtil.getJavaExecutable().toString(), "-cp",
            ProcessUtil.getClassPath(), LockThisFileProgram.class.getCanonicalName(), file.getAbsolutePath());
    File wd = new File("target/test-classes").getAbsoluteFile();
    pb.directory(wd);
    Process process = pb.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    assertThat(reader.readLine(), is(LockThisFileProgram.LOCKED_OUTPUT));

    try {
        createSwapper(factory, file, 4, NO_CALLBACK, true);
    } finally {
        process.getOutputStream().write(0);
        process.getOutputStream().flush();
        process.waitFor();
    }
}

From source file:org.apache.nifi.processors.standard.ExecuteProcess.java

protected Future<?> launchProcess(final ProcessContext context, final List<String> commandStrings,
        final Long batchNanos, final ProxyOutputStream proxyOut) throws IOException {

    final Boolean redirectErrorStream = context.getProperty(REDIRECT_ERROR_STREAM).asBoolean();

    final ProcessBuilder builder = new ProcessBuilder(commandStrings);
    final String workingDirName = context.getProperty(WORKING_DIR).getValue();
    if (workingDirName != null) {
        builder.directory(new File(workingDirName));
    }/*from w w  w.  j  a  v a2 s .com*/

    final Map<String, String> environment = new HashMap<>();
    for (final Map.Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) {
        if (entry.getKey().isDynamic()) {
            environment.put(entry.getKey().getName(), entry.getValue());
        }
    }

    if (!environment.isEmpty()) {
        builder.environment().putAll(environment);
    }

    getLogger().info("Start creating new Process > {} ", new Object[] { commandStrings });
    this.externalProcess = builder.redirectErrorStream(redirectErrorStream).start();

    // Submit task to read error stream from process
    if (!redirectErrorStream) {
        executor.submit(new Runnable() {
            @Override
            public void run() {
                try (final BufferedReader reader = new BufferedReader(
                        new InputStreamReader(externalProcess.getErrorStream()))) {
                    reader.lines().filter(line -> line != null && line.length() > 0).forEach(getLogger()::warn);
                } catch (final IOException ioe) {
                }
            }
        });
    }

    // Submit task to read output of Process and write to FlowFile.
    failure = new AtomicBoolean(false);
    final Future<?> future = executor.submit(new Callable<Object>() {
        @Override
        public Object call() throws IOException {
            try {
                if (batchNanos == null) {
                    // if we aren't batching, just copy the stream from the
                    // process to the flowfile.
                    try (final BufferedInputStream bufferedIn = new BufferedInputStream(
                            externalProcess.getInputStream())) {
                        final byte[] buffer = new byte[4096];
                        int len;
                        while ((len = bufferedIn.read(buffer)) > 0) {

                            // NB!!!! Maybe all data should be read from
                            // input stream in case of !isScheduled() to
                            // avoid subprocess deadlock?
                            // (we just don't write data to proxyOut)
                            // Or because we don't use this subprocess
                            // anymore anyway, we don't care?
                            if (!isScheduled()) {
                                return null;
                            }

                            proxyOut.write(buffer, 0, len);
                        }
                    }
                } else {
                    // we are batching, which means that the output of the
                    // process is text. It doesn't make sense to grab
                    // arbitrary batches of bytes from some process and send
                    // it along as a piece of data, so we assume that
                    // setting a batch during means text.
                    // Also, we don't want that text to get split up in the
                    // middle of a line, so we use BufferedReader
                    // to read lines of text and write them as lines of text.
                    try (final BufferedReader reader = new BufferedReader(
                            new InputStreamReader(externalProcess.getInputStream()))) {
                        String line;

                        while ((line = reader.readLine()) != null) {
                            if (!isScheduled()) {
                                return null;
                            }

                            proxyOut.write((line + "\n").getBytes(StandardCharsets.UTF_8));
                        }
                    }
                }
            } catch (final IOException ioe) {
                failure.set(true);
                throw ioe;
            } finally {
                try {
                    // Since we are going to exit anyway, one sec gives it an extra chance to exit gracefully.
                    // In the future consider exposing it via configuration.
                    boolean terminated = externalProcess.waitFor(1000, TimeUnit.MILLISECONDS);
                    int exitCode = terminated ? externalProcess.exitValue() : -9999;
                    getLogger().info("Process finished with exit code {} ", new Object[] { exitCode });
                } catch (InterruptedException e1) {
                    Thread.currentThread().interrupt();
                }
            }

            return null;
        }
    });

    return future;
}

From source file:com.searchcode.app.jobs.IndexSvnRepoJob.java

public String getCurrentRevision(String repoLocations, String repoName) {
    String currentRevision = "";

    try {// w  ww  .j a  v  a 2 s .  c  o m
        ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "info", "--xml");
        processBuilder.directory(new File(repoLocations + repoName));
        Process process = processBuilder.start();

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();
        String line;

        while ((line = br.readLine()) != null) {
            sb.append(Helpers.removeUTF8BOM(line));
        }

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

        Singleton.getLogger().info("getCurrentRevision: " + repoName + " " + sb.toString());

        Document doc = dBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes()));
        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName("entry");

        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;
                currentRevision = eElement.getAttribute("revision");
            }
        }
    } catch (IOException | ParserConfigurationException | SAXException ex) {
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + "\n with message: " + ex.getMessage());
    }

    return currentRevision;
}

From source file:tachyon.java.manager.JavaFxManager.java

@Override
public void runIndividualFile(ProcessItem item, Program pro) {
    if (pro instanceof JavaProgram) {
        JavaProgram program = (JavaProgram) pro;
        compile(item);//from w  w w  .j a v a 2s. c o  m
        if (!item.isCancelled()) {
            ProcessBuilder pb;
            if (OS.contains("win")) {
                pb = getWindowsRunFileString(program);
            } else {
                pb = getMacRunFileString(program);
            }
            pb.directory(getProject().getBuild().toFile());
            try {
                Process start = pb.start();
                item.setName("Launching File : " + program.getClassName());
                item.setProcess(start);
                ProcessPool.getPool().addItem(item);
                (new Thread(new Project.OutputReader(start.getInputStream(), item.getConsole()))).start();
                (new Thread(new Project.ErrorReader(start.getErrorStream(), item.getConsole()))).start();
                int waitFor = start.waitFor();
                System.out.println(waitFor);
            } catch (IOException | InterruptedException e) {
            }
        }
    }
}

From source file:com.searchcode.app.jobs.IndexSvnRepoJob.java

private CodeOwner getInfoExternal(int codeLinesSize, String repoName, String repoLocations, String fileName) {
    CodeOwner owner = new CodeOwner("Unknown", codeLinesSize, (int) (System.currentTimeMillis() / 1000));

    try {/*from   ww  w .  j  av  a 2  s.c  o m*/
        ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "info", "--xml", fileName);
        processBuilder.directory(new File(repoLocations + repoName));

        Process process = processBuilder.start();

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        StringBuffer bf = new StringBuffer();

        while ((line = br.readLine()) != null) {
            bf.append(Helpers.removeUTF8BOM(line));
        }

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new ByteArrayInputStream(bf.toString().getBytes()));
        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName("entry");

        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;

                Node node = eElement.getElementsByTagName("commit").item(0);
                Element e = (Element) node;

                owner.setName(e.getElementsByTagName("author").item(0).getTextContent());
            }
        }

    } catch (IOException | ParserConfigurationException | SAXException ex) {
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + "\n with message: " + ex.getMessage());
    }

    return owner;
}

From source file:net.doubledoordev.cmd.CurseModpackDownloader.java

private Process runForgeInstaller(File file) throws IOException {
    ProcessBuilder processBuilder = new ProcessBuilder("java", "-jar", file.getName(), "--installServer");
    StringBuilder joiner = new StringBuilder("Running forge installer with command: ");
    for (String cmd : processBuilder.command())
        joiner.append(cmd).append(' ');
    if (!quiet)//from  w ww.  j  a va  2 s  .co m
        logger.println(joiner.toString());
    processBuilder.directory(output);
    processBuilder.redirectErrorStream(true);
    return processBuilder.start();
}

From source file:org.jenkins_ci.update_center.Main.java

/**
 * Generates symlink to the latest version.
 *//*ww  w.  j  av  a2 s.  co m*/
protected void createLatestSymlink(PluginHistory hpi, HPI latest) throws InterruptedException, IOException {
    File dir = new File(download, "plugins/" + hpi.artifactId);
    new File(dir, "latest").delete();

    ProcessBuilder pb = new ProcessBuilder();
    pb.command("ln", "-s", latest.version, "latest");
    pb.directory(dir);
    int r = pb.start().waitFor();
    if (r != 0) {
        throw new IOException("ln failed: " + r);
    }
}