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:net.urosk.mifss.core.workers.converters.BaseMediaConverter.java

public boolean exec(String[] command) {

    Process proc;

    logger.info("cmd: " + StringUtils.join(command, " "));
    try {/*w  w  w.  j  ava 2 s.c  o  m*/

        proc = Runtime.getRuntime().exec(command);

        logger.debug("proc.std.error:" + IOUtils.toString(proc.getErrorStream(), "UTF-8"));
        logger.debug("proc.std.out:" + IOUtils.toString(proc.getInputStream(), "UTF-8"));

        //proc.destroy();

    } catch (IOException e) {
        System.out.println("IOException while trying to execute " + command);
        logger.error("IOException while trying to execute " + command, e);
        return false;
    }

    int exitStatus;

    while (true) {
        try {
            exitStatus = proc.waitFor();
            break;
        } catch (java.lang.InterruptedException e) {
            logger.error("Interrupted: Ignoring and waiting", e);
        }
    }
    if (exitStatus != 0) {
        logger.error("Error executing command: " + exitStatus);
    }

    return (exitStatus == 0);
}

From source file:com.mdsh.test.media.encoding.process.AbstractProcess.java

protected synchronized void closeProcess() {
    final Process process = getProcess();
    if (null != process) {
        IOUtils.closeQuietly(process.getInputStream());
        IOUtils.closeQuietly(process.getOutputStream());
        IOUtils.closeQuietly(process.getErrorStream());
    }/*  ww w .j av a2  s  .  com*/
}

From source file:de.cosmocode.palava.store.FileSystemStore.java

private void close(Process process) {
    Closeables.closeQuietly(process.getInputStream());
    Closeables.closeQuietly(process.getOutputStream());
    Closeables.closeQuietly(process.getErrorStream());
}

From source file:com.longevitysoft.java.bigslice.server.SlicerSlic3r.java

@Override
public void slice(@Header(value = Constants.MSG_HEADER_SLICE_CONFIG_ARRAY_LIST) String configList,
        @Header(value = Constants.MSG_HEADER_CAMEL_FILE_ABSOLUTE_PATH) String filePath,
        @Header(value = Constants.MSG_HEADER_OUTPUT_PATH) String headerOutputFilename) {
    Endpoint epSlice = camel.getEndpoint(Constants.EP_NAME_JMS_QUEUE_PENDINGSTL);
    Exchange inEx = epSlice.createExchange(ExchangePattern.InOnly);
    // check if output filename header present
    StringBuilder configFileParam = new StringBuilder();
    if (null != configList) {
        configList = configList.trim();// w  w  w .j ava  2s  .  c o m
        String[] configs = configList.split(",");
        LOG.debug("configs received in msg header");
        configFileParam.append(Constants.SPACE);
        for (String configName : configs) {
            configFileParam.append(Constants.SLIC3R_PARAM_NAME_LOAD).append(Constants.SPACE).append(configName);
        }
    }
    // check if output filename header present
    try {
        StringBuilder gcodeOutputFilename = new StringBuilder().append(Constants.PARENT_DIR)
                .append(Constants.FILEPATH_GCODEOUT); // slic3r
        // uses
        // STL
        // folder
        // by
        // default
        if (null != headerOutputFilename) {
            gcodeOutputFilename.append(Constants.SLASH)
                    .append(headerOutputFilename.replace(Constants.TILDE_BANG_TILDE,
                            Constants.SLIC3R_PARAM_VAL_INPUT_FILENAME_BASE + Constants.UNDERSCORE));
            // init directory-tree in output filename
            int lastSlash = headerOutputFilename.lastIndexOf("/");
            if (0 < lastSlash) {
                String outputTree = headerOutputFilename.substring(0, lastSlash);
                outputTree = outputTree.replace("/./", "/");
                File outDir = new File(buildOutputPath() + Constants.SLASH + outputTree);
                outDir.mkdirs();
            }
        } else {
            gcodeOutputFilename.append(Constants.SLASH).append(Constants.SLIC3R_PARAM_VAL_INPUT_FILENAME_BASE);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-dd-MM__HH-mm-ss");
            gcodeOutputFilename.append("_TS").append(sdf.format(Calendar.getInstance().getTime()));
        }
        if (null == pathToExecutable) {
            throw new InterruptedException("no exec path found");
        }
        for (int i = 0; i < pathToExecutable.size(); i++) {
            String execPath = pathToExecutable.get(i);
            // inject executable name into gcode output filename
            String insToken = null;
            int insertPos = gcodeOutputFilename.indexOf(Constants.SLIC3R_PARAM_VAL_INPUT_FILENAME_BASE);
            if (0 < insertPos) {
                insertPos += Constants.SLIC3R_PARAM_VAL_INPUT_FILENAME_BASE.length();
                if (null != execOutputFilenameFilter) {
                    insToken = execOutputFilenameFilter.get(i);
                }
                if (null == insToken) {
                    insToken = sanitizeFilename(execPath);
                }
                insToken = Constants.UNDERSCORE + insToken;
            }
            // build exec string
            final StringBuilder execStr = new StringBuilder(execPath).append(configFileParam)
                    .append(Constants.SPACE).append(Constants.SLIC3R_CLI_PARAM_OUTPUT_FILENAME_FORMAT)
                    .append(gcodeOutputFilename.substring(0, insertPos)).append(insToken)
                    .append(gcodeOutputFilename.substring(insertPos, gcodeOutputFilename.length()))
                    .append(Constants.EXT_GCODE).append(Constants.SPACE).append(filePath);
            LOG.debug("executing-slic3r: " + execStr + Constants.NEWLINE);
            final String fPath = filePath;
            final StringBuilder gcodeOutFName = gcodeOutputFilename;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Runtime rt = Runtime.getRuntime();
                        RuntimeExec rte = new RuntimeExec();
                        StreamWrapper error, output;
                        Process proc = rt.exec(execStr.toString());
                        error = rte.getStreamWrapper(proc.getErrorStream(), Constants.STREAM_NAME_ERROR);
                        output = rte.getStreamWrapper(proc.getInputStream(), Constants.STREAM_NAME_OUTPUT);
                        int exitVal = 0;
                        error.start();
                        output.start();
                        error.join(3000);
                        output.join(3000);
                        exitVal = proc.waitFor();
                        // TODO process exitVal for caller - decide what to
                        // do in
                        // http://camel.apache.org/exception-clause.html
                        LOG.info(new StringBuilder().append("stl-file-path: ").append(fPath)
                                .append(", output-file-path:").append(gcodeOutFName).append(Constants.NEWLINE)
                                .append(", proc-output: ").append(output.getMessage()).append(Constants.NEWLINE)
                                .append(", proc-error: ").append(error.getMessage()).toString());
                    } catch (Exception e) {
                        LOG.trace(e.toString());
                    }
                }
            });
        }
    } catch (InterruptedException e) {
        LOG.trace(e.toString());
    }
}

From source file:es.ehu.si.ixa.qwn.ppv.UKBwrapper.java

public void propagate(String ctxtFile) throws IOException {
    try {/*w  w w . ja  va  2 s.c  o m*/
        String[] command = { ukbPath + "/ukb_ppv", "-K", this.graph, "-D", this.langDict, "--variants", "-O",
                this.outDir, ctxtFile };
        System.err.println("UKB komandoa: " + Arrays.toString(command));

        ProcessBuilder ukbBuilder = new ProcessBuilder().command(command);
        //.redirectErrorStream(true);
        Process ukb_ppv = ukbBuilder.start();
        int success = ukb_ppv.waitFor();
        System.err.println("ukb_ppv succesful? " + success);
        if (success != 0) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ukb_ppv.getErrorStream()),
                    1);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.err.println(line);
            }
        }
    } catch (Exception e) {
        System.err.println("PropagationUKB class: error when calling ukb_ppv\n.");
        e.printStackTrace();
    }
    //"$UKB_PATH"/bin/ukb_ppv -K "$PROPAGATION_PATH"/lkb_resources/wnet30_enSyn.bin -D "$UKB_PATH"/lkb_sources/30/wnet30_dict.txt --variants -O "$PPV_OUT_DIR" $TMP_DIR/propag_posSeeds_syn.ctx  
    //mv "$PPV_OUT_DIR"/ctx_01.ppv "$PPV_OUT_DIR"/pos_syn.ppv

}

From source file:com.eucalyptus.blockstorage.HttpReader.java

private void getResponseToFile() {
    byte[] bytes = new byte[StorageProperties.TRANSFER_CHUNK_SIZE];
    FileOutputStream fileOutputStream = null;
    BufferedOutputStream bufferedOut = null;
    try {//from  w  w  w .  j  a  va2 s. c o  m
        File outFile = null;
        File outFileUncompressed = null;
        if (compressed) {
            String outFileNameUncompressed = tempPath + File.pathSeparator + file.getName()
                    + Hashes.getRandom(16);
            outFileUncompressed = new File(outFileNameUncompressed);
            outFile = new File(outFileNameUncompressed + ".gz");
        } else {
            outFile = file;
        }

        httpClient.executeMethod(method);

        // GZIPInputStream has a bug thats corrupting snapshot file system. Mounting the block device failed with unknown file system error
        /*InputStream httpIn = null;
        if(compressed) {
           httpIn = new GZIPInputStream(method.getResponseBodyAsStream());
        }
        else {
           httpIn = method.getResponseBodyAsStream();            
        }*/

        InputStream httpIn = method.getResponseBodyAsStream();
        int bytesRead;
        fileOutputStream = new FileOutputStream(outFile);
        // fileOutputStream = new FileOutputStream(file);
        bufferedOut = new BufferedOutputStream(fileOutputStream);
        while ((bytesRead = httpIn.read(bytes)) > 0) {
            bufferedOut.write(bytes, 0, bytesRead);
        }
        bufferedOut.close();

        if (compressed) {
            try {
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec(new String[] { "/bin/gunzip", outFile.getAbsolutePath() });
                StreamConsumer error = new StreamConsumer(proc.getErrorStream());
                StreamConsumer output = new StreamConsumer(proc.getInputStream());
                error.start();
                output.start();
                output.join();
                error.join();
            } catch (Exception t) {
                LOG.error(t);
            }
            if ((outFileUncompressed != null) && (!outFileUncompressed.renameTo(file))) {
                LOG.error("Unable to uncompress: " + outFile.getAbsolutePath());
                return;
            }
        }
    } catch (Exception ex) {
        LOG.error(ex, ex);
    } finally {
        method.releaseConnection();
        if (bufferedOut != null) {
            try {
                bufferedOut.close();
            } catch (IOException e) {
                LOG.error(e);
            }
        }
        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                LOG.error(e);
            }
        }
    }
}

From source file:com.wakatime.intellij.plugin.WakaTime.java

private static void sendHeartbeat(final Heartbeat heartbeat, final ArrayList<Heartbeat> extraHeartbeats) {
    final String[] cmds = buildCliCommand(heartbeat, extraHeartbeats);
    log.debug("Executing CLI: " + Arrays.toString(obfuscateKey(cmds)));
    try {//from www.j  ava 2s.c  o  m
        Process proc = Runtime.getRuntime().exec(cmds);
        if (extraHeartbeats.size() > 0) {
            String json = toJSON(extraHeartbeats);
            log.debug(json);
            try {
                BufferedWriter stdin = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
                stdin.write(json);
                stdin.write("\n");
                try {
                    stdin.flush();
                    stdin.close();
                } catch (IOException e) {
                    /* ignored because wakatime-cli closes pipe after receiving \n */ }
            } catch (IOException e) {
                log.warn(e);
            }
        }
        if (WakaTime.DEBUG) {
            BufferedReader stdout = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            BufferedReader stderr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            proc.waitFor();
            String s;
            while ((s = stdout.readLine()) != null) {
                log.debug(s);
            }
            while ((s = stderr.readLine()) != null) {
                log.debug(s);
            }
            log.debug("Command finished with return value: " + proc.exitValue());
        }
    } catch (Exception e) {
        log.warn(e);
    }
}

From source file:net.solarnetwork.node.control.ping.HttpRequesterJob.java

private void handleOSCommand(String command) {
    if (command == null) {
        return;/*from   w ww .  j a v  a2  s. co m*/
    }
    ProcessBuilder pb = new ProcessBuilder(command.split("\\s+"));
    try {
        Process pr = pb.start();
        logInputStream(pr.getInputStream(), false);
        logInputStream(pr.getErrorStream(), true);
        pr.waitFor();
        if (pr.exitValue() == 0) {
            log.debug("Command [{}] executed", command);
            handleCommandSleep();
        } else {
            log.error("Error executing [{}], exit status: {}", command, pr.exitValue());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.cisco.dvbu.ps.common.util.ScriptExecutor.java

public int executeCommand(String errorFile) {
    int exitValue = -99;

    String prefix = "ScriptExecutor::";
    String command = "";
    try {/*  w  w w.  j av a 2 s .c o  m*/
        // Print out the command and execution directory
        for (int i = 0; i < scriptArgsList.size(); i++) {
            command = command + scriptArgsList.get(i) + " ";
        }
        if (logger.isDebugEnabled()) {
            logger.debug(prefix + "-------------------------------------------------");
            logger.debug(prefix + "Command:  " + CommonUtils.maskCommand(command));
            logger.debug(prefix + "Exec Dir: " + execFromDir.toString());
        }

        // Build a new process to execute
        ProcessBuilder pb = new ProcessBuilder(scriptArgsList);

        // Setup the environment variables
        Map<String, String> env = pb.environment();
        for (int i = 0; i < envList.size(); i++) {
            String envVar = envList.get(i).toString();
            StringTokenizer st = new StringTokenizer(envVar, "=");
            if (st.hasMoreTokens()) {
                String property = st.nextToken();
                String propertyVal = "";
                try {
                    propertyVal = st.nextToken();
                } catch (Exception e) {
                }
                env.put(property, propertyVal);

                if (logger.isDebugEnabled()) {
                    logger.debug(prefix + "Env Var:  " + CommonUtils.maskCommand(envVar));
                }
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug(prefix + "-------------------------------------------------");
        }

        // Setup up the execute from directory
        File execDir = new File(execFromDir);
        pb.directory(execDir);

        if (logger.isDebugEnabled()) {
            logger.debug("");
            logger.debug("ProcessBuilder::pb.command:                    "
                    + CommonUtils.maskCommand(pb.command().toString()));
            logger.debug("ProcessBuilder::pb.directory:                  " + pb.directory().toString());
            logger.debug("ProcessBuilder::pb.directory.getAbsolutePath:  " + pb.directory().getAbsolutePath());
            logger.debug("ProcessBuilder::pb.directory.getCanonicalPath: " + pb.directory().getCanonicalPath());
            logger.debug("");
            logger.debug("ProcessBuilder::pb.environment:                "
                    + CommonUtils.maskCommand(pb.environment().toString()));
            logger.debug(prefix + "-------------------------------------------------");
            logger.debug("");
        }

        // Execute the command
        Process process = pb.start();

        OutputStream stdOutput = process.getOutputStream();

        InputStream inputStream = process.getInputStream();
        InputStream errorStream = process.getErrorStream();

        inputStreamHandler = new ScriptStreamHandler(inputStream, stdOutput);
        errorStreamHandler = new ScriptStreamHandler(errorStream);

        inputStreamHandler.start();
        errorStreamHandler.start();

        exitValue = process.waitFor();

        if (logger.isDebugEnabled()) {
            logger.debug(prefix + "exitValue for process.waitFor is: " + exitValue);
        }

        if (exitValue > 0) {
            logger.error("Error executing command=" + CommonUtils.maskCommand(command));
            logger.error("Error=" + CommonUtils.maskCommand(getStandardErrorFromCommand().toString()));
        } else {
            if (logger.isInfoEnabled()) {
                logger.info("Successfully executed command:\n" + CommonUtils.maskCommand(command));
                logger.info("Output:\n" + getStandardOutputFromCommand().toString());
            }
        }

    } catch (IOException e) {
        CompositeLogger.logException(e, e.getMessage());
        throw new CompositeException(e);
    } catch (InterruptedException e) {
        CompositeLogger.logException(e, e.getMessage());
        throw new CompositeException(e);
    }
    return exitValue;

}

From source file:de.cosmocode.palava.store.FileSystemStore.java

private void waitAndCheck(Process process) throws InterruptedException, IOException {
    if (process.waitFor() == 0) {
        return;//  w w  w . ja  v  a2  s  .  co  m
    } else {
        final byte[] bytes = ByteStreams.toByteArray(process.getErrorStream());
        final String message = new String(bytes, Charsets.UTF_8);
        throw new IOException(message);
    }
}