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:me.philnate.textmanager.utils.PDFCreator.java

@SuppressWarnings("deprecation")
private void preparePDF() {
    try {// w ww  .  j  a  v a  2 s  . c  om
        File path = new File(SystemUtils.getUserDir(), "template");
        File template = new File(path, Setting.find("template").getValue());

        Velocity.setProperty("file.resource.loader.path", path.getAbsolutePath());
        Velocity.init();
        VelocityContext ctx = new VelocityContext();

        // User data/Settings
        for (Setting setting : ds.find(Setting.class).asList()) {
            ctx.put(setting.getKey(), setting.getValue());
        }

        NumberFormat format = NumberFormat.getNumberInstance(new Locale(Setting.find("locale").getValue()));
        // #60 always show 2 digits for fraction no matter if right most(s)
        // are zero
        format.setMinimumFractionDigits(2);
        format.setMaximumFractionDigits(2);
        ctx.put("number", format);
        // TODO update schema to have separate first and lastname
        // Customer data
        ctx.put("customer", customer);

        // General data
        ctx.put("month", new DateFormatSymbols().getMonths()[month]);
        ctx.put("math", new MathTool());
        // Billing data
        ctx.put("allItems", BillingItem.find(customer.getId(), year, month));
        ctx.put("billNo", bill.getBillNo());

        StringWriter writer = new StringWriter();
        Velocity.mergeTemplate(template.getName(), ctx, writer);
        File filledTemplate = new File(path, bill.getBillNo() + ".tex");
        FileUtils.writeStringToFile(filledTemplate, writer.toString(), "ISO-8859-1");

        ProcessBuilder pdfLatex = new ProcessBuilder(Setting.find("pdfLatex").getValue(),
                "-interaction nonstopmode", "-output-format pdf", filledTemplate.toString());

        // Saving template file (just in case it may be needed later
        GridFSFile texFile = tex.createFile(filledTemplate);
        texFile.put("month", month);
        texFile.put("year", year);
        texFile.put("customerId", customer.getId());
        texFile.save();

        pdfLatex.directory(path);
        String pdfPath = filledTemplate.toString().replaceAll("tex$", "pdf");
        if (0 == printOutputStream(pdfLatex)) {
            // display Bill in DocumentViewer
            new ProcessBuilder(Setting.find("pdfViewer").getValue(), pdfPath).start().waitFor();
            GridFSFile pdfFile = pdf.createFile(new File(pdfPath));
            pdfFile.put("month", month);
            pdfFile.put("year", year);
            pdfFile.put("customerId", customer.getId());
            pdf.remove(QueryBuilder.start("month").is(month).and("year").is(year).and("customerId")
                    .is(customer.getId()).get());
            pdfFile.save();
            File[] files = path.listFiles((FileFilter) new WildcardFileFilter(bill.getBillNo() + ".*"));
            for (File file : files) {
                FileUtils.forceDelete(file);
            }
        } else {
            new JOptionPane(
                    "Bei der Erstellung der Rechnung ist ein Fehler aufgetreten. Es wurde keine Rechnung erstellt.\n Bitte Schauen sie in die Logdatei fr nhere Fehlerinformationen.",
                    JOptionPane.ERROR_MESSAGE).setVisible(true);
        }
    } catch (IOException e) {
        Throwables.propagate(e);
    } catch (InterruptedException e) {
        Throwables.propagate(e);
    }
}

From source file:org.apache.flume.test.util.StagedInstall.java

public synchronized void startAgent(String name, Properties properties) throws Exception {
    if (process != null) {
        throw new Exception("A process is already running");
    }/*from   w  w w  .java  2s.  c  om*/
    LOGGER.info("Starting process for agent: " + name + " using config: " + properties);

    File configFile = createConfigurationFile(name, properties);
    configFilePath = configFile.getCanonicalPath();

    String configFileName = configFile.getName();
    String logFileName = "flume-" + name + "-" + configFileName.substring(0, configFileName.indexOf('.'))
            + ".log";

    LOGGER.info("Created configuration file: " + configFilePath);

    String[] cmdArgs = { launchScriptPath, "agent", "-n", name, "-f", configFilePath, "-c", confDirPath,
            "-D" + ENV_FLUME_LOG_DIR + "=" + logDirPath,
            "-D" + ENV_FLUME_ROOT_LOGGER + "=" + ENV_FLUME_ROOT_LOGGER_VALUE,
            "-D" + ENV_FLUME_LOG_FILE + "=" + logFileName };

    StringBuilder sb = new StringBuilder("");
    for (String cmdArg : cmdArgs) {
        sb.append(cmdArg).append(" ");
    }

    LOGGER.info("Using command: " + sb.toString());

    ProcessBuilder pb = new ProcessBuilder(cmdArgs);

    Map<String, String> env = pb.environment();

    LOGGER.debug("process environment: " + env);
    pb.directory(baseDir);
    pb.redirectErrorStream(true);

    process = pb.start();
    consumer = new ProcessInputStreamConsumer(process.getInputStream());
    consumer.start();

    shutdownHook = new ProcessShutdownHook();
    Runtime.getRuntime().addShutdownHook(shutdownHook);

    Thread.sleep(3000); // sleep for 3s to let system initialize
}

From source file:alluxio.multi.process.MultiProcessCluster.java

/**
 * Copies the work directory to the artifacts folder.
 *//*w  w w.  jav  a 2 s.co m*/
public synchronized void saveWorkdir() throws IOException {
    Preconditions.checkState(mState == State.STARTED,
            "cluster must be started before you can save its work directory");
    ARTIFACTS_DIR.mkdirs();

    File tarball = new File(mWorkDir.getParentFile(), mWorkDir.getName() + ".tar.gz");
    // Tar up the work directory.
    ProcessBuilder pb = new ProcessBuilder("tar", "-czf", tarball.getName(), mWorkDir.getName());
    pb.directory(mWorkDir.getParentFile());
    pb.redirectOutput(Redirect.appendTo(TESTS_LOG));
    pb.redirectError(Redirect.appendTo(TESTS_LOG));
    Process p = pb.start();
    try {
        p.waitFor();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
    }
    // Move tarball to artifacts directory.
    File finalTarball = new File(ARTIFACTS_DIR, tarball.getName());
    FileUtils.moveFile(tarball, finalTarball);
    LOG.info("Saved cluster {} to {}", mClusterName, finalTarball.getAbsolutePath());
}

From source file:com.hellblazer.process.impl.AbstractManagedProcess.java

/**
 * The actual execution process. Control will not return until the command
 * list execution has finished./* w  ww.  j av a  2s  .c o  m*/
 * 
 * @param commands
 *            - the command list to execute
 * 
 * @throws IOException
 *             - if anything goes wrong during the execution.
 */
protected void primitiveExecute(List<String> commands) throws IOException {
    ProcessBuilder builder = new ProcessBuilder();
    builder.directory(directory);
    if (environment != null) {
        builder.environment().putAll(environment);
    }
    builder.command(commands);
    builder.redirectErrorStream(true); // combine OUT and ERR into one
    // stream
    Process p = builder.start();
    final BufferedReader shellReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    Runnable reader = new Runnable() {
        @Override
        public void run() {
            String line;
            try {
                line = shellReader.readLine();
            } catch (IOException e) {
                if (!"Stream closed".equals(e.getMessage())
                        && !e.getMessage().contains("Bad file descriptor")) {
                    log.log(Level.SEVERE, "Failed reading process output", e);
                }
                return;
            }
            while (line != null) {
                if (log.isLoggable(Level.FINE) && line != null) {
                    log.fine("[" + id + "] " + line);
                }
                try {
                    line = shellReader.readLine();
                } catch (IOException e) {
                    if (!"Stream closed".equals(e.getMessage())) {
                        log.log(Level.SEVERE, "Failed reading process output", e);
                    }
                    return;
                }
            }
        }
    };

    Thread readerThread = new Thread(reader, "Process reader for: " + getCommand());
    readerThread.setDaemon(true);
    readerThread.start();

    try {
        p.waitFor();
    } catch (InterruptedException e) {
        return;
    } finally {
        readerThread.interrupt();
        p.destroy();
    }
}

From source file:org.splandroid.tr.commons.KillableProcess.java

/**
 * Start the thread that will spawn the defined process as long as the process
 * is not running./* w ww.  j  a  v  a2s.  c om*/
 */
final public synchronized void start() {
    if (this.isRunning() == false) {
        // Generate a unique-ish name for the thread
        final int hash = cmdLine.hashCode();
        final String thrName = String.format("KillableProcess-%d", hash);

        // Build a thread that'll run the process
        thread = new Thread(thrName) {
            public void run() {
                // Launch the process and wait for completion
                try {
                    final ProcessBuilder pb = new ProcessBuilder(cmdLine);
                    // Add the passed in environment
                    Map<String, String> procEnv = pb.environment();
                    for (ImmutablePair<String, String> p : envVars) {
                        procEnv.put(p.getLeft(), p.getRight());
                    }

                    // Add working directory
                    pb.directory(workingDir);
                    // Start the process
                    process = pb.start();
                    if (process != null) {
                        // Re-direct the streams
                        try {
                            streamHandler.setProcessInputStream(process.getOutputStream());
                            streamHandler.setProcessOutputStream(process.getInputStream());
                            streamHandler.setProcessErrorStream(process.getErrorStream());
                        } catch (Exception e) {
                            process.destroy();
                            throw e;
                        }
                        streamHandler.start();
                        final int retValue = process.waitFor();
                        streamHandler.stop();
                        procStatus.setReturnValue(retValue);
                    }
                } catch (Exception ex) {
                    procStatus.setException(ex);
                } finally {
                    finishSema.release();
                }
            }
        };
        thread.setDaemon(true);
        finishSema.acquireUninterruptibly();
        thread.start();
        killRequested = false;
    }
}

From source file:com.searchcode.app.jobs.repository.IndexGitRepoJob.java

/**
 * Only works if we have path to GIT//www .ja v a2  s .  com
 */
public List<CodeOwner> getBlameInfoExternal(int codeLinesSize, String repoName, String repoLocations,
        String fileName) {
    List<CodeOwner> codeOwners = new ArrayList<>(codeLinesSize);

    // -w is to ignore whitespace bug
    ProcessBuilder processBuilder = new ProcessBuilder(this.GIT_BINARY_PATH, "blame", "-c", "-w", fileName);
    // The / part is required due to centos bug for version 1.1.1
    processBuilder.directory(new File(repoLocations + "/" + repoName));

    Process process = null;
    BufferedReader bufferedReader = null;

    try {
        process = processBuilder.start();

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, Values.CHARSET_UTF8);
        bufferedReader = new BufferedReader(isr);
        String line;
        DateFormat df = new SimpleDateFormat("yyyy-mm-dd kk:mm:ss");

        HashMap<String, CodeOwner> owners = new HashMap<>();

        boolean foundSomething = false;

        while ((line = bufferedReader.readLine()) != null) {
            Singleton.getLogger().info("Blame line " + repoName + fileName + ": " + line);
            String[] split = line.split("\t");

            if (split.length > 2 && split[1].length() != 0) {
                foundSomething = true;
                String author = split[1].substring(1);
                int commitTime = (int) (System.currentTimeMillis() / 1000);
                try {
                    commitTime = (int) (df.parse(split[2]).getTime() / 1000);
                } catch (ParseException ex) {
                    Singleton.getLogger().info("time parse expection for " + repoName + fileName);
                }

                if (owners.containsKey(author)) {
                    CodeOwner codeOwner = owners.get(author);
                    codeOwner.incrementLines();

                    int timestamp = codeOwner.getMostRecentUnixCommitTimestamp();

                    if (commitTime > timestamp) {
                        codeOwner.setMostRecentUnixCommitTimestamp(commitTime);
                    }
                    owners.put(author, codeOwner);
                } else {
                    owners.put(author, new CodeOwner(author, 1, commitTime));
                }
            }
        }

        if (foundSomething == false) {
            // External call for CentOS issue
            String[] split = fileName.split("/");

            if (split.length != 1) {
                codeOwners = getBlameInfoExternal(codeLinesSize, repoName, repoLocations,
                        String.join("/", Arrays.asList(split).subList(1, split.length)));
            }

        } else {
            codeOwners = new ArrayList<>(owners.values());
        }

    } catch (IOException | StringIndexOutOfBoundsException ex) {
        Singleton.getLogger().info("getBlameInfoExternal repoloc: " + repoLocations + "/" + repoName);
        Singleton.getLogger().info("getBlameInfoExternal fileName: " + fileName);
        Singleton.getLogger()
                .warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                        + " getBlameInfoExternal for " + repoName + " " + fileName + "\n with message: "
                        + ex.getMessage());
    } finally {
        Singleton.getHelpers().closeQuietly(process);
        Singleton.getHelpers().closeQuietly(bufferedReader);
    }

    return codeOwners;
}

From source file:de.uni_luebeck.inb.knowarc.usecases.invocation.local.LocalUseCaseInvocation.java

private String setOneBinaryInput(ReferenceService referenceService, T2Reference t2Reference, ScriptInput input,
        String targetSuffix) throws InvocationException {

    if (input.isFile() || input.isTempFile()) {
        // Try to get it as a file
        String target = tempDir.getAbsolutePath() + "/" + targetSuffix;
        FileReference fileRef = getAsFileReference(referenceService, t2Reference);
        if (fileRef != null) {

            if (!input.isForceCopy()) {
                if (linkCommand != null) {
                    String source = fileRef.getFile().getAbsolutePath();
                    String actualLinkCommand = getActualOsCommand(linkCommand, source, targetSuffix, target);
                    logger.info("Link command is " + actualLinkCommand);
                    String[] splitCmds = actualLinkCommand.split(" ");
                    ProcessBuilder builder = new ProcessBuilder(splitCmds);
                    builder.directory(tempDir);
                    try {
                        int code = builder.start().waitFor();
                        if (code == 0) {
                            return target;
                        } else {
                            logger.error("Link command gave errorcode: " + code);
                        }/* www.j  a  v  a2 s  .  c om*/

                    } catch (InterruptedException e) {
                        // go through
                    } catch (IOException e) {
                        // go through
                    }

                }
            }
        }

        InputStream is = null;
        OutputStream os = null;
        is = getAsStream(referenceService, t2Reference);

        try {
            os = new FileOutputStream(target);
        } catch (FileNotFoundException e) {
            throw new InvocationException(e);
        }

        try {
            IOUtils.copyLarge(is, os);
        } catch (IOException e) {
            throw new InvocationException(e);
        }
        try {
            is.close();
            os.close();
        } catch (IOException e) {
            throw new InvocationException(e);
        }
        return target;
    } else {
        String value = (String) referenceService.renderIdentifier(t2Reference, String.class, this.getContext());
        return value;
    }
}

From source file:acoli.controller.Controller.java

private void runBashScript(String path, String scriptCommand, String aScriptParam, String anotherScriptParam)
        throws IOException {
    // Run bash .sh script here.
    ProcessBuilder pb = null;
    // Call the startup script on the uploaded and unzipped grammar directory.
    pb = new ProcessBuilder(scriptCommand, aScriptParam, anotherScriptParam);
    if (pb != null) {
        //System.out.println("Running bash script....");
        // Point to where the script is located.
        pb.directory(new File(path + "/resources/uploads/"));
        Process p = pb.start();/*  w ww.  j a v a 2 s  . c  om*/

        BufferedReader output = getOutput(p);
        BufferedReader error = getError(p);
        String line = "";
        while ((line = output.readLine()) != null) {
            System.out.println("out: " + line);
        }
        while ((line = error.readLine()) != null) {
            System.out.println("err: " + line);
        }
    }
}

From source file:de.teamgrit.grit.checking.compile.JavaCompileChecker.java

/**
 * Runs a command specified by a compiler invocation.
 *
 * @param compilerInvocation//w w  w  .  jav  a 2  s.c  om
 *            specifies what program with which flags is being executed
 * @param pathToSourceFolder
 *            the path to the source folder of the submission
 * @return CompilerOutput with fields initialized according to the outcome
 *         of the process
 * @throws BadFlagException
 *             if a flag is not known to javac
 */
private CompilerOutput runJavacProcess(List<String> compilerInvocation, Path pathToSourceFolder, boolean junit)
        throws BadFlagException {
    Process compilerProcess = null;
    try {
        ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation);
        // make sure the compiler stays in its directory.
        if (Files.isDirectory(pathToSourceFolder, LinkOption.NOFOLLOW_LINKS)) {
            compilerProcessBuilder.directory(pathToSourceFolder.toFile());
        } else {
            compilerProcessBuilder.directory(pathToSourceFolder.getParent().toFile());
        }
        compilerProcess = compilerProcessBuilder.start();
    } catch (IOException e) {
        // If we cannot call the compiler we return a CompilerOutput
        // which is
        // initialized with false, false, indicating
        // that the compiler wasn't invoked properly and that there was no
        // clean Compile.
        CompilerOutput compilerInvokeError = new CompilerOutput();
        compilerInvokeError.setClean(false);
        compilerInvokeError.setCompilerInvoked(false);
        return compilerInvokeError;
    }

    // Now we read compiler output. If everything is ok javac reports
    // nothing at all.
    InputStream compilerOutputStream = compilerProcess.getErrorStream();
    InputStreamReader compilerStreamReader = new InputStreamReader(compilerOutputStream);
    BufferedReader compilerOutputBuffer = new BufferedReader(compilerStreamReader);
    String line;

    CompilerOutput compilerOutput = new CompilerOutput();
    compilerOutput.setCompilerInvoked(true);

    List<String> compilerOutputLines = new LinkedList<>();

    try {
        while ((line = compilerOutputBuffer.readLine()) != null) {
            compilerOutputLines.add(line);
        }

        compilerOutputStream.close();
        compilerStreamReader.close();
        compilerOutputBuffer.close();
        compilerProcess.destroy();
    } catch (IOException e) {
        // Reading might go wrong here if javac should unexpectedly
        // terminate
        LOGGER.severe("Could not read compiler ourput from its output stream." + " Aborting compile of: "
                + pathToSourceFolder.toString() + " Got message: " + e.getMessage());
        compilerOutput.setClean(false);
        compilerOutput.setCompileStreamBroken(true);
        return compilerOutput;
    }

    splitCompilerOutput(compilerOutputLines, compilerOutput);

    if (compilerOutputLines.size() == 0) {
        compilerOutput.setClean(true);
    }

    return compilerOutput;
}

From source file:org.sipfoundry.sipxconfig.admin.BackupPlan.java

private boolean perform(File workingDir, File binDir) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(binDir.getPath() + File.separator + m_backupScript, "-n");
    if (!isVoicemail()) {
        // Configuration only.
        pb.command().add("-c");
    } else if (!isConfigs()) {
        // Voicemail only.
        pb.command().add("-v");
    }//from  w w w .  j  a v  a2  s . com

    Process process = pb.directory(workingDir).start();
    int code = process.waitFor();
    if (code != 0) {
        String errorMsg = String.format("Backup operation failed. Exit code: %d", code);
        LOG.error(errorMsg);
        return false;
    }

    return true;
}