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.esp8266.mkspiffs.ESP8266FS.java

private int listenOnProcess(String[] arguments) {
    try {/*from  w w w.  j  a v  a2 s .  c  o m*/
        final Process p = ProcessUtils.exec(arguments);
        Thread thread = new Thread() {
            public void run() {
                try {
                    InputStreamReader reader = new InputStreamReader(p.getInputStream());
                    int c;
                    while ((c = reader.read()) != -1)
                        System.out.print((char) c);
                    reader.close();

                    reader = new InputStreamReader(p.getErrorStream());
                    while ((c = reader.read()) != -1)
                        System.err.print((char) c);
                    reader.close();
                } catch (Exception e) {
                }
            }
        };
        thread.start();
        int res = p.waitFor();
        thread.join();
        return res;
    } catch (Exception e) {
        return -1;
    }
}

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

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

    Process shell = mock(Process.class);

    String[] cmd = { anyString() };

    when(processBuilderFactory.createProcessBuilder(cmd)).thenReturn(shell).thenReturn(shell);

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

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

    Assert.assertTrue("testnodename.openstacklocal".equals(actionsService.getRealNodeName("testnodename")));

}

From source file:com.adito.community.unix.UNIXUserDatabase.java

public void changePassword(String username, String oldPassword, String password,
        boolean forcePasswordChangeAtLogon) throws UserDatabaseException, InvalidLoginCredentialsException {
    if (!supportsPasswordChange()) {
        throw new InvalidLoginCredentialsException("Database doesn't support password change.");
    }// www.  j av  a  2  s  . c om
    if (forcePasswordChangeAtLogon) {
        LOG.warn(
                "Password change function of UNIX user database does not support forcePassswordChangeAtLogon.");
    }
    Process p = null;
    try {
        p = Runtime.getRuntime()
                .exec("true".equals(SystemProperties.get("adito.useDevConfig", "false"))
                        ? "sudo /usr/sbin/chpasswd"
                        : "/usr/sbin/chpasswd");
        new StreamReaderThread(p.getInputStream());
        new StreamReaderThread(p.getErrorStream());
        OutputStream out = p.getOutputStream();
        PrintWriter pw = new PrintWriter(out);
        pw.println(username + ":" + password);
        pw.flush();
        out.close();
        try {
            p.waitFor();
        } catch (InterruptedException ie) {

        }
        int ret = p.exitValue();
        if (ret != 0) {
            throw new UserDatabaseException(
                    "Failed to change password. chpasswd returned exit code " + ret + ".");
        }

    } catch (IOException e) {
        throw new UserDatabaseException("Failed to change password.", e);
    } finally {
        if (p != null) {
            Util.closeStream(p.getOutputStream());
            Util.closeStream(p.getInputStream());
            Util.closeStream(p.getErrorStream());
        }
    }
}

From source file:ExecHelper.java

/**
 * Take a process, record its standard error and standard out streams, wait for it to finish
 *
 * @param process process to watch//from   www  .j  a v  a  2 s. c o m
 * @throws SecurityException if a security manager exists and its checkExec method doesn't allow creation of a subprocess.
 * @throws IOException - if an I/O error occurs
 * @throws NullPointerException - if cmdarray is null
 * @throws IndexOutOfBoundsException - if cmdarray is an empty array (has length 0).
 *
 * @since ostermillerutils 1.06.00
 */
private ExecHelper(Process process, String charset) throws IOException {
    StringBuffer output = new StringBuffer();
    StringBuffer error = new StringBuffer();

    Reader stdout;
    Reader stderr;

    if (charset == null) {
        // This is one time that the system charset is appropriate,
        // don't specify a character set.
        stdout = new InputStreamReader(process.getInputStream());
        stderr = new InputStreamReader(process.getErrorStream());
    } else {
        stdout = new InputStreamReader(process.getInputStream(), charset);
        stderr = new InputStreamReader(process.getErrorStream(), charset);
    }
    char[] buffer = new char[1024];

    boolean done = false;
    boolean stdoutclosed = false;
    boolean stderrclosed = false;
    while (!done) {
        boolean readSomething = false;
        // read from the process's standard output
        if (!stdoutclosed && stdout.ready()) {
            readSomething = true;
            int read = stdout.read(buffer, 0, buffer.length);
            if (read < 0) {
                readSomething = true;
                stdoutclosed = true;
            } else if (read > 0) {
                readSomething = true;
                output.append(buffer, 0, read);
            }
        }
        // read from the process's standard error
        if (!stderrclosed && stderr.ready()) {
            int read = stderr.read(buffer, 0, buffer.length);
            if (read < 0) {
                readSomething = true;
                stderrclosed = true;
            } else if (read > 0) {
                readSomething = true;
                error.append(buffer, 0, read);
            }
        }
        // Check the exit status only we haven't read anything,
        // if something has been read, the process is obviously not dead yet.
        if (!readSomething) {
            try {
                this.status = process.exitValue();
                done = true;
            } catch (IllegalThreadStateException itx) {
                // Exit status not ready yet.
                // Give the process a little breathing room.
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ix) {
                    process.destroy();
                    throw new IOException("Interrupted - processes killed");
                }
            }
        }
    }

    this.output = output.toString();
    this.error = error.toString();
}

From source file:au.com.permeance.liferay.portlet.patchingtoolinfo.cli.PatchingToolCommandRunner.java

public void runCommand() throws Exception {

    if (LOG.isDebugEnabled()) {
        LOG.debug("running patching tool command ...");
    }/*from  ww w. j av  a2s.c o  m*/

    try {

        ProcessBuilder processBuilder = configureProcessBuilder();

        // NOTE: ProcessBuilder#environent is initialised with System.getenv()
        // @see http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html#environment%28%29

        if (LOG.isDebugEnabled()) {
            LOG.debug("processBuilder : " + processBuilder);
            List<String> commandList = processBuilder.command();
            LOG.debug("command environment : " + processBuilder.environment());
            LOG.debug("command list : " + commandList);
            LOG.debug("command directory : " + processBuilder.directory());
        }

        if (LOG.isDebugEnabled()) {
            List<String> commandList = processBuilder.command();
            String processCommandStr = StringHelper.flattenStringList(commandList);
            LOG.debug("running patching tool command : " + processCommandStr);
        }

        Process process = processBuilder.start();

        if (LOG.isDebugEnabled()) {
            LOG.debug("process : " + process);
        }

        // NOTE: Java 1.8 supports Process#waitFor with a timeout
        // eg. boolean finished = iostat.waitFor(100, TimeUnit.MILLISECONDS);

        int processExitValue = process.waitFor();

        List<String> processOutputLines = IOUtils.readLines(process.getInputStream());

        List<String> processErrorLines = IOUtils.readLines(process.getErrorStream());

        this.patchingToolResults = new PatchingToolResults(processExitValue, processOutputLines,
                processErrorLines);

        if (LOG.isDebugEnabled()) {
            LOG.debug("patchingToolResults: " + patchingToolResults);
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("patching tool returned exit code " + this.patchingToolResults.getExitValue());
            LOG.debug("patching tool returned " + this.patchingToolResults.getOutputLines().size()
                    + " output lines");
            LOG.debug("--- COMMAND OUTPUT ---");
            LOG.debug(processOutputLines);
            LOG.debug("patching tool returned " + this.patchingToolResults.getErrorLines().size()
                    + " error lines");
            LOG.debug("--- COMMAND ERROR ---");
            LOG.debug(processErrorLines);
        }

        // NOTE: Command shell may return lines in the error stream that are warning messages, not errors.
        // Hence, we cannot rely upon content in the error stream as a valid error.

        if (this.patchingToolResults.getExitValue() != 0) {
            StringBuilder sb = new StringBuilder();
            String errorLine1 = null;
            if (this.patchingToolResults.hasErrorLines()) {
                errorLine1 = this.patchingToolResults.getErrorLines().get(0);
            }
            if (errorLine1 == null) {
                sb.append("Error running patching tool command.");
                sb.append(" See portal logs for more details.");
            } else {
                sb.append("Error running patching tool command : ");
                sb.append(errorLine1);
            }
            String errMsg = sb.toString();
            throw new Exception(errMsg);
        }

    } catch (Exception e) {

        String msg = "Error executing patching tool command : " + e.getMessage();
        LOG.error(msg, e);
        throw new Exception(msg, e);
    }
}

From source file:controllers.admin.AuditableController.java

public Result dumpDatabase() {
    Utilities.sendSuccessFlashMessage(Msg.get("admin.auditable.mysql.dump.request.success"));

    // prepare the notification messages
    final String successTitle = Msg.get("admin.auditable.mysql.dump.process.success.title");
    final String successMessage = Msg.get("admin.auditable.mysql.dump.process.success.message");
    final String failureTitle = Msg.get("admin.auditable.mysql.dump.process.failure.title");
    final String failureMessage = Msg.get("admin.auditable.mysql.dump.process.failure.message");

    final String uid = getUserSessionManagerPlugin().getUserSessionId(ctx());

    getSysAdminUtils().scheduleOnce(false, "MySQL Dump", Duration.create(0, TimeUnit.MILLISECONDS),
            new Runnable() {
                @Override//w  w w .j  a  v a2 s  .  co m
                public void run() {

                    INotificationManagerPlugin notificationManagerPlugin = getNotificationManagerPlugin();

                    try {
                        String host = "localhost";
                        String schema = "maf";
                        String port = "3306";
                        // URL pattern :
                        // jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]]
                        // [?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]
                        String[] completeUrl = Play.application().configuration().getString("db.default.url")
                                .split("//");
                        // if there is informations in the url
                        if (completeUrl.length > 1) {
                            String tempUrl = completeUrl[1];
                            // if many urls, get the first one only
                            if (completeUrl[1].contains(",")) {
                                tempUrl = completeUrl[1].split(",")[0];
                            }
                            // if there is a port
                            if (tempUrl.contains(":")) {
                                host = tempUrl.split(":")[0];
                                String portAndSchema = tempUrl.split(":")[1];
                                // Get the port
                                if (!tempUrl.contains("/")) {
                                    port = portAndSchema;
                                } else {
                                    port = portAndSchema.split("/")[0];
                                    schema = portAndSchema.split("/")[1];
                                    if (schema.contains("?")) {
                                        schema = schema.split("\\?")[0];
                                    }
                                }
                                // if schema without port
                            } else if (tempUrl.contains("/")) {
                                host = tempUrl.split("/")[0];
                                schema = tempUrl.split("/")[1];
                                // if no schema and no port
                            } else {
                                host = tempUrl;
                            }
                            // properties are not considered for the dump
                            if (schema.contains("?")) {
                                schema = schema.split("\\?")[0];
                            }
                        }

                        String user = Play.application().configuration().getString("db.default.username");
                        String passwd = Play.application().configuration().getString("db.default.password");
                        String path = Play.application().configuration().getString("maf.sftp.store.root");
                        String cmd = "mysqldump -R -h " + host + " -P " + port + " -u " + user + " -p" + passwd
                                + " " + schema + " | gzip > " + path
                                + "/outputs/maf_`date +'%Y-%m-%d-%H-%M-%S'`.gz";
                        Process p = Runtime.getRuntime().exec(new String[] { "sh", "-c", cmd });
                        log.debug(IOUtils.toString(p.getInputStream(), "UTF-8"));
                        log.debug(IOUtils.toString(p.getErrorStream(), "UTF-8"));
                        p.waitFor();
                        notificationManagerPlugin.sendNotification(uid,
                                NotificationCategory.getByCode(Code.INFORMATION), successTitle, successMessage,
                                controllers.admin.routes.SharedStorageManagerController.index().url());
                    } catch (Exception e) {
                        log.error(e.getMessage());
                        notificationManagerPlugin.sendNotification(uid,
                                NotificationCategory.getByCode(Code.ISSUE), failureTitle, failureMessage,
                                controllers.admin.routes.AuditableController.listAuditable().url());
                    }
                }
            });

    return redirect(routes.AuditableController.listAuditable());
}

From source file:com.asakusafw.testdriver.DefaultJobExecutor.java

private int runCommand(List<String> commandLine, Map<String, String> environmentVariables) throws IOException {
    LOG.info(MessageFormat.format(Messages.getString("DefaultJobExecutor.infoEchoCommandLine"), //$NON-NLS-1$
            toCommandLineString(commandLine)));

    ProcessBuilder builder = new ProcessBuilder(commandLine);
    builder.redirectErrorStream(true);//from ww  w  .j ava 2s .  c o m
    builder.environment().putAll(environmentVariables);
    File hadoopCommand = configurations.getHadoopCommand();
    if (hadoopCommand != null) {
        builder.environment().put("HADOOP_CMD", hadoopCommand.getAbsolutePath()); //$NON-NLS-1$
    }
    builder.directory(new File(System.getProperty("user.home", "."))); //$NON-NLS-1$ //$NON-NLS-2$

    int exitCode;
    Process process = builder.start();
    try (InputStream is = process.getInputStream()) {
        InputStreamThread it = new InputStreamThread(is);
        it.start();
        exitCode = process.waitFor();
        it.join();
    } catch (InterruptedException e) {
        throw new IOException(
                MessageFormat.format(Messages.getString("DefaultJobExecutor.errorExecutionInterrupted"), //$NON-NLS-1$
                        toCommandLineString(commandLine)),
                e);
    } finally {
        process.getOutputStream().close();
        process.getErrorStream().close();
        process.destroy();
    }
    return exitCode;
}

From source file:jeplus.EPlusWinTools.java

/**
 * Call EPlus executable file to run the simulation
 * @param config EPlus Configuration containing info of the binaries
 * @param WorkDir The working directory where the input files are stored and the output files to be generated
 * @return the exit code//from   w  ww . j  av  a 2 s . c  om
 */
public static int runEPMacro(EPlusConfig config, String WorkDir) {

    int ExitValue = -99;

    try {
        Process EPProc;
        // Run EP-Macro executable
        String CmdLine = config.getResolvedEPMacro();
        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 EP-Macro - " + (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");
            p_out.start();
            p_err.start();
            ExitValue = EPProc.waitFor();
            p_out.join();
            p_err.join();
            if (outs != null) {
                outs.println("# EP-Macro returns: " + ExitValue);
                outs.flush();
            }
        }
    } catch (Exception ex) {
        logger.error("Error running EP-Macro.", ex);
    }

    // Return Radiance exit value
    return ExitValue;
}

From source file:com.sap.prd.mobile.ios.mios.PListAccessor.java

public String getStringValue(String key) throws IOException {
    if (!plist.exists()) {
        throw new FileNotFoundException("The Plist " + plist.getAbsolutePath() + " does not exist.");
    }/*  ww w.ja  v  a2 s.  com*/

    try {
        String command = "/usr/libexec/PlistBuddy -c \"Print :" + key + "\" \"" + plist.getAbsolutePath()
                + "\"";

        System.out.println("[INFO] PlistBuddy Print command is: '" + command + "'.");

        String[] args = new String[] { "bash", "-c", command };
        Process p = Runtime.getRuntime().exec(args);
        p.waitFor();

        int exitValue = p.exitValue();

        if (exitValue == 0) {
            InputStream is = p.getInputStream();
            try {
                return new Scanner(is, Charset.defaultCharset().name()).useDelimiter("\\Z").next();
            } finally {
                closeQuietly(is);
            }
        }

        String errorMessage = "<n/a>";

        try {
            errorMessage = new Scanner(p.getErrorStream(), Charset.defaultCharset().name()).useDelimiter("\\Z")
                    .next();
        } catch (Exception ex) {
            System.out.println("[ERROR] Exception caught during retrieving error message of command '" + command
                    + "': " + ex);
        }

        if (errorMessage.contains(":" + key + "\", Does Not Exist")) {
            // ugly string parsing above, but no other known way ...
            return null;
        }

        throw new IllegalStateException(
                "Execution of \"" + StringUtils.join(args, " ") + "\" command failed. Error message is: "
                        + errorMessage + ". Return code was: '" + exitValue + "'.");
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}