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:alluxio.multi.process.MultiProcessCluster.java

/**
 * Copies the work directory to the artifacts folder.
 *//*w  ww  .j  av a2  s  . c o  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:fr.amap.lidar.RxpScanConversion.java

public void toLaz(SimpleScan scan, File outputDirectory, boolean laz, boolean exportIntensity)
        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  ww  .  j a va  2s  . 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];

            if (exportIntensity) {
                writer.write(x + " " + y + " " + z + " " + (i + 1) + " " + shot.nbEchos + " "
                        + reflectanceToIntensity(shot.reflectances[i]) + "\n");
            } else {
                writer.write(x + " " + y + " " + z + " " + (i + 1) + " " + shot.nbEchos + "\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;

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

    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:org.apache.zeppelin.python.IPythonInterpreter.java

/**
 * non-empty return value mean the errors when checking ipython prerequisite.
 * empty value mean IPython prerequisite is meet.
 *
 * @param pythonExec/*www.  ja  v a  2s  .  c o  m*/
 * @return
 */
public String checkIPythonPrerequisite(String pythonExec) {
    ProcessBuilder processBuilder = new ProcessBuilder(pythonExec, "-m", "pip", "freeze");
    try {
        File stderrFile = File.createTempFile("zeppelin", ".txt");
        processBuilder.redirectError(stderrFile);
        File stdoutFile = File.createTempFile("zeppelin", ".txt");
        processBuilder.redirectOutput(stdoutFile);

        Process proc = processBuilder.start();
        int ret = proc.waitFor();
        if (ret != 0) {
            return "Fail to run pip freeze.\n" + IOUtils.toString(new FileInputStream(stderrFile));
        }
        String freezeOutput = IOUtils.toString(new FileInputStream(stdoutFile));
        if (!freezeOutput.contains("jupyter-client=")) {
            return "jupyter-client is not installed.";
        }
        if (!freezeOutput.contains("ipykernel=")) {
            return "ipykernel is not installed";
        }
        if (!freezeOutput.contains("ipython=")) {
            return "ipython is not installed";
        }
        if (!freezeOutput.contains("grpcio=")) {
            return "grpcio is not installed";
        }
        if (!freezeOutput.contains("protobuf=")) {
            return "protobuf is not installed";
        }
        LOGGER.info("IPython prerequisite is met");
    } catch (Exception e) {
        LOGGER.warn("Fail to checkIPythonPrerequisite", e);
        return "Fail to checkIPythonPrerequisite: " + ExceptionUtils.getStackTrace(e);
    }
    return "";
}

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 ww.jav  a  2 s  .  c o  m
 */
@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:com.axelor.studio.service.ModuleRecorderService.java

private String restartServer(boolean reset) throws AxelorException {

    String logFile = checkParams("studio.restart.log", AppSettings.get().get("studio.restart.log"), true);
    String warPath = getWarPath();

    try {/*from  ww  w.j av a2s.  c  o m*/
        String scriptPath = getRestartScriptPath();
        ProcessBuilder processBuilder;
        if (reset) {
            processBuilder = new ProcessBuilder(scriptPath, warPath, "reset");
        } else {
            processBuilder = new ProcessBuilder(scriptPath, warPath);
        }
        processBuilder.environment().putAll(ENV);
        processBuilder.redirectOutput(new File(logFile));
        processBuilder.redirectError(new File(logFile));
        processBuilder.start();
    } catch (IOException e) {
        throw new AxelorException(e, 5);
    }

    if (reset) {
        return I18n.get("App reset sucessfully");
    }

    return I18n.get("App updated successfully");
}

From source file:com.opentable.db.postgres.embedded.EmbeddedPostgres.java

private void startPostmaster() throws IOException {
    final StopWatch watch = new StopWatch();
    watch.start();//from  ww  w.  j  a  v  a 2s .  co  m
    Preconditions.checkState(started.getAndSet(true) == false, "Postmaster already started");

    final List<String> args = Lists.newArrayList(pgBin("pg_ctl"), "-D", dataDirectory.getPath(), "-o",
            Joiner.on(" ").join(createInitOptions()), "start");

    final ProcessBuilder builder = new ProcessBuilder(args);
    builder.redirectErrorStream(true);
    builder.redirectError(outputRedirector);
    builder.redirectOutput(outputRedirector);
    postmaster = builder.start();
    LOG.info("{} postmaster started as {} on port {}.  Waiting up to {}ms for server startup to finish.",
            instanceId, postmaster.toString(), port, PG_STARTUP_WAIT_MS);

    Runtime.getRuntime().addShutdownHook(newCloserThread());

    waitForServerStartup(watch);
}

From source file:gov.pnnl.goss.gridappsd.simulation.SimulationManagerImpl.java

/**
 * This method is called by Process Manager to start a simulation
 * @param simulationId//from www  .  j  a  va  2  s  . c o m
 * @param simulationFile
 */
@Override
public void startSimulation(int simulationId, File simulationFile, SimulationConfig simulationConfig) {

    try {
        logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                new Date().getTime(), "Starting simulation " + simulationId, LogLevel.INFO,
                ProcessStatus.STARTING, true), GridAppsDConstants.username);
    } catch (Exception e2) {
        log.warn("Error while reporting status " + e2.getMessage());
    }

    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {

            Process gridlabdProcess = null;
            Process fncsProcess = null;
            Process fncsBridgeProcess = null;
            Process vvoAppProcess = null;
            InitializedTracker isInitialized = new InitializedTracker();
            try {

                File defaultLogDir = simulationFile.getParentFile();

                //Start FNCS
                //TODO, verify no errors on this
                String broker_location = "tcp://*:5570";
                if (simulationConfig != null && simulationConfig.model_creation_config != null
                        && simulationConfig.model_creation_config.schedule_name != null
                        && simulationConfig.model_creation_config.schedule_name.trim().length() > 0) {
                    broker_location = "tcp://" + simulationConfig.getSimulation_broker_location() + ":"
                            + String.valueOf(simulationConfig.getSimulation_broker_port());
                    File serviceDir = serviceManager.getServiceConfigDirectory();
                    //copy zipload_schedule.player file
                    try {
                        RunCommandLine.runCommand("cp " + serviceDir.getAbsolutePath() + File.separator + "etc"
                                + File.separator + "zipload_schedule.player "
                                + simulationFile.getParentFile().getAbsolutePath() + File.separator
                                + simulationConfig.model_creation_config.schedule_name + ".player");
                    } catch (Exception e) {
                        log.warn("Could not copy player file to working directory");
                    }
                }

                logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                        new Date().getTime(), "Calling " + getPath(GridAppsDConstants.FNCS_PATH) + " 2",
                        LogLevel.INFO, ProcessStatus.STARTING, true), GridAppsDConstants.username);

                ProcessBuilder fncsBuilder = new ProcessBuilder(getPath(GridAppsDConstants.FNCS_PATH), "2");
                fncsBuilder.redirectErrorStream(true);
                fncsBuilder.redirectOutput(
                        new File(defaultLogDir.getAbsolutePath() + File.separator + "fncs.log"));
                Map<String, String> fncsEnvironment = fncsBuilder.environment();
                fncsEnvironment.put("FNCS_BROKER", broker_location);
                fncsProcess = fncsBuilder.start();
                // Watch the process
                watch(fncsProcess, "FNCS");
                //TODO: check if FNCS is started correctly and send publish simulation status accordingly

                logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                        new Date().getTime(), "FNCS Co-Simulator started", LogLevel.INFO, ProcessStatus.RUNNING,
                        true), GridAppsDConstants.username);

                //client.publish(GridAppsDConstants.topic_simulationStatus+simulationId, "FNCS Co-Simulator started");

                //Start GridLAB-D
                logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                        new Date().getTime(),
                        "Calling " + getPath(GridAppsDConstants.GRIDLABD_PATH) + " " + simulationFile,
                        LogLevel.INFO, ProcessStatus.RUNNING, true), GridAppsDConstants.username);
                ProcessBuilder gridlabDBuilder = new ProcessBuilder(getPath(GridAppsDConstants.GRIDLABD_PATH),
                        simulationFile.getAbsolutePath());
                gridlabDBuilder.redirectErrorStream(true);
                gridlabDBuilder.redirectOutput(
                        new File(defaultLogDir.getAbsolutePath() + File.separator + "gridlabd.log"));
                //launch from directory containing simulation files
                gridlabDBuilder.directory(simulationFile.getParentFile());
                gridlabdProcess = gridlabDBuilder.start();
                // Watch the process
                watch(gridlabdProcess, "GridLABD");

                //TODO: check if GridLAB-D is started correctly and send publish simulation status accordingly

                logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                        new Date().getTime(), "GridLAB-D started", LogLevel.INFO, ProcessStatus.RUNNING, true),
                        GridAppsDConstants.username);

                //Start VVO Application
                //TODO filname really should be constant
                String vvoInputFile = simulationFile.getParentFile().getAbsolutePath() + File.separator
                        + "vvo_inputs.json";
                logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                        new Date().getTime(),
                        "Calling " + "python " + getPath(GridAppsDConstants.VVO_APP_PATH) + " " + simulationId
                                + " " + vvoInputFile,
                        LogLevel.INFO, ProcessStatus.RUNNING, true), GridAppsDConstants.username);
                ProcessBuilder vvoAppBuilder = new ProcessBuilder("python",
                        getPath(GridAppsDConstants.VVO_APP_PATH), "-f", vvoInputFile, "" + simulationId);
                vvoAppBuilder.redirectErrorStream(true);
                vvoAppBuilder.redirectOutput(
                        new File(defaultLogDir.getAbsolutePath() + File.separator + "vvo_app.log"));
                vvoAppProcess = vvoAppBuilder.start();
                // Watch the process
                watch(vvoAppProcess, "VVO Application");

                logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                        new Date().getTime(), "FNCS-GOSS Bridge started", LogLevel.INFO, ProcessStatus.RUNNING,
                        true), GridAppsDConstants.username);

                //Start GOSS-FNCS Bridge
                logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                        new Date().getTime(),
                        "Calling " + "python " + getPath(GridAppsDConstants.FNCS_BRIDGE_PATH) + " "
                                + simulationConfig.getSimulation_name(),
                        LogLevel.INFO, ProcessStatus.RUNNING, true), GridAppsDConstants.username);

                ProcessBuilder fncsBridgeBuilder = new ProcessBuilder("python",
                        getPath(GridAppsDConstants.FNCS_BRIDGE_PATH), simulationConfig.getSimulation_name(),
                        broker_location);
                fncsBridgeBuilder.redirectErrorStream(true);
                fncsBridgeBuilder.redirectOutput(
                        new File(defaultLogDir.getAbsolutePath() + File.separator + "fncs_goss_bridge.log"));
                fncsBridgeProcess = fncsBridgeBuilder.start();
                // Watch the process
                watch(fncsBridgeProcess, "FNCS GOSS Bridge");

                //TODO: check if bridge is started correctly and send publish simulation status accordingly

                logManager.log(new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                        new Date().getTime(), "FNCS-GOSS Bridge started", LogLevel.INFO, ProcessStatus.RUNNING,
                        true), GridAppsDConstants.username);

                //Subscribe to fncs-goss-bridge output topic
                client.subscribe(GridAppsDConstants.topic_FNCS_output,
                        new GossFncsResponseEvent(logManager, isInitialized, simulationId));

                int initAttempts = 0;
                while (!isInitialized.isInited && initAttempts < MAX_INIT_ATTEMPTS) {
                    //Send 'isInitialized' call to fncs-goss-bridge to check initialization until it is initialized.
                    //TODO add limiting how long it checks for initialized, or cancel if the fncs process exits
                    //This call would return true/false for initialization and simulation output of time step 0.
                    logManager.log(
                            new LogMessage(this.getClass().getName() + "-" + Integer.toString(simulationId),
                                    new Date().getTime(),
                                    "Checking fncs is initialized, currently " + isInitialized.isInited,
                                    LogLevel.INFO, ProcessStatus.RUNNING, true),
                            GridAppsDConstants.username);

                    client.publish(GridAppsDConstants.topic_FNCS_input, "{\"command\": \"isInitialized\"}");
                    initAttempts++;
                    Thread.sleep(1000);

                }

                if (initAttempts < MAX_INIT_ATTEMPTS) {
                    logManager.log(
                            new LogMessage(Integer.toString(simulationId), new Date().getTime(),
                                    "FNCS Initialized", LogLevel.INFO, ProcessStatus.RUNNING, true),
                            GridAppsDConstants.username);

                    //Send the timesteps by second for the amount of time specified in the simulation config
                    sendTimesteps(simulationConfig, simulationId);
                } else {
                    logManager.log(
                            new LogMessage(Integer.toString(simulationId), new Date().getTime(),
                                    "FNCS Initialization Failed", LogLevel.ERROR, ProcessStatus.ERROR, true),
                            GridAppsDConstants.username);

                }

                //call to stop the fncs broker
                client.publish(GridAppsDConstants.topic_FNCS_input, "{\"command\":  \"stop\"}");
                logManager.log(new LogMessage(Integer.toString(simulationId), new Date().getTime(),
                        "Simulation " + simulationId + " complete", LogLevel.INFO, ProcessStatus.COMPLETE,
                        true), GridAppsDConstants.username);
            } catch (Exception e) {
                log.error("Error during simulation", e);
                try {
                    logManager.log(new LogMessage(Integer.toString(simulationId), new Date().getTime(),
                            "Simulation error: " + e.getMessage(), LogLevel.ERROR, ProcessStatus.ERROR, true),
                            GridAppsDConstants.username);
                } catch (Exception e1) {
                    log.error("Error while reporting error status", e);
                }
            } finally {
                //shut down fncs broker and gridlabd and bridge if still running
                if (fncsProcess != null) {
                    fncsProcess.destroy();
                }
                if (gridlabdProcess != null) {
                    gridlabdProcess.destroy();
                }
                if (fncsBridgeProcess != null) {
                    fncsBridgeProcess.destroy();
                }
            }
        }
    });

    thread.start();
}

From source file:nz.co.fortytwo.signalk.handler.GitHandler.java

private void runNpmInstall(final File output, File destDir) throws Exception {
    FileUtils.writeStringToFile(output, "\nBeginning npm install", true);
    ProcessBuilder pb = new ProcessBuilder("npm", "install");
    Map<String, String> env = System.getenv();
    if (env.containsKey("PATH")) {
        pb.environment().put("PATH", env.get("PATH"));
    }/*from  w ww  .ja v a 2 s  . co m*/
    if (env.containsKey("Path")) {
        pb.environment().put("Path", env.get("Path"));
    }
    if (env.containsKey("path")) {
        pb.environment().put("path", env.get("path"));
    }
    pb.directory(destDir);
    pb.redirectErrorStream(true);
    pb.redirectOutput(output);
    final Process p = pb.start();
    Thread t = new Thread() {

        @Override
        public void run() {
            try {
                p.waitFor();
                FileUtils.writeStringToFile(output, "\nDONE: Npm ended sucessfully", true);
            } catch (Exception e) {
                try {
                    logger.error(e);
                    FileUtils.writeStringToFile(output, "\nNpm ended badly:" + e.getMessage(), true);
                    FileUtils.writeStringToFile(output, "\n" + e.getStackTrace(), true);
                } catch (IOException e1) {
                    logger.error(e1);
                }
            }
        }

    };
    t.start();
}

From source file:com.orange.clara.cloud.servicedbdumper.integrations.AbstractIntegrationTest.java

protected Process runCommandLine(String[] commandLine) throws IOException, InterruptedException {
    logger.info("Running command line: " + String.join(" ", commandLine));

    ProcessBuilder pb = new ProcessBuilder(commandLine);
    pb.redirectOutput(ProcessBuilder.Redirect.PIPE);
    Process process = pb.start();
    return process;
}

From source file:org.apache.hadoop.hive.llap.cli.LlapServiceDriver.java

private int runPackagePy(String[] args, Path tmpDir, Path scriptParent, String version, String outputDir)
        throws IOException, InterruptedException {
    Path scriptPath = new Path(new Path(scriptParent, "slider"), "package.py");
    List<String> scriptArgs = new ArrayList<>(args.length + 7);
    scriptArgs.add("python");
    scriptArgs.add(scriptPath.toString());
    scriptArgs.add("--input");
    scriptArgs.add(tmpDir.toString());//  w  w w  .  j  a  va  2 s.  c o  m
    scriptArgs.add("--output");
    scriptArgs.add(outputDir);
    scriptArgs.add("--javaChild");
    for (String arg : args) {
        scriptArgs.add(arg);
    }
    LOG.debug("Calling package.py via: " + scriptArgs);
    ProcessBuilder builder = new ProcessBuilder(scriptArgs);
    builder.redirectError(ProcessBuilder.Redirect.INHERIT);
    builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    builder.environment().put("HIVE_VERSION", version);
    return builder.start().waitFor();
}