Example usage for java.lang ProcessBuilder redirectOutput

List of usage examples for java.lang ProcessBuilder redirectOutput

Introduction

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

Prototype

public ProcessBuilder redirectOutput(File file) 

Source Link

Document

Sets this process builder's standard output destination to a file.

Usage

From source file:com.st.symfony.Symfony.java

public void run(final String command, final long replyTimeout) throws Exception {

    String[] commands = command.split("\\s+");

    ProcessBuilder pb = new ProcessBuilder(commands);
    File log = new File(this.logFilePath);
    pb.redirectErrorStream(true);/*from w w w .  j  av a 2  s. c o m*/
    pb.redirectOutput(Redirect.appendTo(log));
    Process p = pb.start();

    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

    String line = null;
    StringBuilder output = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        System.out.println(line + "\n");
        output.append(line + "\n");
    }

    p.waitFor();

}

From source file:org.apache.tika.module.command.internal.Activator.java

public void forkProcess(String[] command) throws IOException, InterruptedException {
    ProcessBuilder builder = new ProcessBuilder();
    builder.redirectOutput(Redirect.INHERIT);
    builder.redirectError(Redirect.INHERIT);
    List<String> forkCommand = new ArrayList<String>();
    forkCommand.add("java");
    forkCommand.add("-cp");
    forkCommand.add(System.getProperty("java.class.path"));
    forkCommand.add("org.apache.tika.main.Main");
    forkCommand.addAll(Arrays.asList(command));

    //Remove fork command when running process forked.
    forkCommand.remove("-f");
    forkCommand.remove("--fork");

    builder.command(forkCommand);// www .  j av a2 s . c  o m
    Process process = builder.start();

    process.waitFor();
}

From source file:org.apache.hadoop.mpich.MpichContainerWrapper.java

public void run() {
    try {//from  w w  w  .  j a v a  2s. c  o m
        clientSock = new Socket(ioServer, ioServerPort);
        System.setOut(new PrintStream(clientSock.getOutputStream(), true));
        System.setErr(new PrintStream(clientSock.getOutputStream(), true));

        String hostName = InetAddress.getLocalHost().getHostName();
        System.out.println("Starting process " + executable + " on " + hostName);

        List<String> commands = new ArrayList<String>();
        commands.add(executable);
        if (appArgs != null && appArgs.length > 0) {
            commands.addAll(Arrays.asList(appArgs));
        }

        ProcessBuilder processBuilder = new ProcessBuilder(commands);
        processBuilder.redirectErrorStream(true);
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);

        Map<String, String> evns = processBuilder.environment();
        evns.put("PMI_RANK", rank);
        evns.put("PMI_SIZE", np);
        evns.put("PMI_ID", pmiid);
        evns.put("PMI_PORT", pmiServer + ":" + pmiServerPort);

        if (this.isSpawn) {
            evns.put("PMI_SPAWNED", "1");
        }

        LOG.info("Starting process:");
        for (String cmd : commands) {
            LOG.info(cmd + "\n");
        }

        Process process = processBuilder.start();
        System.out.println("Process exit with value " + process.waitFor());
        System.out.println("EXIT");//Stopping IOThread
        clientSock.close();
    } catch (UnknownHostException exp) {
        System.err.println("Unknown Host Exception, Host not found");
        exp.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fr.amap.amapvox.rxptolaz.RxpScanConversion.java

public void toLaz(SimpleScan scan, File outputDirectory, boolean laz)
        throws IOException, InterruptedException, UnsupportedOperationException, Exception {

    /***Convert rxp to txt***/

    Mat4D transfMatrix = Mat4D.multiply(scan.sopMatrix, scan.popMatrix);

    Mat3D rotation = new Mat3D();
    rotation.mat = new double[] { transfMatrix.mat[0], transfMatrix.mat[1], transfMatrix.mat[2],
            transfMatrix.mat[4], transfMatrix.mat[5], transfMatrix.mat[6], transfMatrix.mat[8],
            transfMatrix.mat[9], transfMatrix.mat[10] };

    File outputTxtFile = new File(
            outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".txt");
    BufferedWriter writer = new BufferedWriter(new FileWriter(outputTxtFile));

    RxpExtraction extraction = new RxpExtraction();

    extraction.openRxpFile(scan.file, RxpExtraction.REFLECTANCE);

    Iterator<Shot> iterator = extraction.iterator();

    while (iterator.hasNext()) {

        Shot shot = iterator.next();/*w  w  w .j  av a2 s . c o m*/

        Vec4D origin = Mat4D.multiply(transfMatrix,
                new Vec4D(shot.origin.x, shot.origin.y, shot.origin.z, 1.0d));
        Vec3D direction = Mat3D.multiply(rotation,
                new Vec3D(shot.direction.x, shot.direction.y, shot.direction.z));

        for (int i = 0; i < shot.nbEchos; i++) {

            double x = origin.x + direction.x * shot.ranges[i];
            double y = origin.y + direction.y * shot.ranges[i];
            double z = origin.z + direction.z * shot.ranges[i];

            writer.write(x + " " + y + " " + z + " " + (i + 1) + " " + shot.nbEchos + " "
                    + reflectanceToIntensity(shot.reflectances[i]) + "\n");
        }

    }

    extraction.close();
    writer.close();

    /***Convert txt to laz***/
    String propertyValue = System.getProperty("user.dir");
    System.out.println("Current jar directory : " + propertyValue);

    String txtToLasPath;

    String osName = getOSName();

    switch (osName) {
    case "windows":
    case "linux":
        txtToLasPath = propertyValue + File.separator + "LASTools" + File.separator + osName + File.separator
                + "txt2las";
        break;
    default:
        throw new UnsupportedOperationException("Os architecture not supported");
    }

    if (osName.equals("windows")) {
        txtToLasPath = txtToLasPath + ".exe";
    }

    File outputLazFile;
    if (laz) {
        outputLazFile = new File(
                outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".laz");
    } else {
        outputLazFile = new File(
                outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".las");
    }

    String[] commandLine = new String[] { txtToLasPath, "-i", outputTxtFile.getAbsolutePath(), "-o",
            outputLazFile.getAbsolutePath(), "-parse", "xyzrni" };

    System.out.println("Command line : "
            + ArrayUtils.toString(commandLine).replaceAll(",", " ").replaceAll("}", "").replace("{", ""));

    ProcessBuilder pb = new ProcessBuilder(commandLine);
    pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    pb.redirectError(ProcessBuilder.Redirect.INHERIT);

    Process p = pb.start();

    p.waitFor();

}

From source file:com.qhrtech.emr.launcher.TemplateLauncherManager.java

private void doRefresh() {
    synchronized (eventLock) {
        try {/*  w  w w.  j a  va  2s  .c o  m*/
            doGeneration();
            if (notifyCommand != null) {
                ProcessBuilder pb = new ProcessBuilder(notifyCommand);
                pb.redirectError(ProcessBuilder.Redirect.INHERIT);
                pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
                pb.start().waitFor();
            }
        } catch (Exception ex) {
            LoggerFactory.getLogger(getClass()).error("Error reloading templates.", ex);
        }
    }
}

From source file:org.obiba.rserver.service.RServerService.java

private ProcessBuilder buildRProcess() {
    List<String> args = getArguments();
    log.info("Starting R server: {}", StringUtils.collectionToDelimitedString(args, " "));
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(getWorkingDirectory());
    pb.redirectErrorStream(true);//from   www .  j a  va2 s.  c  om
    pb.redirectOutput(ProcessBuilder.Redirect.appendTo(getRserveLogFile()));
    return pb;
}

From source file:de.saly.es.example.tssl.plugin.test.multijvm.MultiJvmUnitTest.java

public void startCluster() throws Exception {
    final String separator = System.getProperty("file.separator");
    final String classpath = System.getProperty("java.class.path");
    final String path = System.getProperty("java.home") + separator + "bin" + separator + "java";
    final ProcessBuilder processBuilder = new ProcessBuilder(path, "-Xmx1g", "-Xms1g", "-cp", classpath,
            Cluster.class.getCanonicalName());
    processBuilder.redirectErrorStream(true);
    processBuilder.redirectOutput(Redirect.INHERIT);
    processes.add(processBuilder.start());
}

From source file:com.anrisoftware.globalpom.exec.core.DefaultProcessTask.java

@Override
public ProcessTask call() throws CommandExecException {
    List<String> command = commandLine.getCommand();
    ProcessBuilder builder = new ProcessBuilder(command);
    builder.directory(commandLine.getWorkingDir());
    builder.redirectOutput(Redirect.PIPE);
    builder.redirectError(Redirect.PIPE);
    builder.redirectInput(Redirect.PIPE);
    try {/* w ww  .  j  a v a  2  s  . c o  m*/
        startProcess(builder);
    } catch (IOException e) {
        throw log.errorStartCommand(this, e, commandLine);
    } catch (InterruptedException e) {
        throw log.commandInterrupted(this, e, commandLine);
    } catch (ExecutionException e) {
        throw log.errorStartCommand(this, e.getCause(), commandLine);
    }
    return this;
}

From source file:com.github.ffremont.microservices.springboot.node.tasks.StartTask.java

/**
 * Syntaxe : java [-options] class [args...] (pour l'excution d'une classe)
 * ou java [-options] -jar jarfile [args...] (pour l'excution d'un fichier
 * JAR//from   w  w w  .  j  ava2  s  .  co  m
 *
 * @param task
 * @throws
 * com.github.ffremont.microservices.springboot.node.exceptions.FailStartedException
 * @throws
 * com.github.ffremont.microservices.springboot.node.exceptions.FileMsNotFoundException
 */
@Override
public void run(MicroServiceTask task) throws FailStartedException, FileMsNotFoundException {
    LOG.info("Dmarrage du micro service {}", task.getMs().getName());

    Path jar = helper.targetJarOf(task.getMs());
    Path workingDir = helper.targetDirOf(task.getMs());

    if (!Files.exists(jar)
            || !Files.exists(Paths.get(workingDir.toString(), InstallTask.CHECKSUM_FILE_NAME + ".txt"))) {
        throw new FileMsNotFoundException("Jar inexistant ou invalide");
    }

    String javaEx = this.javaExec.isEmpty() ? System.getProperty("java.home") + "/bin/java" : this.javaExec;

    ProcessBuilder ps = new ProcessBuilder(javaEx, "-jar", helper.targetJarOf(task.getMs()).toString(), "&");
    ps.directory(workingDir.toFile());

    try {
        Path consoleLog = Paths.get(workingDir.toString(), "console.log");
        ps.redirectOutput(consoleLog.toFile());
        ps.redirectError(consoleLog.toFile());

        LOG.info("Run de {}", ps.command().toString());
        ps.start();
    } catch (IOException ex) {
        throw new FailStartedException("Impossible de dmarrer le programme java : " + task.getMs().getId(),
                ex);
    }

    LOG.info("Micro service {} dmarr", task.getMs().getName());
}

From source file:com.github.psorobka.appium.StartServerMojo.java

@Override
public void execute() throws MojoExecutionException {
    try {// w  ww . j  ava 2s.c  o  m
        getLog().info("Starting Appium server...");
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command("appium", "--log-timestamp", "--log",
                new File(target, "appiumLog.txt").getAbsolutePath());
        processBuilder.redirectError(new File(target, "appiumErrorLog.txt"));
        processBuilder.redirectOutput(new File(target, "appiumOutputLog.txt"));
        getLog().debug("Appium server commands " + processBuilder.command());
        Process process = processBuilder.start();
        if (!Processes.newPidProcess(process).isAlive()) {
            throw new MojoExecutionException("Failed to start Appium server");
        }
        int pid = PidUtil.getPid(process);
        getLog().info("Appium server started");
        getLog().debug("Appium server PID " + pid);
        FileUtils.writeStringToFile(new File(target, "appium.pid"), Integer.toString(pid));
        //Dumb way to sleep until appium starts - file watcher would be better
        Thread.sleep(5000);
    } catch (IOException | InterruptedException ex) {
        throw new MojoExecutionException("Failed to start Appium server", ex);
    }
}