Example usage for java.lang Process getErrorStream

List of usage examples for java.lang Process getErrorStream

Introduction

In this page you can find the example usage for java.lang Process getErrorStream.

Prototype

public abstract InputStream getErrorStream();

Source Link

Document

Returns the input stream connected to the error output of the process.

Usage

From source file:com.telefonica.euro_iaas.sdc.pupperwrapper.services.tests.ActionsServiceTest.java

@Test
public void deleteNodeNotFoundTest() throws IOException {

    Process shell = mock(Process.class);
    Process shell2 = mock(Process.class);
    Process shellNodeName = mock(Process.class);

    String[] cmd = { anyString() };
    // call to puppet cert list --all
    when(processBuilderFactory.createProcessBuilder(cmd)).thenReturn(shellNodeName).thenReturn(shell)
            .thenReturn(shell2);/*ww  w . j ava2  s .  com*/

    String strNodeName = "\"1.novalocal\"";
    when(shellNodeName.getInputStream()).thenReturn(new ByteArrayInputStream(strNodeName.getBytes("UTF-8")));
    when(shellNodeName.getErrorStream()).thenReturn(new ByteArrayInputStream(" ".getBytes("UTF-8")));

    String str = "Node 1.novalocal is registered";
    String strdelete = "Node 1 unregistered";
    when(shell.getInputStream()).thenReturn(new ByteArrayInputStream(str.getBytes("UTF-8")))
            .thenReturn(new ByteArrayInputStream(strdelete.getBytes("UTF-8")));

    String strEr = " ";
    when(shell.getErrorStream()).thenReturn(new ByteArrayInputStream(strEr.getBytes("UTF-8")));

    String str2 = "1.novalocal";
    when(shell2.getInputStream()).thenReturn(new ByteArrayInputStream(str2.getBytes("UTF-8")));

    String strEr2 = " ";
    when(shell2.getErrorStream()).thenReturn(new ByteArrayInputStream(strEr2.getBytes("UTF-8")));

    when(catalogManagerMongo.getNode("1")).thenThrow(new NoSuchElementException()).thenReturn(node1);

    when(statusLine.getStatusCode()).thenReturn(200);

    actionsService.deleteNode("1");

    verify(shell, times(1)).getInputStream();
    verify(shell2, times(1)).getInputStream();
    verify(shellNodeName, times(1)).getInputStream();
    verify(processBuilderFactory, times(3)).createProcessBuilder((String[]) anyObject());

}

From source file:com.telefonica.euro_iaas.sdc.pupperwrapper.services.tests.ActionsServiceTest.java

@Test
public void deleteNodeTestOK() throws IOException {

    Process shell = mock(Process.class);
    Process shell2 = mock(Process.class);
    Process shellNodeName = mock(Process.class);

    String[] cmd = { anyString() };
    // call to puppet cert list --all
    when(processBuilderFactory.createProcessBuilder(cmd)).thenReturn(shellNodeName).thenReturn(shell)
            .thenReturn(shell2);//from   ww  w  .j a va 2  s . c  o  m

    String strNodeName = "\"1.novalocal\"";
    when(shellNodeName.getInputStream()).thenReturn(new ByteArrayInputStream(strNodeName.getBytes("UTF-8")));
    when(shellNodeName.getErrorStream()).thenReturn(new ByteArrayInputStream(" ".getBytes("UTF-8")));

    String str = "Node 1.novalocal is registered";
    String strdelete = "Node 1 unregistered";
    when(shell.getInputStream()).thenReturn(new ByteArrayInputStream(str.getBytes("UTF-8")))
            .thenReturn(new ByteArrayInputStream(strdelete.getBytes("UTF-8")));

    String strEr = " ";
    when(shell.getErrorStream()).thenReturn(new ByteArrayInputStream(strEr.getBytes("UTF-8")));

    String str2 = "1.novalocal";
    when(shell2.getInputStream()).thenReturn(new ByteArrayInputStream(str2.getBytes("UTF-8")));

    String strEr2 = " ";
    when(shell2.getErrorStream()).thenReturn(new ByteArrayInputStream(strEr2.getBytes("UTF-8")));

    when(catalogManagerMongo.getNode("1")).thenReturn(node1).thenThrow(new NoSuchElementException())
            .thenReturn(node1);

    when(statusLine.getStatusCode()).thenReturn(200);

    actionsService.deleteNode("1");

    verify(shell, times(1)).getInputStream();
    verify(shell2, times(1)).getInputStream();
    verify(shellNodeName, times(1)).getInputStream();
    verify(processBuilderFactory, times(3)).createProcessBuilder((String[]) anyObject());

}

From source file:de.rrze.idmone.utils.jidgen.filter.ShellCmdFilter.java

public String apply(String id) {
    String cmd = this.cmdTemplate.replace("%s", id);

    logger.trace("Executing command: " + cmd);

    Runtime run = Runtime.getRuntime();
    try {// w  w  w  .j  av  a  2 s  .  com
        Process proc = run.exec(cmd);

        /*      BufferedWriter commandLine = new BufferedWriter(
                    new OutputStreamWriter(proc.getOutputStream())
              );
              commandLine.write(cmd);
              commandLine.flush();
        */
        // read stdout and log it to the debug level
        BufferedReader stdOut = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String stdOutput = "";
        while ((stdOutput = stdOut.readLine()) != null) {
            logger.debug("STDOUT: " + stdOutput);
        }
        stdOut.close();

        // read stderr and log it to the error level
        BufferedReader stdErr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
        String errOutput = "";
        while ((errOutput = stdErr.readLine()) != null) {
            logger.error("STDERR: " + errOutput);
        }
        stdErr.close();

        int exitCode = proc.waitFor();
        proc.destroy();

        if (exitCode == 0) {
            logger.trace("Filtered!");
            return null;
        } else {
            return id;
        }

    } catch (IOException e) {
        logger.fatal(e.toString());
        System.exit(120);
    } catch (InterruptedException e) {
        logger.fatal(e.toString());
        System.exit(121);
    }

    return null;
}

From source file:com.thoughtworks.go.agent.AgentProcessParentImpl.java

public int run(String launcherVersion, String launcherMd5, ServerUrlGenerator urlGenerator,
        Map<String, String> env, Map context) {
    int exitValue = 0;
    LOG.info("Agent is version: {}", CurrentGoCDVersion.getInstance().fullVersion());
    String command[] = new String[] {};

    try {//from  ww w .j  av  a  2 s.c  o m
        AgentBootstrapperArgs bootstrapperArgs = AgentBootstrapperArgs.fromProperties(context);
        File rootCertFile = bootstrapperArgs.getRootCertFile();
        SslVerificationMode sslVerificationMode = SslVerificationMode
                .valueOf(bootstrapperArgs.getSslMode().name());

        ServerBinaryDownloader agentDownloader = new ServerBinaryDownloader(urlGenerator, rootCertFile,
                sslVerificationMode);
        agentDownloader.downloadIfNecessary(DownloadableFile.AGENT);

        ServerBinaryDownloader pluginZipDownloader = new ServerBinaryDownloader(urlGenerator, rootCertFile,
                sslVerificationMode);
        pluginZipDownloader.downloadIfNecessary(DownloadableFile.AGENT_PLUGINS);

        ServerBinaryDownloader tfsImplDownloader = new ServerBinaryDownloader(urlGenerator, rootCertFile,
                sslVerificationMode);
        tfsImplDownloader.downloadIfNecessary(DownloadableFile.TFS_IMPL);

        command = agentInvocationCommand(agentDownloader.getMd5(), launcherMd5, pluginZipDownloader.getMd5(),
                tfsImplDownloader.getMd5(), env, context, agentDownloader.getExtraProperties());
        LOG.info("Launching Agent with command: {}", join(command, " "));

        Process agent = invoke(command);

        // The next lines prevent the child process from blocking on Windows

        AgentOutputAppender agentOutputAppenderForStdErr = new AgentOutputAppender(GO_AGENT_STDERR_LOG);
        AgentOutputAppender agentOutputAppenderForStdOut = new AgentOutputAppender(GO_AGENT_STDOUT_LOG);

        if (new SystemEnvironment().consoleOutToStdout()) {
            agentOutputAppenderForStdErr.writeTo(AgentOutputAppender.Outstream.STDERR);
            agentOutputAppenderForStdOut.writeTo(AgentOutputAppender.Outstream.STDOUT);
        }

        agent.getOutputStream().close();
        AgentConsoleLogThread stdErrThd = new AgentConsoleLogThread(agent.getErrorStream(),
                agentOutputAppenderForStdErr);
        stdErrThd.start();
        AgentConsoleLogThread stdOutThd = new AgentConsoleLogThread(agent.getInputStream(),
                agentOutputAppenderForStdOut);
        stdOutThd.start();

        Shutdown shutdownHook = new Shutdown(agent);
        Runtime.getRuntime().addShutdownHook(shutdownHook);
        try {
            exitValue = agent.waitFor();
        } catch (InterruptedException ie) {
            LOG.error("Agent was interrupted. Terminating agent and respawning. {}", ie.toString());
            agent.destroy();
        } finally {
            removeShutdownHook(shutdownHook);
            stdErrThd.stopAndJoin();
            stdOutThd.stopAndJoin();
        }
    } catch (Exception e) {
        LOG.error("Exception while executing command: {} - {}", join(command, " "), e.toString());
        exitValue = EXCEPTION_OCCURRED;
    }
    return exitValue;
}

From source file:jeplus.EPlusWinTools.java

/**
 * Call EPlus executable file to run the simulation
 * @param config/*from ww w . j a va2  s. c  om*/
 * @param WorkDir The working directory where the input files are stored and the output files to be generated
 * @param useReadVars Whether or not to use readvars after simulation
 * @param process Reference to the actual execution process for external access
 * @return the result code represents the state of execution steps. >=0 means successful
 */
public static int runEPlus(EPlusConfig config, String WorkDir, boolean useReadVars, ProcessWrapper process) {

    // Copy IDD, or better, create an INI pointing to the correct IDD. INI will work only on Windows systems
    if (JEPlusFrameMain.osName.toLowerCase().startsWith("windows")) {
        EPlusWinTools.writeMinimumEPlusINI(WorkDir, config.getResolvedEPlusBinDir());
    } else {
        fileCopy(config.getResolvedEPlusBinDir() + EPlusConfig.getEPDefIDD(),
                WorkDir + EPlusConfig.getEPDefIDD());
    }

    int ExitValue = -99;

    try {
        Process EPProc;

        // Run EnergyPlus ExpandObjects
        String CmdLine = config.getResolvedExpandObjects();
        EPProc = Runtime.getRuntime().exec(CmdLine, null, new File(WorkDir));
        // Console logger
        try (PrintWriter outs = (config.getScreenFile() == null) ? null
                : new PrintWriter(new FileWriter(WorkDir + "/" + config.getScreenFile(), true));) {
            if (outs != null) {
                outs.println("# Calling ExpandObjects - " + (new SimpleDateFormat()).format(new Date()));
                outs.println("# Command line: " + WorkDir + ">" + CmdLine);
                outs.flush();
            }
            StreamPrinter p_out = new StreamPrinter(EPProc.getInputStream(), "OUTPUT", outs);
            StreamPrinter p_err = new StreamPrinter(EPProc.getErrorStream(), "ERROR", outs);
            p_out.start();
            p_err.start();
            ExitValue = EPProc.waitFor();
            p_out.join();
            p_err.join();
            if (outs != null) {
                outs.println("# ExpandObjects returns: " + ExitValue);
                outs.flush();
            }
        }

        // Copy expanded.idf to in.idf
        if (new File(WorkDir + EPlusConfig.getEPDefExpandedIDF()).exists()) {
            if (!fileCopy(WorkDir + EPlusConfig.getEPDefExpandedIDF(), WorkDir + EPlusConfig.getEPDefIDF())) {
                // File copy failed
                logger.warn("Failed to copy " + WorkDir + EPlusConfig.getEPDefExpandedIDF() + " to " + WorkDir
                        + EPlusConfig.getEPDefIDF() + ". Simulation is aborted.");
                return (ExitValue);
            }
        }

        // Run EnergyPlus executable
        CmdLine = config.getResolvedEPlusEXEC();
        // EP_OMP_NUM_THREADS forced to 1. This may be overridden by the following block if present in the model
        // ProgramControl,
        //    1 ; !- Number of Threads Allowed
        EPProc = Runtime.getRuntime().exec(CmdLine, new String[] { "EP_OMP_NUM_THREADS=1" }, new File(WorkDir));
        if (process != null) {
            process.setWrappedProc(EPProc);
        }
        // Console logger
        try (PrintWriter outs = (config.getScreenFile() == null) ? null
                : new PrintWriter(new FileWriter(WorkDir + "/" + config.getScreenFile(), true));) {
            if (outs != null) {
                outs.println("# Calling EnergyPlus - " + (new SimpleDateFormat()).format(new Date()));
                outs.println("# Command line: " + WorkDir + ">" + CmdLine);
                outs.flush();
            }
            StreamPrinter p_out = new StreamPrinter(EPProc.getInputStream(), "OUTPUT", outs);
            StreamPrinter p_err = new StreamPrinter(EPProc.getErrorStream(), "ERROR", outs);
            p_out.start();
            p_err.start();
            ExitValue = EPProc.waitFor();
            p_out.join();
            p_err.join();
            if (outs != null) {
                outs.println("# EnergyPlus returns: " + ExitValue);
                outs.flush();
            }
        }

        // Run EnergyPlus ReadVarsESO
        if (useReadVars) {
            CmdLine = config.getResolvedReadVars() + " " + EPlusConfig.getEPDefRvi();
            EPProc = Runtime.getRuntime().exec(CmdLine, null, new File(WorkDir));
            // Console logger
            try (PrintWriter outs = (config.getScreenFile() == null) ? null
                    : new PrintWriter(new FileWriter(WorkDir + "/" + config.getScreenFile(), true));) {
                if (outs != null) {
                    outs.println("# Calling ReadVarsESO - " + (new SimpleDateFormat()).format(new Date()));
                    outs.println("# Command line: " + WorkDir + ">" + CmdLine);
                    outs.flush();
                }
                StreamPrinter p_out = new StreamPrinter(EPProc.getInputStream(), "OUTPUT", outs);
                StreamPrinter p_err = new StreamPrinter(EPProc.getErrorStream(), "ERROR", outs);
                p_out.start();
                p_err.start();
                ExitValue = EPProc.waitFor();
                p_out.join();
                p_err.join();
                if (outs != null) {
                    outs.println("# ReadVarsESO returns: " + ExitValue);
                    outs.flush();
                }
            }
        }
        // set it to successful
        ExitValue = 0;
    } catch (Exception ex) {
        logger.error("Error executing E+ binaries.", ex);
    }

    // Return Radiance exit value
    return ExitValue;
}

From source file:eu.planets_project.tb.gui.backing.admin.wsclient.faces.WSClientBean.java

/**
 * runs the WSI Check using the official WS-I Testing Tool (and runs
 * this tool via Runtime.exec(..))/*from  w  w w .j ava  2 s.c  o m*/
 * @param configFile - the path to the confguration file used by the 
 *                     official WS-I Testing Tool
 */
private void runWSICheck(String configFile) {
    String[] args;
    log.debug("WSI_HOME = " + System.getenv("WSI_HOME"));
    log.debug("os.name = " + System.getProperty("os.name"));
    if (System.getProperty("os.name").contains("indows")) {
        args = new String[5];
        args[0] = "cmd.exe";
        args[1] = "/C";
        args[2] = "%WSI_HOME%/java/bin/Analyzer.bat";
        args[3] = "-config";
        args[4] = configFile;
    } else {
        args = new String[4];
        args[0] = "sh";
        //args[1] = "-c";
        //args[1] = "$WSI_HOME/java/bin/Analyzer.sh";
        args[1] = System.getenv("WSI_HOME") + "/java/bin/Analyzer.sh";
        args[2] = "-config";
        args[3] = configFile;
    }

    log.debug("Execution stmt: ");
    for (int i = 0; i < args.length; i++) {
        log.debug(args[i] + " ");
    }

    try {
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(args);
        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
        StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
        errorGobbler.start();
        outputGobbler.start();

        try {
            if (proc.waitFor() != 0) {
                log.error("exit value = " + proc.exitValue());
            } else
                log.debug("Terminated gracefully");
        } catch (InterruptedException e) {
            log.error(e);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.telefonica.euro_iaas.sdc.pupperwrapper.services.tests.ActionsServiceTest.java

@Test(expected = IOException.class)
public void deleteNodeTestException() throws IOException {

    Process shell = mock(Process.class);
    Process shellNodeName = mock(Process.class);

    String[] cmd = { anyString() };
    when(processBuilderFactory.createProcessBuilder(cmd)).thenReturn(shellNodeName).thenReturn(shellNodeName)
            .thenReturn(shell);// w w w  . j a va  2 s . c  om

    String strNodeName = "1.novalocal";
    when(shellNodeName.getInputStream()).thenReturn(new ByteArrayInputStream(strNodeName.getBytes("UTF-8")))
            .thenReturn(new ByteArrayInputStream(strNodeName.getBytes("UTF-8")));
    when(shellNodeName.getErrorStream()).thenReturn(new ByteArrayInputStream(" ".getBytes("UTF-8")));

    String str = "";
    String strdelete = "";
    when(shell.getInputStream()).thenReturn(new ByteArrayInputStream(str.getBytes("UTF-8")))
            .thenReturn(new ByteArrayInputStream(strdelete.getBytes("UTF-8")));

    String strEr = " ";
    when(shell.getErrorStream()).thenReturn(new ByteArrayInputStream(strEr.getBytes("UTF-8")));

    when(catalogManagerMongo.getNode("1")).thenReturn(node1).thenThrow(new NoSuchElementException())
            .thenReturn(node1);

    // delete node 1

    actionsService.deleteNode("1");

    verify(shell, times(1)).getInputStream();
    verify(processBuilderFactory, times(3)).createProcessBuilder((String[]) anyObject());

}

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

protected InterruptedException generateInterruptedExceptionFromProcess(Process process) throws IOException {
    return new InterruptedException("\nError during process (exit code is " + process.exitValue() + "): \n"
            + this.getInputStreamToStringFromProcess(process.getErrorStream()) + "\n"
            + this.getInputStreamToStringFromProcess(process.getInputStream()));
}

From source file:io.fabric8.elasticsearch.ElasticsearchIntegrationTest.java

protected void seedSearchGuardAcls() throws Exception {
    log.info("Starting seeding of SearchGuard ACLs...");
    String configdir = basedir + "/src/it/resources/sgconfig";
    String[] cmd = { basedir + "/tools/sgadmin.sh", "-cd", configdir, "-ks", keystore, "-kst", "JKS", "-kspass",
            password, "-ts", truststore, "-tst", "JKS", "-tspass", password, "-nhnv", "-nrhn", "-icl" };
    String[] envvars = { "CONFIG_DIR=" + configdir,
            "SCRIPT_CP=" + System.getProperty("surefire.test.class.path") };
    log.debug("Seeding ACLS with: {}, {}", cmd, envvars);
    Runtime rt = Runtime.getRuntime();
    Process process = rt.exec(cmd, envvars);
    if (0 != process.waitFor()) {
        log.error("Stdout of seeding SearchGuard ACLs:\n{}", IOUtils.toString(process.getInputStream()));
        fail("Error seeding SearchGuard ACLs:\n{}" + IOUtils.toString(process.getErrorStream()));
    } else {// w  w  w  .  ja  v  a2s. co  m
        log.debug("Stdout of seeding SearchGuard ACLs:\n{}", IOUtils.toString(process.getInputStream()));
    }
    log.info("Completed seeding SearchGuard ACL");
}

From source file:com.jsystem.j2autoit.AutoItAgent.java

@Override
public boolean isProcessStillActive(String processName) throws Exception {
    String cmd = "TASKLIST.EXE /FO CSV /NH /FI \"IMAGENAME eq " + processName + "\"";
    Process child = Runtime.getRuntime().exec(cmd);
    Log.infoLog("Running the command line : " + cmd + NEW_LINE);
    return readFromStream("ErrorStream : ", child.getErrorStream())
            && readFromStream("InputStream : ", child.getInputStream());
}