Example usage for java.lang ProcessBuilder redirectError

List of usage examples for java.lang ProcessBuilder redirectError

Introduction

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

Prototype

public ProcessBuilder redirectError(File file) 

Source Link

Document

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

Usage

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

private void doRefresh() {
    synchronized (eventLock) {
        try {/*from   w ww.  ja v a  2 s .  co 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:com.github.psorobka.appium.StartServerMojo.java

@Override
public void execute() throws MojoExecutionException {
    try {//  w  ww.ja v  a 2s.  c  om
        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);
    }
}

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);//ww w .  j ava 2s  .  c o m
    Process process = builder.start();

    process.waitFor();
}

From source file:de.phoenix.submission.SubmissionCompilerAndTest.java

@Override
public PhoenixSubmissionResult controlSubmission(TaskSubmission submission) {

    SubmissionTask task = new SubmissionTask();

    File dir = PhoenixApplication.submissionPipelineDir;
    List<String> commands = getCommands();

    // Check, if all necessary classes are submitted
    Set<String> classes = new HashSet<String>();
    for (Text text : submission.getTask().getTexts()) {
        classes.add(text.getTitle());//ww w .java2s.c  o  m
    }

    for (Text clazz : submission.getTexts()) {
        task.addClass(clazz.convert());
        classes.remove(clazz.getTitle());
    }

    // Some to implement classes are missing -> error
    if (!classes.isEmpty()) {
        return new PhoenixSubmissionResult(SubmissionStatus.MISSING_FILES,
                "Missing classes to implement/submit. Maybe you wrote the name of the class wrong? Missing Classes:\r\n"
                        + classes.toString());
    }

    if (submission.getTask().isAutomaticTest()) {
        for (TaskTest test : submission.getTask().getTaskTests()) {
            addTest(task, test);
        }
    }

    // TODO: Add libraries
    ProcessBuilder builder = new ProcessBuilder(commands);
    builder.directory(dir);

    File errorLog = new File(dir, "error.log");
    errorLog.delete();
    builder.redirectError(errorLog);

    try {
        Process process = builder.start();
        JSON_MAPPER.writeValue(process.getOutputStream(), task);
        process.getOutputStream().close();

        PhoenixSubmissionResult result = JSON_MAPPER.readValue(process.getInputStream(),
                PhoenixSubmissionResult.class);

        return result;
    } catch (Exception e) {
        DebugLog.log(e);
    }

    return new PhoenixSubmissionResult(SubmissionStatus.OK, "Fine");
}

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();//from w w  w . jav 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.smash.revolance.ui.materials.CmdlineHelper.java

public CmdlineHelper exec() throws InterruptedException, IOException {
    ProcessBuilder pb = new ProcessBuilder();

    if (dir != null) {
        pb.directory(dir);/*from   w w  w  .  j  a va2s. c om*/
    }

    pb.command(cmd);

    pb.redirectError(ProcessBuilder.Redirect.to(err));
    pb.redirectOutput(ProcessBuilder.Redirect.to(out));
    pb.redirectInput(ProcessBuilder.Redirect.from(in));

    System.out.println("Executing cmd: " + cmd[0] + " from dir: " + dir);
    System.out.println("Redirecting out to: " + out.getAbsolutePath());
    System.out.println("Redirecting err to: " + err.getAbsolutePath());

    Process process = pb.start();
    if (sync) {
        process.waitFor();
    }

    this.process = process;

    return this;
}

From source file:org.fiware.cybercaptor.server.api.InformationSystemManagement.java

/**
 * Execute the python script that builds MulVAL inputs
 *
 * @return boolean true if the execution was right
 *//*ww  w  . ja v a2 s. c om*/
public static boolean prepareMulVALInputs() {
    try {
        //Load python script properties

        String pythonPath = ProjectProperties.getProperty("python-path");
        String mulvalInputScriptFolder = ProjectProperties.getProperty("mulval-input-script-folder");
        String mulvalInputScriptPath = mulvalInputScriptFolder + "main.py";

        String hostInterfacePath = ProjectProperties.getProperty("host-interfaces-path");
        String vlansPath = ProjectProperties.getProperty("vlans-path");
        String routingPath = ProjectProperties.getProperty("routing-path");
        String flowMatrixPath = ProjectProperties.getProperty("flow-matrix-path");
        String vulnerabilityScanPath = ProjectProperties.getProperty("vulnerability-scan-path");
        String mulvalInputPath = ProjectProperties.getProperty("mulval-input");
        String topologyPath = ProjectProperties.getProperty("topology-path");

        File mulvalInputFile = new File(mulvalInputPath);
        if (mulvalInputFile.exists()) {
            mulvalInputFile.delete();
        }

        Logger.getAnonymousLogger().log(Level.INFO, "Genering MulVAL inputs");

        //TODO: use parameter nessus-files-path rather than vulnerability-scan-path, in order to manage when
        // mutliple nessus files are provided.
        ProcessBuilder processBuilder = new ProcessBuilder(pythonPath, mulvalInputScriptPath,
                "--hosts-interfaces-file", hostInterfacePath, "--vlans-file", vlansPath, "--flow-matrix-file",
                flowMatrixPath, "--vulnerability-scan", vulnerabilityScanPath, "--routing-file", routingPath,
                "--mulval-output-file", mulvalInputFile.getAbsolutePath(), "--to-fiware-xml-topology",
                topologyPath);
        processBuilder.directory(new File(mulvalInputScriptFolder));
        StringBuilder command = new StringBuilder();
        for (String str : processBuilder.command())
            command.append(str + " ");
        Logger.getAnonymousLogger().log(Level.INFO,
                "Launch generation of MulVAL inputs with command : \n" + command.toString());
        processBuilder.redirectOutput(
                new File(ProjectProperties.getProperty("output-path") + "/input-generation.log"));
        processBuilder.redirectError(
                new File(ProjectProperties.getProperty("output-path") + "/input-generation.log"));
        Process process = processBuilder.start();
        process.waitFor();

        if (!mulvalInputFile.exists()) {
            Logger.getAnonymousLogger().log(Level.WARNING,
                    "A problem happened in the generation of mulval inputs");
            return false;
        }

        return true;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:be.tarsos.transcoder.ffmpeg.FFMPEGExecutor.java

public AudioInputStream pipe(Attributes attributes) throws EncoderException {
    String pipeEnvironment;//ww  w.ja  v a2  s .c om
    String pipeArgument;
    File pipeLogFile;
    int pipeBuffer;

    if (System.getProperty("os.name").indexOf("indows") > 0) {
        pipeEnvironment = "cmd.exe";
        pipeArgument = "/C";
    } else {
        pipeEnvironment = "/bin/bash";
        pipeArgument = "-c";
    }
    pipeLogFile = new File("decoder_log.txt");
    //buffer 1/4 second of audio.
    pipeBuffer = attributes.getSamplingRate() / 4;

    AudioFormat audioFormat = Encoder.getTargetAudioFormat(attributes);

    String command = toString();

    ProcessBuilder pb = new ProcessBuilder(pipeEnvironment, pipeArgument, command);

    pb.redirectError(Redirect.appendTo(pipeLogFile));

    LOG.fine("Starting piped decoding process");
    final Process process;
    try {
        process = pb.start();
    } catch (IOException e1) {
        throw new EncoderException("Problem starting piped sub process: " + e1.getMessage());
    }

    InputStream stdOut = new BufferedInputStream(process.getInputStream(), pipeBuffer);

    //read and ignore the 46 byte wav header, only pipe the pcm samples to the audioinputstream
    byte[] header = new byte[46];
    double sleepSeconds = 0;
    double timeoutLimit = 20; //seconds

    try {
        while (stdOut.available() < header.length) {
            try {
                Thread.sleep(100);
                sleepSeconds += 0.1;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (sleepSeconds > timeoutLimit) {
                throw new Error("Could not read from pipe within " + timeoutLimit + " seconds: timeout!");
            }
        }
        int bytesRead = stdOut.read(header);
        if (bytesRead != header.length) {
            throw new EncoderException(
                    "Could not read complete WAV-header from pipe. This could result in mis-aligned frames!");
        }
    } catch (IOException e1) {
        throw new EncoderException("Problem reading from piped sub process: " + e1.getMessage());
    }

    final AudioInputStream audioStream = new AudioInputStream(stdOut, audioFormat, AudioSystem.NOT_SPECIFIED);

    //This thread waits for the end of the subprocess.
    new Thread(new Runnable() {
        public void run() {
            try {
                process.waitFor();
                LOG.fine("Finished piped decoding process");
            } catch (InterruptedException e) {
                LOG.severe("Interrupted while waiting for sub process exit.");
                e.printStackTrace();
            }
        }
    }, "Decoding Pipe Reader").start();
    return audioStream;
}

From source file:de.tudarmstadt.ukp.dkpro.core.rftagger.RfTagger.java

private void ensureTaggerRunning() throws AnalysisEngineProcessException {
    if (process == null) {
        try {/*from www.j a  v  a 2  s.  c  o  m*/
            PlatformDetector pd = new PlatformDetector();
            String platform = pd.getPlatformId();
            getLogger().info("Load binary for platform: [" + platform + "]");

            File executableFile = runtimeProvider.getFile("rft-annotate");

            List<String> cmd = new ArrayList<>();
            cmd.add(executableFile.getAbsolutePath());
            cmd.add("-q"); // quiet mode
            cmd.add(modelProvider.getResource().getAbsolutePath());
            ProcessBuilder pb = new ProcessBuilder();
            pb.redirectError(Redirect.INHERIT);
            pb.command(cmd);
            process = pb.start();

            writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream(), getEncoding()));
            reader = new BufferedReader(new InputStreamReader(process.getInputStream(), getEncoding()));
        } catch (Exception e) {
            throw new AnalysisEngineProcessException(e);
        }
    }
}

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 {/*ww w  .  j  a  va  2s .  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;
}