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:org.apache.hadoop.hive.llap.cli.service.LlapServiceDriver.java

private int runPackagePy(Path tmpDir, Path scriptParent, String version, String outputDir)
        throws IOException, InterruptedException {
    Path scriptPath = new Path(new Path(scriptParent, "yarn"), "package.py");
    List<String> scriptArgs = new ArrayList<>(cl.getArgs().length + 7);
    scriptArgs.addAll(Arrays.asList("python", scriptPath.toString(), "--input", tmpDir.toString(), "--output",
            outputDir, "--javaChild"));
    scriptArgs.addAll(Arrays.asList(cl.getArgs()));

    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();
}

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  .  c  om
 *
 * @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.gordoni.opal.ScenarioSet.java

public void subprocess(String cmd, String prefix, String... args) throws IOException, InterruptedException {
    String real_cwd = System.getProperty("user.dir");
    List<String> arguments = new ArrayList<String>(Arrays.asList(args));
    arguments.add(0, real_cwd + "/" + cmd);
    ProcessBuilder pb = new ProcessBuilder(arguments);
    Map<String, String> env = pb.environment();
    env.put("OPAL_FILE_PREFIX", cwd + "/" + prefix);
    pb.redirectError(Redirect.INHERIT);
    Process p = pb.start();//from w  w w .j a  v  a2 s. c  om

    InputStream stdout = p.getInputStream();
    byte buf[] = new byte[8192];
    while (stdout.read(buf) != -1) {
    }
    p.waitFor();
    assert (p.exitValue() == 0);
}

From source file:org.p_vcd.process.ProcessBase.java

private void runCommandInternal(String command, ProcessArguments commandArgs, File workingDir,
        StringBuffer sbSaveStdout, StringBuffer sbSaveStderr) throws Exception {
    commandArgs.insertFirst(command);/*  www. jav  a  2 s . com*/
    FileUtils.forceMkdir(workingDir);
    StringBuffer sbLog = new StringBuffer();
    sbLog.append("\n").append(MyUtil.getFormateDate());
    commandArgs.addToLog(sbLog);
    System.out.println(sbLog.toString());
    this.status.appendOutputLine(sbLog.toString());
    ProcessBuilder pb = new ProcessBuilder(commandArgs.getCommands());
    pb.directory(workingDir);
    pb.redirectInput(Redirect.INHERIT);
    pb.redirectOutput(Redirect.PIPE);
    pb.redirectError(Redirect.PIPE);
    long init = System.currentTimeMillis();
    this.currentSystemProcess = pb.start();
    PrintThreadWithStatus thStdout = new PrintThreadWithStatus(this.currentSystemProcess.getInputStream(),
            command, this.status, sbSaveStdout);
    PrintThreadWithStatus thStderr = new PrintThreadWithStatus(this.currentSystemProcess.getErrorStream(),
            command, this.status, sbSaveStderr);
    this.currentSystemProcess.getOutputStream().close();
    thStdout.start();
    thStderr.start();
    int ret = -1;
    try {
        this.processRunning = true;
        ret = this.currentSystemProcess.waitFor();
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    } finally {
        this.processRunning = false;
    }
    try {
        thStderr.join();
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
    try {
        thStdout.join();
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
    long milis = System.currentTimeMillis() - init;
    if (ret != 0) {
        throw new Exception("command error code=" + ret + " (" + milis + " ms)");
    }
    sbLog = new StringBuffer();
    sbLog.append(MyUtil.getFormateDate()).append("command ").append(command).append(" ok (").append(milis)
            .append(" ms)");
    System.out.println(sbLog.toString());
    this.status.appendOutputLine(sbLog.toString());
}

From source file:fr.amap.lidar.PtgScanConversion.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");

    try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputTxtFile))) {
        PTGScan ptgScan = new PTGScan();
        ptgScan.openScanFile(scan.file);

        LPointShotExtractor shots = new LPointShotExtractor(ptgScan);
        Iterator<LShot> iterator = shots.iterator();

        while (iterator.hasNext()) {

            LShot shot = iterator.next();
            shot.direction.normalize();//from   w  w w .ja va2 s . co 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.ranges.length; 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.ranges.length + " "
                            + shot.point.intensity + "\n");
                } else {
                    writer.write(x + " " + y + " " + z + " " + (i + 1) + " " + shot.ranges.length + "\n");
                }

            }

        }
    }

    /***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:husky.server.HuskyMaster.java

@Override
public void run() {
    try {//from w w  w. ja v a2s  .c  o  m
        LOG.info("Starting husky master process");
        ProcessBuilder mHuskyMasterProcess = new ProcessBuilder(getCommands());
        if (!mAppMaster.getLdLibraryPath().isEmpty()) {
            mHuskyMasterProcess.environment().put("LD_LIBRARY_PATH", mAppMaster.getLdLibraryPath());
        }
        mHuskyMasterProcess.redirectOutput(new File(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stdout"));
        mHuskyMasterProcess.redirectError(new File(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stderr"));
        Process p = mHuskyMasterProcess.start();
        p.waitFor();
        if (p.exitValue() == 0) {
            LOG.info("Husky master exits successfully");
        } else {
            LOG.info("Husky master exits with code " + p.exitValue());
        }
    } catch (Exception e) {
        LOG.log(Level.SEVERE, " Failed to start c++ husky master process: ", e);
    } finally {
        if (!mAppMaster.getLogPathToHDFS().isEmpty()) {
            try {
                mAppMaster.getFileSystem().copyFromLocalFile(false, true,
                        new Path[] { new Path(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stdout"),
                                new Path(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stderr") },
                        new Path(mAppMaster.getLogPathToHDFS()));
            } catch (IOException e) {
                LOG.log(Level.INFO, "Failed to upload logs of husky master to hdfs", e);
            }
        }
    }
}

From source file:org.iobserve.mobile.instrument.core.APKToolProxy.java

/**
 * Adjust the manifest file of the application.
 * /* w w w. ja v  a 2 s  .c om*/
 * @param rights
 *            the rights which are mandatory
 * @param modifiedManifest
 *            the file where the adjusted manifest can be stored
 * @return true if success - false otherwise
 */
public boolean adjustManifest(final List<String> rights, final File modifiedManifest) {
    if (folderName == null) {
        return false;
    }

    // read all rights
    final File manifestFile = new File(folderName + "/" + MANIFEST_FILE);
    if (!manifestFile.exists()) {
        return false;
    }

    final Set<String> exRights = new HashSet<String>();

    // PARSING XML
    final Document dom;
    // Make an instance of the DocumentBuilderFactory
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    try {
        final DocumentBuilder db = dbf.newDocumentBuilder();

        dom = db.parse(manifestFile);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        return false;
    }

    final Node manifestNode = dom.getElementsByTagName("manifest").item(0);
    this.packageName = manifestNode.getAttributes().getNamedItem("package").getTextContent();
    final NodeList permissionNodes = manifestNode.getChildNodes();

    for (int k = 0; k < permissionNodes.getLength(); k++) {
        final Node permNode = permissionNodes.item(k);
        if (permNode.getNodeName().equals("uses-permission")) {
            exRights.add(permNode.getAttributes().getNamedItem("android:name").getTextContent());
        }
    }

    // determine which to add
    for (String right : rights) {
        if (!exRights.contains(right)) {
            final Element nNode = dom.createElement("uses-permission");
            nNode.setAttribute("android:name", right);
            manifestNode.appendChild(nNode);
        }
    }

    // write content back to file
    try {
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();
        final DOMSource source = new DOMSource(dom);
        final StreamResult result = new StreamResult(manifestFile);
        transformer.transform(source, result);
    } catch (TransformerException e) {
        return false;
    }

    // RECOMPILE
    // apktool b bar -o new_bar.apk
    final File rebuildFile = new File(folderName + "/rebuild.apk");
    final ProcessBuilder pb = new ProcessBuilder("java", "-jar", LIB_PATH, "b", folderName, "-o",
            rebuildFile.getAbsolutePath());

    pb.redirectOutput(Redirect.INHERIT);
    pb.redirectError(Redirect.INHERIT);

    try {
        pb.start().waitFor();
    } catch (InterruptedException | IOException e) {
        LOG.error("Failed to rebuild apk with APKTool.");
        return false;
    }

    // UNZIP IT
    try {
        final ZipFile rebuildZip = new ZipFile(rebuildFile);
        rebuildZip.extractFile(MANIFEST_FILE, folderName + "/" + "manifest_new");
        Files.copy(new File(folderName + "/" + "manifest_new" + "/" + MANIFEST_FILE).toPath(),
                modifiedManifest.toPath());
    } catch (ZipException | IOException e) {
        LOG.error("Failed to extract the manifest from the rebuilt application.");
        return false;
    }

    return true;
}

From source file:org.jboss.qa.jenkins.test.executor.utils.MavenCli.java

public void run() throws Exception {
    final List<String> cmd = new ArrayList<>();

    // Maven//from  ww w  . ja  v  a  2  s. com
    if (OSDetector.isWindows()) {
        // TODO(mbasovni): Not yet tested!
        cmd.add("cmd");
        cmd.add("/c");
        cmd.add(mavenHome + "/bin/mvn.bat");
    } else {
        cmd.add("/bin/bash");
        cmd.add(mavenHome + "/bin/mvn");
    }

    // Maven opts
    if (xms != null) {
        mavenOpts.add("-Xms" + xms);
    }
    if (xmx != null) {
        mavenOpts.add("-Xmx" + xmx);
    }
    if (maxPermSize != null) {
        mavenOpts.add("-XX:MaxPermSize=" + maxPermSize);
    }

    // Path to POM file
    cmd.add("-f");
    cmd.add(pom.getAbsolutePath());

    cmd.addAll(goals);

    // Profiles
    if (!profiles.isEmpty()) {
        cmd.add("-P" + StringUtils.join(profiles, ","));
    }

    // Projects
    if (!projects.isEmpty()) {
        cmd.add("-pl");
        cmd.add(StringUtils.join(projects, ","));
    }

    // If project list is specified, also build projects required by the list
    if (alsoMake) {
        cmd.add("-am");
    }

    // Only fail the build afterwards; allow all non-impacted builds to continue
    if (failAtEnd) {
        cmd.add("-fae");
    }

    // System properties
    for (Map.Entry<String, String> entry : sysProps.entrySet()) {
        cmd.add(String.format("-D%s=%s", entry.getKey(), entry.getValue()));
    }

    if (params != null) {
        cmd.addAll(params);
    }

    final ProcessBuilder processBuilder = new ProcessBuilder(cmd);
    processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
    processBuilder.environment().put("JAVA_HOME", javaHome.getAbsolutePath());
    processBuilder.environment().put("M2_HOME", mavenHome.getAbsolutePath());
    processBuilder.environment().put("MAVEN_OTPS", StringUtils.join(mavenOpts, " "));

    log.debug("===========");
    log.debug("Process arguments: " + cmd.toString());
    log.debug("JAVA_HOME={}", processBuilder.environment().get("JAVA_HOME"));
    log.debug("M2_HOME={}", processBuilder.environment().get("M2_HOME"));
    log.debug("MAVEN_OTPS={}", processBuilder.environment().get("MAVEN_OTPS"));

    final Process process = processBuilder.start();
    process.waitFor();

    if (process.exitValue() != 0) {
        log.error("Maven execution failed with exit code: " + process.exitValue());
    }
}

From source file:com.diversityarrays.kdxplore.trialdesign.JobRunningTask.java

@Override
public Either<String, AlgorithmRunResult> generateResult(Closure<Void> arg0) throws Exception {

    AlgorithmRunResult result = new AlgorithmRunResult(algorithmName, algorithmFolder);
    ProcessBuilder pb = new ProcessBuilder(command);

    File tempAlgorithmOutputFile = new File(algorithmFolder, "stdout.txt");
    File tempAlgorithmErrorFile = new File(algorithmFolder, "stderr.txt");

    //pb.redirectErrorStream(true);
    tempAlgorithmErrorFile.createNewFile();
    tempAlgorithmOutputFile.createNewFile();

    pb.redirectOutput(tempAlgorithmOutputFile);
    pb.redirectError(tempAlgorithmErrorFile);

    Process process = pb.start();

    while (!process.waitFor(1000, TimeUnit.MILLISECONDS)) {
        if (backgroundRunner.isCancelRequested()) {
            process.destroy();/* w  ww  .  j  av a 2s . c o  m*/
            throw new CancellationException();
        }
    }

    int exitCode = process.exitValue();
    if (exitCode != 0) {
        String errtxt = Algorithms.readContent("Error Output: (code=" + exitCode + ")",
                new FileInputStream(tempAlgorithmErrorFile));
        return Either.left(errtxt);
    }

    if (!kdxploreOutputFile.exists()) {
        return Either.left("Missing output file: " + kdxploreOutputFile.getPath());
    }

    result.addTrialEntries(kdxploreOutputFile, userTrialEntries);

    return Either.right(result);
}

From source file:com.ecofactor.qa.automation.platform.ops.impl.AndroidOperations.java

/**
 * Start Appium server./*from   w w  w.j  av  a  2s.c  o m*/
 * @see com.ecofactor.qa.automation.mobile.ops.impl.AbstractMobileOperations#startAppiumServer()
 */
@Override
public void startAppiumServer() {

    setLogString(LogSection.START, "Start appium server", true);
    final String deviceId = getDeviceIdParam();
    if (!deviceProps.get(deviceId + DEVICE_STATE).equals("Online")) {
        setLogString("Appium will not be started since the device state is = "
                + deviceProps.get(deviceId + DEVICE_STATE) + ".", true);
        return;
    }
    final String appiumHome = System.getenv("APPIUM_HOME");
    setLogString("APPIUM_HOME : " + appiumHome, true);
    if (appiumHome == null || appiumHome.isEmpty()) {
        setErrorMsg("\033[41;1mPlease set APPIUM_HOME environment variable and try again.");
        setLogString(errorMsg, true);
        hasErrors = true;
        return;
    }
    generateNodeConfig();
    final List<String> commands = arrayToList("node", ".", "-U", deviceId, "-p", DEFAULT_PORT, "--full-reset");
    String listToString = StringUtil.listToString(commands, " ");
    final int indexOfK = listToString.lastIndexOf("/k");
    listToString = listToString.substring(indexOfK + 2, listToString.length());
    setLogString("Command to Start Appium Server:" + listToString, true);

    final ProcessBuilder process = new ProcessBuilder(commands);
    process.directory(new File(appiumHome));
    process.redirectOutput(new File("outPut.txt"));
    process.redirectError(new File("error.txt"));
    startProcessBuilder(process);
    mediumWait();
    setLogString(LogSection.END, "Started appium server", true);
}