Example usage for java.lang ProcessBuilder redirectErrorStream

List of usage examples for java.lang ProcessBuilder redirectErrorStream

Introduction

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

Prototype

boolean redirectErrorStream

To view the source code for java.lang ProcessBuilder redirectErrorStream.

Click Source Link

Usage

From source file:edu.stanford.epad.epadws.handlers.dicom.DSOUtil.java

public static String getNiftiDSOComparison(File standardDSO, File testDSO) throws Exception {
    String command = EPADConfig.getEPADWebServerBaseDir() + "bin/EvaluateSegmentation "
            + standardDSO.getAbsolutePath() + " " + testDSO.getAbsolutePath()
            + " -use DICE,JACRD,AUC,KAPPA,RNDIND,ADJRIND,ICCORR,VOLSMTY,MUTINF,MAHLNBS,VARINFO,GCOERR,PROBDST,SNSVTY,SPCFTY,PRCISON,ACURCY,FALLOUT,HDRFDST@0.96@,FMEASR@0.5@ -xml "
            + EPADConfig.getEPADWebServerBaseDir() + "bin/result.xml";
    log.info(command);/*from   www.  ja v a 2s .c om*/
    String[] args = command.split(" ");
    InputStream is = null;
    InputStreamReader isr = null;
    BufferedReader br = null;
    try {
        ProcessBuilder processBuilder = new ProcessBuilder(args);
        processBuilder.directory(new File(EPADConfig.getEPADWebServerBaseDir() + "bin/"));
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        is = process.getInputStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);

        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
            log.debug("./eval_seg output: " + line);
        }

        int exitValue = process.waitFor();
        log.info("Evaluate Segmentation exit value is: " + exitValue);
        return sb.toString();
    } catch (Exception e) {
        log.warning("Error evaluating dsos", e);
        throw e;
    }
}

From source file:org.taverna.server.master.localworker.ForkRunFactory.java

/**
 * Makes the subprocess that manufactures runs.
 * //from   w  w  w. ja  va2s. com
 * @throws Exception
 *             If anything goes wrong.
 */
public void initFactory() throws Exception {
    if (factory != null)
        return;
    // Generate the arguments to use when spawning the subprocess
    factoryProcessName = state.getFactoryProcessNamePrefix() + randomUUID();
    ProcessBuilder p = new ProcessBuilder(getJavaBinary());
    p.command().addAll(asList(getExtraArguments()));
    p.command().add("-jar");
    p.command().add(getServerWorkerJar());
    p.command().add(getExecuteWorkflowScript());
    p.command().add(factoryProcessName);
    p.redirectErrorStream(true);
    p.directory(new File(getProperty("javax.servlet.context.tempdir", getProperty("java.io.tmpdir"))));

    // Spawn the subprocess
    log.info("about to create subprocess: " + p.command());
    factoryProcess = p.start();
    Thread logger = new Thread(new OutputLogger(factoryProcessName, factoryProcess),
            factoryProcessName + ".Logger");
    logger.setDaemon(true);
    logger.start();

    // Wait for the subprocess to register itself in the RMI registry
    Calendar deadline = Calendar.getInstance();
    deadline.add(SECOND, state.getWaitSeconds());
    Exception lastException = null;
    lastStartupCheckCount = 0;
    while (deadline.after(Calendar.getInstance())) {
        try {
            sleep(state.getSleepMS());
            lastStartupCheckCount++;
            log.info("about to look up resource called " + factoryProcessName);
            try {
                // Validate registry connection first
                getTheRegistry().list();
            } catch (ConnectException ce) {
                log.warn("connection problems with registry", ce);
            } catch (ConnectIOException e) {
                log.warn("connection problems with registry", e);
            }
            factory = (RemoteRunFactory) getTheRegistry().lookup(factoryProcessName);
            log.info("successfully connected to factory subprocess " + factoryProcessName);
            if (interhost != null)
                factory.setInteractionServiceDetails(interhost, interport, interwebdav, interfeed);
            return;
        } catch (InterruptedException ie) {
            continue;
        } catch (NotBoundException nbe) {
            lastException = nbe;
            log.info("resource \"" + factoryProcessName + "\" not yet registered...");
            continue;
        } catch (RemoteException re) {
            // Unpack a remote exception if we can
            lastException = re;
            try {
                if (re.getCause() != null)
                    lastException = (Exception) re.getCause();
            } catch (Throwable t) {
                // Ignore!
            }
        } catch (Exception e) {
            lastException = e;
        }
    }
    throw lastException;
}

From source file:net.solarnetwork.node.setup.s3.S3SetupManager.java

private List<Path> extractTarball(File tarball) throws IOException {
    List<String> cmd = new ArrayList<>(tarCommand.size());
    String tarballPath = tarball.getAbsolutePath();
    for (String param : tarCommand) {
        param = param.replace(SOURCE_FILE_PLACEHOLDER, tarballPath);
        param = param.replace(DESTINATION_DIRECTORY_PLACEHOLDER, destinationPath);
        cmd.add(param);/*from   ww  w .  j  a v a  2  s  . c o m*/
    }
    if (log.isDebugEnabled()) {
        StringBuilder buf = new StringBuilder();
        for (String p : cmd) {
            if (buf.length() > 0) {
                buf.append(' ');
            }
            buf.append(p);
        }
        log.debug("Tar command: {}", buf.toString());
    }
    log.info("Extracting S3 tar archive {}", tarball);
    List<Path> extractedPaths = new ArrayList<>();
    ProcessBuilder pb = new ProcessBuilder(cmd);
    pb.redirectErrorStream(true); // OS X tar output list to STDERR; Linux GNU tar to STDOUT
    Process pr = pb.start();
    try (BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()))) {
        String line = null;
        while ((line = in.readLine()) != null) {
            Matcher m = TAR_LIST_PAT.matcher(line);
            if (m.matches()) {
                line = m.group(1);
            }
            Path path = FileSystems.getDefault().getPath(line).toAbsolutePath().normalize();
            extractedPaths.add(path);
            log.trace("Installed setup resource: {}", line);
        }
    }
    try {
        pr.waitFor();
    } catch (InterruptedException e) {
        log.warn("Interrupted waiting for tar command to complete");
    }
    if (pr.exitValue() != 0) {
        String output = extractedPaths.stream().map(p -> p.toString()).collect(Collectors.joining("\n")).trim();
        log.error("Tar command returned non-zero exit code {}: {}", pr.exitValue(), output);
        throw new IOException("Tar command returned non-zero exit code " + pr.exitValue() + ": " + output);
    }
    return extractedPaths;
}

From source file:dk.netarkivet.harvester.harvesting.controller.AbstractJMXHeritrixController.java

/**
 * Create a BnfHeritrixController object.
 *
 * @param files//from   www.j  av  a 2  s  .co  m
 *            Files that are used to set up Heritrix.
 */
public AbstractJMXHeritrixController(HeritrixFiles files) {
    ArgumentNotValid.checkNotNull(files, "HeritrixFile files");
    this.files = files;

    SystemUtils.checkPortNotUsed(guiPort);
    SystemUtils.checkPortNotUsed(jmxPort);

    hostName = SystemUtils.getLocalHostName();

    try {
        log.info("Starting Heritrix for " + this);
        /*
         * To start Heritrix, we need to do the following (taken from the
         * Heritrix startup shell script): - set heritrix.home to base dir
         * of Heritrix stuff - set com.sun.management.jmxremote.port to JMX
         * port - set com.sun.management.jmxremote.ssl to false - set
         * com.sun.management.jmxremote.password.file to JMX password file -
         * set heritrix.out to heritrix_out.log - set
         * java.protocol.handler.pkgs=org.archive.net - send processOutput &
         * stderr into heritrix.out - let the Heritrix GUI-webserver listen
         * on all available network interfaces: This is done with argument
         * "--bind /" (default is 127.0.0.1) - listen on a specific port
         * using the port argument: --port <GUI port>
         *
         * We also need to output something like the following to
         * heritrix.out: `date Starting heritrix uname -a java -version
         * JAVA_OPTS ulimit -a
         */
        File heritrixOutputFile = files.getHeritrixOutput();
        StringBuilder settingProperty = new StringBuilder();
        for (File file : Settings.getSettingsFiles()) {
            settingProperty.append(File.pathSeparator);

            String absolutePath = file.getAbsolutePath();
            // check that the settings files not only exist but
            // are readable
            boolean readable = new File(absolutePath).canRead();
            if (!readable) {
                final String errMsg = "The file '" + absolutePath + "' is missing. ";
                log.warn(errMsg);
                throw new IOFailure("Failed to read file '" + absolutePath + "'");
            }
            settingProperty.append(absolutePath);
        }
        if (settingProperty.length() > 0) {
            // delete last path-separator
            settingProperty.deleteCharAt(0);
        }

        List<String> allOpts = new LinkedList<String>();
        allOpts.add(new File(new File(System.getProperty("java.home"), "bin"), "java").getAbsolutePath());
        allOpts.add("-Xmx" + Settings.get(HarvesterSettings.HERITRIX_HEAP_SIZE));
        allOpts.add("-Dheritrix.home=" + files.getCrawlDir().getAbsolutePath());

        String jvmOptsStr = Settings.get(HarvesterSettings.HERITRIX_JVM_OPTS);
        if ((jvmOptsStr != null) && (!jvmOptsStr.isEmpty())) {
            String[] add = jvmOptsStr.split(" ");
            allOpts.addAll(Arrays.asList(add));
        }

        allOpts.add("-Dcom.sun.management.jmxremote.port=" + jmxPort);
        allOpts.add("-Dcom.sun.management.jmxremote.ssl=false");
        // check that JMX password and access files are readable.
        // TODO This should probably be extracted to a method?
        File passwordFile = files.getJmxPasswordFile();
        String pwAbsolutePath = passwordFile.getAbsolutePath();
        if (!passwordFile.canRead()) {
            final String errMsg = "Failed to read the password file '" + pwAbsolutePath
                    + "'. It is possibly missing.";
            log.warn(errMsg);
            throw new IOFailure(errMsg);
        }
        File accessFile = files.getJmxAccessFile();
        String acAbsolutePath = accessFile.getAbsolutePath();
        if (!accessFile.canRead()) {
            final String errMsg = "Failed to read the access file '" + acAbsolutePath
                    + "'. It is possibly missing.";
            log.warn(errMsg);
            throw new IOFailure(errMsg);
        }
        allOpts.add("-Dcom.sun.management.jmxremote.password.file=" + new File(pwAbsolutePath));
        allOpts.add("-Dcom.sun.management.jmxremote.access.file=" + new File(acAbsolutePath));
        allOpts.add("-Dheritrix.out=" + heritrixOutputFile.getAbsolutePath());
        allOpts.add("-Djava.protocol.handler.pkgs=org.archive.net");
        allOpts.add("-Ddk.netarkivet.settings.file=" + settingProperty);
        allOpts.add(Heritrix.class.getName());
        allOpts.add("--bind");
        allOpts.add("/");
        allOpts.add("--port=" + guiPort);
        allOpts.add("--admin=" + getHeritrixAdminName() + ":" + getHeritrixAdminPassword());

        String[] args = allOpts.toArray(new String[allOpts.size()]);
        log.info("Starting Heritrix process with args" + Arrays.toString(args));
        log.debug("The JMX timeout is set to " + TimeUtils.readableTimeInterval(JMXUtils.getJmxTimeout()));

        ProcessBuilder builder = new ProcessBuilder(args);

        updateEnvironment(builder.environment());
        FileUtils.copyDirectory(new File("lib/heritrix"), files.getCrawlDir());
        builder.directory(files.getCrawlDir());
        builder.redirectErrorStream(true);
        writeSystemInfo(heritrixOutputFile, builder);
        FileUtils.appendToFile(heritrixOutputFile, "Working directory: " + files.getCrawlDir());
        addProcessKillerHook();
        heritrixProcess = builder.start();
        ProcessUtils.writeProcessOutput(heritrixProcess.getInputStream(), heritrixOutputFile,
                collectionThreads);
    } catch (IOException e) {
        throw new IOFailure("Error starting Heritrix process", e);
    }
}

From source file:hydrograph.ui.graph.utility.JobScpAndProcessUtility.java

/**
 * //ww  w . j a  va2  s . co  m
 * Create process builder as per operating system.
 * @param project
 * @param gradleCommand
 * @return process builder
 */
public ProcessBuilder getProcess(IProject project, String gradleCommand) {
    String[] runCommand = new String[3];
    if (OSValidator.isWindows()) {
        String[] command = { Messages.CMD, "/c", gradleCommand };
        runCommand = command;

    } else if (OSValidator.isMac()) {
        String[] command = { Messages.SHELL, "-c", gradleCommand };
        runCommand = command;
    }

    ProcessBuilder processBuilder = new ProcessBuilder(runCommand);
    processBuilder.directory(new File(project.getLocation().toOSString()));
    processBuilder.redirectErrorStream(true);
    return processBuilder;

}

From source file:com.hortonworks.streamline.streams.actions.storm.topology.StormTopologyActionsImpl.java

private ShellProcessResult executeShellProcess(List<String> commands) throws Exception {
    LOG.debug("Executing command: {}", Joiner.on(" ").join(commands));
    ProcessBuilder processBuilder = new ProcessBuilder(commands);
    processBuilder.redirectErrorStream(true);
    Process process = processBuilder.start();
    StringWriter sw = new StringWriter();
    IOUtils.copy(process.getInputStream(), sw, Charset.defaultCharset());
    String stdout = sw.toString();
    process.waitFor();//from   w ww  . j  a v a  2 s.  c  o m
    int exitValue = process.exitValue();
    LOG.debug("Command output: {}", stdout);
    LOG.debug("Command exit status: {}", exitValue);
    return new ShellProcessResult(exitValue, stdout);
}

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

/**
 * The actual execution process. Control will not return until the command
 * list execution has finished.//from w w w  .  j ava2  s .co 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:net.doubledoordev.cmd.CurseModpackDownloader.java

private Process runForgeInstaller(File file) throws IOException {
    ProcessBuilder processBuilder = new ProcessBuilder("java", "-jar", file.getName(), "--installServer");
    StringBuilder joiner = new StringBuilder("Running forge installer with command: ");
    for (String cmd : processBuilder.command())
        joiner.append(cmd).append(' ');
    if (!quiet)/*  w  w  w.  ja  v a  2s .c o m*/
        logger.println(joiner.toString());
    processBuilder.directory(output);
    processBuilder.redirectErrorStream(true);
    return processBuilder.start();
}

From source file:org.apache.maven.dotnet.AbstractDotNetMojo.java

/**
 * Launches a command line, redirecting the stream to the maven logs
 * @param commandline/*from w w w .  j av a  2 s.  c  o  m*/
 *          the command ready to be executed
 * @param reportType
 *          a display type for the report
 * @param acceptedMask
 *          a mask for the exit code of the command that is accepted (put 0 if
 *          you don't know)
 * @param throwsFailure
 *          <code>true</code> if the method should throw an exception in case
 *          of failure
 * 
 * @return the status of the command after execution
 * @throws MojoExecutionException
 *           if the execution command could not be launched for any reason
 * @throws MojoFailureException
 *           if the command status after execution is not satisfying and the
 *           throwsFailure parameter is not false
 */
protected int launchCommand(Commandline commandline, String reportType, int acceptedMask, boolean throwsFailure)
        throws MojoExecutionException, MojoFailureException {
    int commandLineResult;
    Log log = getLog();
    String[] commandLineElements = commandline.getCommandline();

    CommandStreamConsumer systemOut = new CommandStreamConsumer(log);

    try {
        // Execute the commandline
        log.debug("Executing command: " + commandline);
        log.debug("Command elements :" + Arrays.toString(commandLineElements));
        ProcessBuilder builder = new ProcessBuilder(Arrays.asList(commandLineElements));
        builder.redirectErrorStream(true);
        if (traceCommands) {
            try {
                File commandFile = getReportFile("command.txt");
                OutputStream stream = new FileOutputStream(commandFile, true);
                PrintWriter writer = new PrintWriter(stream);
                writer.println("Mojo : " + reportType + " on " + new Timestamp(System.currentTimeMillis()));
                writer.println(commandline);
                writer.println();
                writer.close();
            } catch (FileNotFoundException e) {
                // Nothing : commands are not logged
                log.debug("command.txt not found");
            }
        }
        commandLineResult = CommandLineUtils.executeCommandLine(commandline, systemOut, systemOut);

        // Check if nunit-console is not in the path
        if (systemOut.isCommandNotFound()) {
            throw new MojoExecutionException("Please add the executable for " + reportType + " to your path");
        } else if ((commandLineResult & (~acceptedMask)) != 0) {

            if (log.isWarnEnabled()) {
                log.warn("FAILURE !!!");
                log.warn("Launched command : " + commandline);
                log.warn("");
                log.warn(systemOut.getContent());
            }
            // We throw the exception only if asked for
            if (throwsFailure) {
                throw new MojoFailureException("Failure during the " + reportType
                        + " generation that ended with status=" + commandLineResult);
            }
        }
    } catch (CommandLineException e) {
        throw new MojoExecutionException(
                "Failure during the " + reportType + " generation, executing commandline:\n" + commandline, e);
    }
    return commandLineResult;
}

From source file:gov.pnnl.goss.gridappsd.app.AppManagerImpl.java

@Override
public String startAppForSimultion(String appId, String runtimeOptions, Map simulationContext) {

    String simulationId = simulationContext.get("simulationId").toString();

    appId = appId.trim();/*from   w  w w.  j a  v  a2s .  c  o m*/
    String instanceId = appId + "-" + new Date().getTime();
    // get execution path
    AppInfo appInfo = apps.get(appId);
    if (appInfo == null) {
        throw new RuntimeException("App not found: " + appId);
    }

    // are multiple allowed? if not check to see if it is already running,
    // if it is then fail
    if (!appInfo.isMultiple_instances() && listRunningApps(appId).size() > 0) {
        throw new RuntimeException("App is already running and multiple instances are not allowed: " + appId);
    }

    // build options
    // might need a standard method for replacing things like SIMULATION_ID
    // in the input/output options
    /*String optionsString = appInfo.getOptions();
    if (simulationId != null) {
       if (optionsString.contains("SIMULATION_ID")) {
    optionsString = optionsString.replace("SIMULATION_ID",
          simulationId);
       }
       if (runtimeOptions.contains("SIMULATION_ID")) {
    runtimeOptions = runtimeOptions.replace("SIMULATION_ID",
          simulationId);
       }
    }*/

    File appDirectory = new File(getAppConfigDirectory().getAbsolutePath() + File.separator + appId);

    Process process = null;
    // something like
    if (AppType.PYTHON.equals(appInfo.getType())) {
        List<String> commands = new ArrayList<String>();
        commands.add("python");
        commands.add(appInfo.getExecution_path());

        //Check if static args contain any replacement values
        List<String> staticArgsList = appInfo.getOptions();
        for (String staticArg : staticArgsList) {
            if (staticArg != null) {
                if (staticArg.contains("(")) {
                    String[] replaceArgs = StringUtils.substringsBetween(staticArg, "(", ")");
                    for (String args : replaceArgs) {
                        staticArg = staticArg.replace("(" + args + ")", simulationContext.get(args).toString());
                    }
                }
                commands.add(staticArg);
            }
        }

        if (runtimeOptions != null && !runtimeOptions.isEmpty()) {
            String runTimeString = runtimeOptions.replace(" ", "").replace("\n", "");
            commands.add(runTimeString);
        }

        ProcessBuilder processAppBuilder = new ProcessBuilder(commands);
        processAppBuilder.redirectErrorStream(true);
        processAppBuilder.redirectOutput();
        processAppBuilder.directory(appDirectory);
        logManager.log(new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(),
                "Starting app with command " + String.join(" ", commands), LogLevel.DEBUG,
                ProcessStatus.RUNNING, true), GridAppsDConstants.topic_simulationLog + simulationId);
        try {
            process = processAppBuilder.start();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // ProcessBuilder fncsBridgeBuilder = new ProcessBuilder("python",
        // getPath(GridAppsDConstants.FNCS_BRIDGE_PATH),
        // simulationConfig.getSimulation_name());
        // 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");
        // during watch, send stderr/out to logmanager

    } else if (AppType.JAVA.equals(appInfo.getType())) {
        // ProcessBuilder fncsBridgeBuilder = new ProcessBuilder("python",
        // getPath(GridAppsDConstants.FNCS_BRIDGE_PATH),
        // simulationConfig.getSimulation_name());
        // 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");
        // during watch, send stderr/out to logmanager

    } else if (AppType.WEB.equals(appInfo.getType())) {
        // ProcessBuilder fncsBridgeBuilder = new ProcessBuilder("python",
        // getPath(GridAppsDConstants.FNCS_BRIDGE_PATH),
        // simulationConfig.getSimulation_name());
        // 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");
        // during watch, send stderr/out to logmanager

    } else {
        throw new RuntimeException("Type not recognized " + appInfo.getType());
    }

    // create appinstance object
    AppInstance appInstance = new AppInstance(instanceId, appInfo, runtimeOptions, simulationId, simulationId,
            process);
    appInstance.setApp_info(appInfo);
    watch(appInstance);
    // add to app instances map
    appInstances.put(instanceId, appInstance);

    return instanceId;
}