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.baifendian.swordfish.execserver.runner.flow.FlowRunner.java

/**
 * ?//  ww  w. j  a  va2s. c om
 */
@Override
public void run() {
    // ???
    ExecutionFlow newExecutionFlow = flowDao.queryExecutionFlow(executionFlow.getId());

    // 
    if (newExecutionFlow != null) {
        if (newExecutionFlow.getStatus().typeIsFinished()) {
            logger.info("flow is done: {}", executionFlow.getId());
            return;
        }

        // ?
        // flowDao.deleteExecutionNodes(executionFlow.getId());
    } else { // ?
        logger.info("flow is not exist: {}", executionFlow.getId());
        return;
    }

    FlowStatus status = null;

    // 
    String execLocalPath = BaseConfig.getFlowExecDir(executionFlow.getProjectId(), executionFlow.getFlowId(),
            executionFlow.getId());

    logger.info("exec id:{}, current execution dir:{}, max try times:{}, timeout:{}, failure policy type:{}",
            executionFlow.getId(), execLocalPath, maxTryTimes, timeout, failurePolicyType);

    // ????, 
    if (StringUtils.isEmpty(executionFlow.getWorkflowDataSub())) {
        Map<String, String> systemParamMap = SystemParamManager.buildSystemParam(executionFlow.getType(),
                executionFlow.getScheduleTime());

        // ?,  ${abc} = ${sf.system.bizdate}, $[yyyyMMdd] 
        Map<String, String> customParamMap = executionFlow.getUserDefinedParamMap();

        Map<String, String> allParamMap = new HashMap<>();

        if (systemParamMap != null) {
            allParamMap.putAll(systemParamMap);
        }

        if (customParamMap != null) {
            allParamMap.putAll(customParamMap);
        }

        executionFlow.setWorkflowDataSub(
                ParamHelper.resolvePlaceholders(executionFlow.getWorkflowData(), allParamMap));

        flowDao.updateExecutionFlowDataSub(executionFlow);
    }

    // 
    try {
        // 
        EnvHelper.workDirAndUserCreate(execLocalPath, executionFlow.getProxyUser(), logger);

        // ??,  DAG ?
        FlowDag flowDag = JsonUtil.parseObject(executionFlow.getWorkflowData(), FlowDag.class);

        //  workflow ? exec 
        String workflowHdfsFile = BaseConfig.getHdfsWorkflowFilename(executionFlow.getProjectId(),
                executionFlow.getWorkflowName());
        HdfsClient hdfsClient = HdfsClient.getInstance();

        if (hdfsClient.exists(workflowHdfsFile)) {
            logger.info("get hdfs workflow file:{}", workflowHdfsFile);

            String destPath = execLocalPath + File.separator + executionFlow.getWorkflowName() + ".zip";
            logger.info("Copy hdfs workflow: {} to local: {}", workflowHdfsFile, destPath);

            HdfsClient.getInstance().copyHdfsToLocal(workflowHdfsFile, destPath, false, true);

            // ?? workflow  workflowName.zip
            File zipFile = new File(destPath);
            if (zipFile.exists()) {
                String cmd = String.format("unzip -o %s -d %s", destPath, execLocalPath);

                logger.info("call cmd:{}", cmd);

                Process process = Runtime.getRuntime().exec(cmd);
                int ret = process.waitFor();
                if (ret != 0) {
                    logger.error("run cmd error:{}", cmd);
                    logger.error(IOUtils.toString(process.getErrorStream(), Charset.forName("UTF-8")));
                }
            } else {
                logger.error("can't found workflow zip file:{}", zipFile.getPath());
            }
        } else {
            logger.debug("hdfs workflow file:{} not exists", workflowHdfsFile);
        }

        // ???? "?" ?
        List<String> projectRes = genProjectResFiles(flowDag);

        //  hdfs ??
        EnvHelper.copyResToLocal(executionFlow.getProjectId(), execLocalPath, projectRes, logger);

        // ? Dag, 
        Graph<String, FlowNode, FlowNodeRelation> dagGraph = genDagGraph(flowDag);

        //  flow, ??
        status = runFlow(dagGraph);
    } catch (ExecTimeoutException e) {
        logger.error("Exec flow timeout", e);
        clean(true);
    } catch (Exception e) {
        logger.error(String.format("run exec id: %s", executionFlow.getId()), e);
        clean(true);
    } finally {
        // 
        if (status == null) {
            updateExecutionFlow(FlowStatus.FAILED);
        } else {
            //  ExecutionFlow
            updateExecutionFlow(status);
        }

        // ??
        postProcess();
    }
}

From source file:eu.scape_project.tool.toolwrapper.toolwrapper_bash_debian_generator.DebianBashWrapperGenerator.java

private boolean buildPackage() {
    boolean success = true;
    log.info("generatePackage starting now...");
    Runtime rt = Runtime.getRuntime();
    BufferedReader br = null, br2 = null;
    try {/*from   ww  w.  ja  v a 2 s. c  o m*/
        // / usr/bin/dpkg-buildpackage
        Process exec = rt.exec("/usr/bin/debuild -us -uc -b", null, tempDebianDir);
        br = new BufferedReader(new InputStreamReader(exec.getInputStream(), Charset.defaultCharset()));
        br2 = new BufferedReader(new InputStreamReader(exec.getErrorStream(), Charset.defaultCharset()));
        success = (exec.waitFor() == 0);

        String line;
        while ((line = br.readLine()) != null) {
            log.info(line);
        }

        while ((line = br2.readLine()) != null) {
            log.error(line);
        }

    } catch (InterruptedException e) {
        success = false;
    } catch (IOException e) {
        success = false;
    } finally {
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(br2);
    }
    return success;
}

From source file:gov.nih.nci.caintegrator.application.gpvisualizer.CaIntegratorRunVisualizer.java

protected void runCommand(String[] commandLine) throws IOException {
    Process p = null;
    Thread stdoutReader = null;//from w ww .  j a  va2s .c  o m
    Thread stderrReader = null;

    if (DEBUG) {
        System.out.print("executing ");
        for (int i = 0; i < commandLine.length; i++) {
            System.out.print(commandLine[i] + " ");
        }
        System.out.println();
    }

    p = Runtime.getRuntime().exec(commandLine);
    stdoutReader = copyStream(p.getInputStream(), System.out);
    stderrReader = copyStream(p.getErrorStream(), System.err);

    // drain the output and error streams
    stdoutReader.start();
    stderrReader.start();
}

From source file:com.panet.imeta.job.entries.shell.JobEntryShell.java

private void executeShell(Result result, List<RowMetaAndData> cmdRows, String[] args) {
    LogWriter log = LogWriter.getInstance();
    FileObject fileObject = null;
    String realScript = null;//from   ww  w .j  ava  2  s.  com
    FileObject tempFile = null;

    try {
        // What's the exact command?
        String base[] = null;
        List<String> cmds = new ArrayList<String>();

        if (log.isBasic())
            log.logBasic(toString(), Messages.getString("JobShell.RunningOn", Const.getOS()));

        if (insertScript) {
            realScript = environmentSubstitute(script);
        } else {
            String realFilename = environmentSubstitute(getFilename());
            fileObject = KettleVFS.getFileObject(realFilename);
        }

        if (Const.getOS().equals("Windows 95")) {
            base = new String[] { "command.com", "/C" };
        } else if (Const.getOS().startsWith("Windows")) {
            base = new String[] { "cmd.exe", "/C" };
        } else {
            if (!insertScript) {
                // Just set the command to the script we need to execute...
                //
                base = new String[] { KettleVFS.getFilename(fileObject) };
            } else {
                // Create a unique new temporary filename in the working directory, put the script in there
                // Set the permissions to execute and then run it...
                //
                try {
                    tempFile = KettleVFS.createTempFile("kettle", "shell", workDirectory);
                    tempFile.createFile();
                    OutputStream outputStream = tempFile.getContent().getOutputStream();
                    outputStream.write(realScript.getBytes());
                    outputStream.close();
                    String tempFilename = KettleVFS.getFilename(tempFile);
                    // Now we have to make this file executable...
                    // On Unix-like systems this is done using the command "/bin/chmod +x filename"
                    //
                    ProcessBuilder procBuilder = new ProcessBuilder("chmod", "+x", tempFilename);
                    Process proc = procBuilder.start();
                    // Eat/log stderr/stdout all messages in a different thread...
                    StreamLogger errorLogger = new StreamLogger(proc.getErrorStream(),
                            toString() + " (stderr)");
                    StreamLogger outputLogger = new StreamLogger(proc.getInputStream(),
                            toString() + " (stdout)");
                    new Thread(errorLogger).start();
                    new Thread(outputLogger).start();
                    proc.waitFor();

                    // Now set this filename as the base command...
                    //
                    base = new String[] { tempFilename };
                } catch (Exception e) {
                    throw new Exception("Unable to create temporary file to execute script", e);
                }
            }
        }

        // Construct the arguments...
        if (argFromPrevious && cmdRows != null) {
            // Add the base command...
            for (int i = 0; i < base.length; i++)
                cmds.add(base[i]);

            if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) {
                // for windows all arguments including the command itself
                // need to be
                // included in 1 argument to cmd/command.

                StringBuffer cmdline = new StringBuffer(300);

                cmdline.append('"');
                if (insertScript)
                    cmdline.append(realScript);
                else
                    cmdline.append(optionallyQuoteField(KettleVFS.getFilename(fileObject), "\""));
                // Add the arguments from previous results...
                for (int i = 0; i < cmdRows.size(); i++) // Normally just
                // one row, but
                // once in a
                // while to
                // remain
                // compatible we
                // have
                // multiple.
                {
                    RowMetaAndData r = (RowMetaAndData) cmdRows.get(i);
                    for (int j = 0; j < r.size(); j++) {
                        cmdline.append(' ');
                        cmdline.append(optionallyQuoteField(r.getString(j, null), "\""));
                    }
                }
                cmdline.append('"');
                cmds.add(cmdline.toString());
            } else {
                // Add the arguments from previous results...
                for (int i = 0; i < cmdRows.size(); i++) // Normally just
                // one row, but
                // once in a
                // while to
                // remain
                // compatible we
                // have
                // multiple.
                {
                    RowMetaAndData r = (RowMetaAndData) cmdRows.get(i);
                    for (int j = 0; j < r.size(); j++) {
                        cmds.add(optionallyQuoteField(r.getString(j, null), "\""));
                    }
                }
            }
        } else if (args != null) {
            // Add the base command...
            for (int i = 0; i < base.length; i++)
                cmds.add(base[i]);

            if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) {
                // for windows all arguments including the command itself
                // need to be
                // included in 1 argument to cmd/command.

                StringBuffer cmdline = new StringBuffer(300);

                cmdline.append('"');
                if (insertScript)
                    cmdline.append(realScript);
                else
                    cmdline.append(optionallyQuoteField(KettleVFS.getFilename(fileObject), "\""));

                for (int i = 0; i < args.length; i++) {
                    cmdline.append(' ');
                    cmdline.append(optionallyQuoteField(args[i], "\""));
                }
                cmdline.append('"');
                cmds.add(cmdline.toString());
            } else {
                for (int i = 0; i < args.length; i++) {
                    cmds.add(args[i]);
                }
            }
        }

        StringBuffer command = new StringBuffer();

        Iterator<String> it = cmds.iterator();
        boolean first = true;
        while (it.hasNext()) {
            if (!first)
                command.append(' ');
            else
                first = false;
            command.append((String) it.next());
        }
        if (log.isBasic())
            log.logBasic(toString(), Messages.getString("JobShell.ExecCommand", command.toString()));

        // Build the environment variable list...
        ProcessBuilder procBuilder = new ProcessBuilder(cmds);
        Map<String, String> env = procBuilder.environment();
        String[] variables = listVariables();
        for (int i = 0; i < variables.length; i++) {
            env.put(variables[i], getVariable(variables[i]));
        }

        if (getWorkDirectory() != null && !Const.isEmpty(Const.rtrim(getWorkDirectory()))) {
            String vfsFilename = environmentSubstitute(getWorkDirectory());
            File file = new File(KettleVFS.getFilename(KettleVFS.getFileObject(vfsFilename)));
            procBuilder.directory(file);
        }
        Process proc = procBuilder.start();

        // any error message?
        StreamLogger errorLogger = new StreamLogger(proc.getErrorStream(), toString() + " (stderr)");

        // any output?
        StreamLogger outputLogger = new StreamLogger(proc.getInputStream(), toString() + " (stdout)");

        // kick them off
        new Thread(errorLogger).start();
        new Thread(outputLogger).start();

        proc.waitFor();
        if (log.isDetailed())
            log.logDetailed(toString(), Messages.getString("JobShell.CommandFinished", command.toString()));

        // What's the exit status?
        result.setExitStatus(proc.exitValue());
        if (result.getExitStatus() != 0) {
            if (log.isDetailed())
                log.logDetailed(toString(), Messages.getString("JobShell.ExitStatus",
                        environmentSubstitute(getFilename()), "" + result.getExitStatus()));

            result.setNrErrors(1);
        }

        // close the streams
        // otherwise you get "Too many open files, java.io.IOException" after a lot of iterations
        proc.getErrorStream().close();
        proc.getOutputStream().close();

    } catch (IOException ioe) {
        log.logError(toString(), Messages.getString("JobShell.ErrorRunningShell",
                environmentSubstitute(getFilename()), ioe.toString()));
        result.setNrErrors(1);
    } catch (InterruptedException ie) {
        log.logError(toString(), Messages.getString("JobShell.Shellinterupted",
                environmentSubstitute(getFilename()), ie.toString()));
        result.setNrErrors(1);
    } catch (Exception e) {
        log.logError(toString(), Messages.getString("JobShell.UnexpectedError",
                environmentSubstitute(getFilename()), e.toString()));
        result.setNrErrors(1);
    } finally {
        // If we created a temporary file, remove it...
        //
        if (tempFile != null) {
            try {
                tempFile.delete();
            } catch (Exception e) {
                Messages.getString("JobShell.UnexpectedError", tempFile.toString(), e.toString());
            }
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }
}

From source file:hu.sztaki.lpds.pgportal.portlets.asm.ClientError.java

private String runSystemcmd(String[] cmd) {
    String string_error = "";
    try {/*from  ww w .  ja va 2s  .  c o m*/
        Process pr;
        pr = Runtime.getRuntime().exec(cmd);
        BufferedReader error = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
        pr.waitFor();
        string_error = error.readLine();
    } catch (Exception e) {
        string_error = e.getMessage();
    }
    return string_error;

}

From source file:net.ostis.scpdev.builder.ScRepositoryBuilder.java

/**
 * Create META-file in binary folder./*from  w ww .j  av a  2s  .  c o  m*/
 */
private void createMetaFile(IFolder binary) throws CoreException {
    IFile meta = binary.getFile("META");

    if (log.isDebugEnabled())
        log.debug("Create META for " + binary);

    String scs2tgf = ScCoreModule.getSCsCompilerPath();

    try {
        Process ps = Runtime.getRuntime()
                .exec(String.format("\"%s\" -nc - \"%s\"", scs2tgf, meta.getLocation().toOSString()));

        BufferedWriter outStream2 = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()));
        outStream2.write("\"/info/dirent\" = {META={}");

        // TODO: remove bad solution with filesystem raw working
        File binaryFolder = binary.getRawLocation().toFile();
        for (String n : binaryFolder.list()) {
            outStream2.write(",\"" + n + "\"={}");
        }

        outStream2.write("};");
        outStream2.close();

        if (ps.waitFor() != 0) {
            System.err.println(IOUtils.toString(ps.getErrorStream()));
        }
    } catch (Exception e) {
        String msg = "Error while creating META-file for binary folder " + binary;
        log.error(msg, e);
        throw new CoreException(new Status(IStatus.ERROR, ScpdevPlugin.PLUGIN_ID, msg, e));
    }
}

From source file:AltiConsole.AltiConsoleMainScreen.java

/**
 * Handles all the actions./*from w  w w. ja  v a  2 s.  c o m*/
 * 
 * @param e
 *            the action event.
 */
public void actionPerformed(final ActionEvent e) {
    final Translator trans = Application.getTranslator();

    if (e.getActionCommand().equals("EXIT")) {
        System.out.println("exit and disconnecting\n");
        if (JOptionPane.showConfirmDialog(this, trans.get("AltiConsoleMainScreen.ClosingWindow"),
                trans.get("AltiConsoleMainScreen.ReallyClosing"), JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
            DisconnectFromAlti();
            System.exit(0);
        }
    } else if (e.getActionCommand().equals("ABOUT")) {
        AboutDialog.showPreferences(AltiConsoleMainScreen.this);
    }
    // ERASE_FLIGHT
    else if (e.getActionCommand().equals("ERASE_FLIGHT")) {

        if (JOptionPane.showConfirmDialog(this, trans.get("AltiConsoleMainScreen.eraseAllflightData"),
                trans.get("AltiConsoleMainScreen.eraseAllflightDataTitle"), JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
            System.out.println("erasing flight\n");
            ErasingFlight();
        }

    } else if (e.getActionCommand().equals("RETRIEVE_FLIGHT")) {

        System.out.println("retrieving flight\n");
        RetrievingFlight();

    } else
    // SAVE_FLIGHT
    if (e.getActionCommand().equals("SAVE_FLIGHT")) {
        System.out.println("Saving current flight\n");
        SavingFlight();
    } else
    // RETRIEVE_ALTI_CFG
    if (e.getActionCommand().equals("RETRIEVE_ALTI_CFG")) {
        System.out.println("retrieving alti config\n");
        AltiConfigData pAlticonfig = retrieveAltiConfig();
        if (pAlticonfig != null)
            AltiConfigDlg.showPreferences(AltiConsoleMainScreen.this, pAlticonfig, Serial);

    }
    // LICENSE
    else if (e.getActionCommand().equals("LICENSE")) {

        LicenseDialog.showPreferences(AltiConsoleMainScreen.this);
    }
    // comPorts
    else if (e.getActionCommand().equals("comPorts")) {
        DisconnectFromAlti();
        String currentPort;
        //e.
        currentPort = (String) comPorts.getSelectedItem();
        if (Serial != null)
            Serial.searchForPorts();

        System.out.println("We have a new selected value for comport\n");
        comPorts.setSelectedItem(currentPort);
    }
    // UPLOAD_FIRMWARE
    else if (e.getActionCommand().equals("UPLOAD_FIRMWARE")) {
        System.out.println("upload firmware\n");
        //make sure to disconnect first
        DisconnectFromAlti();
        JFileChooser fc = new JFileChooser();
        String hexfile = null;
        File startFile = new File(System.getProperty("user.dir"));
        //FileNameExtensionFilter filter;

        fc.setDialogTitle("Select firmware");
        //fc.set
        fc.setCurrentDirectory(startFile);
        //fc.addChoosableFileFilter(new FileNameExtensionFilter("*.HEX", "hex"));
        fc.setFileFilter(new FileNameExtensionFilter("*.hex", "hex"));
        //fc.fil
        int action = fc.showOpenDialog(SwingUtilities.windowForComponent(this));
        if (action == JFileChooser.APPROVE_OPTION) {
            hexfile = fc.getSelectedFile().getAbsolutePath();
        }
        if (hexfile != null) {

            String exefile = UserPref.getAvrdudePath();

            String conffile = UserPref.getAvrdudeConfigPath();

            String opts = " -v -v -v -v -patmega328p -carduino -P\\\\.\\"
                    + (String) this.comPorts.getSelectedItem() + " -b115200 -D -V ";

            String cmd = exefile + " -C" + conffile + opts + " -Uflash:w:" + hexfile + ":i";
            System.out.println(cmd);

            try {
                Process p = Runtime.getRuntime().exec(cmd);
                AfficheurFlux fluxSortie = new AfficheurFlux(p.getInputStream(), this);
                AfficheurFlux fluxErreur = new AfficheurFlux(p.getErrorStream(), this);

                new Thread(fluxSortie).start();
                new Thread(fluxErreur).start();

                p.waitFor();
            } catch (IOException e1) {
                e1.printStackTrace();
            } catch (InterruptedException e2) {
                e2.printStackTrace();
            }
        }
    }
    // ON_LINE_HELP
    else if (e.getActionCommand().equals("ON_LINE_HELP")) {
        Desktop d = Desktop.getDesktop();
        System.out.println("Online help \n");
        try {
            d.browse(new URI(trans.get("help.url")));
        } catch (URISyntaxException e1) {

            System.out.println("Illegal URL:  " + trans.get("help.url") + " " + e1.getMessage());
        } catch (IOException e1) {
            System.out.println("Unable to launch browser: " + e1.getMessage());
        }

    }
}

From source file:com.twosigma.beaker.core.rest.PluginServiceLocatorRest.java

private String hashIPythonPassword(String password, String pluginId, String command) throws IOException {
    List<String> cmdBase = pythonBaseCommand(pluginId, command);
    cmdBase.add("--hash");
    cmdBase.add(password);//from www. j  a va  2 s  .c om

    Process proc = Runtime.getRuntime().exec(listToArray(cmdBase), buildEnv(pluginId, null));
    BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    new StreamGobbler(proc.getErrorStream(), "stderr", "ipython-hash", null, null).start();
    String hash = br.readLine();
    if (null == hash) {
        throw new RuntimeException("unable to get IPython hash");
    }
    return hash;
}

From source file:net.pms.PMS.java

/**
 * Executes a new Process and creates a fork that waits for its results.
 * TODO Extend explanation on where this is being used.
 * @param name Symbolic name for the process to be launched, only used in the trace log
 * @param error (boolean) Set to true if you want PMS to add error messages to the trace pane
 * @param workDir (File) optional working directory to run the process in
 * @param params (array of Strings) array containing the command to call and its arguments
 * @return Returns true if the command exited as expected
 * @throws Exception TODO: Check which exceptions to use
 *//*from   w w w.j  a  va 2  s  .  co m*/
private boolean checkProcessExistence(String name, boolean error, File workDir, String... params)
        throws Exception {
    logger.debug("launching: " + params[0]);

    try {
        ProcessBuilder pb = new ProcessBuilder(params);
        if (workDir != null) {
            pb.directory(workDir);
        }
        final Process process = pb.start();

        OutputTextConsumer stderrConsumer = new OutputTextConsumer(process.getErrorStream(), false);
        stderrConsumer.start();

        OutputTextConsumer outConsumer = new OutputTextConsumer(process.getInputStream(), false);
        outConsumer.start();

        Runnable r = new Runnable() {
            public void run() {
                ProcessUtil.waitFor(process);
            }
        };

        Thread checkThread = new Thread(r, "PMS Checker");
        checkThread.start();
        checkThread.join(60000);
        checkThread.interrupt();
        checkThread = null;

        // XXX no longer used
        if (params[0].equals("vlc") && stderrConsumer.getResults().get(0).startsWith("VLC")) {
            return true;
        }

        // XXX no longer used
        if (params[0].equals("ffmpeg") && stderrConsumer.getResults().get(0).startsWith("FF")) {
            return true;
        }

        int exit = process.exitValue();
        if (exit != 0) {
            if (error) {
                logger.info("[" + exit + "] Cannot launch " + name + " / Check the presence of " + params[0]
                        + " ...");
            }
            return false;
        }
        return true;
    } catch (Exception e) {
        if (error) {
            logger.error("Cannot launch " + name + " / Check the presence of " + params[0] + " ...", e);
        }
        return false;
    }
}

From source file:com.elasticgrid.examples.video.MencoderEncoder.java

public File convertVideo(File original, String destName, String format, int width, int height, Integer start,
        Integer end, int vbr, int abr, int fps) throws VideoConversionException, InterruptedException {
    File videoConverted = new File(original.getParent(), destName);

    logger.log(Level.FINE, "Converting video {0} into {1} as {2} format...",
            new Object[] { original, videoConverted, format });

    String command = String.format("%s %s -ofps %d -of lavf"
            + " -ovc lavc -lavcopts vcodec=%s:vbitrate=%d:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -vf scale=%d:%d"
            + " -oac mp3lame -lameopts cbr:br=%d -srate 22050 -o %s", encoderLocation,
            original.getAbsolutePath(), fps, format, vbr, width, height, abr, videoConverted.getAbsolutePath());
    if (start != null && end != null)
        command = String.format("%s -ss %d -endpos %d", command, start, end);

    logger.info("Command is: " + command);

    // run the external conversion program
    File log = new File(videoConverted.getParent(), videoConverted.getName().replace(format, "log"));
    logger.info("Writing output into " + log.getAbsolutePath());
    FileWriter fileWriter = null;
    try {/*w  ww. j ava2s  .  com*/
        fileWriter = enableLog ? new FileWriter(log) : null;
        logger.log(Level.FINEST, "Created log file in {0}", log);
    } catch (IOException e) {
        logger.log(Level.WARNING, "Can't open log file. Skipping...", e);
        fileWriter = null;
    }
    try {
        logger.finest(command);
        final Writer logWriter = enableLog ? new BufferedWriter(fileWriter) : null;
        final Process process = Runtime.getRuntime().exec(command);
        new Thread(new Runnable() {
            public void run() {
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line;
                    try {
                        while ((line = reader.readLine()) != null) {
                            if (enableLog)
                                IOUtils.write(line, logWriter);
                        }
                    } finally {
                        reader.close();
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            public void run() {
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    String line;
                    try {
                        while ((line = reader.readLine()) != null) {
                            if (enableLog)
                                IOUtils.write(line, logWriter);
                        }
                    } finally {
                        reader.close();
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }).start();
        process.waitFor();
        return videoConverted;
    } catch (IOException e) {
        throw new VideoConversionException("Can't run video conversion software", e);
    } finally {
        if (enableLog)
            IOUtils.closeQuietly(fileWriter);
    }
}