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.dv8tion.jda.player.source.RemoteSource.java

@Override
public synchronized AudioInfo getInfo() {
    if (audioInfo != null)
        return audioInfo;

    List<String> infoArgs = new LinkedList<>();
    if (ytdlLaunchArgsF != null) {
        infoArgs.addAll(ytdlLaunchArgsF);
        if (!infoArgs.contains("-q"))
            infoArgs.add("-q");
    } else// w  ww .j a  v a2  s  . co m
        infoArgs.addAll(YOUTUBE_DL_LAUNCH_ARGS);

    infoArgs.add("--ignore-errors"); //Ignore errors, obviously
    infoArgs.add("-j"); //Dumps the json about the file into STDout
    infoArgs.add("--skip-download"); //Doesn't actually download the file.
    infoArgs.add("--"); //Url separator. Deals with YT ids that start with --
    infoArgs.add(url); //specifies the URL to download.

    audioInfo = new AudioInfo();
    try {
        Process infoProcess = new ProcessBuilder().command(infoArgs).start();
        byte[] infoData = IOUtils.readFully(infoProcess.getErrorStream(), -1, false); //YT-DL outputs to STDerr
        if (infoData == null || infoData.length == 0)
            throw new NullPointerException("The Youtube-DL process resulted in a null or zero-length INFO!");

        String infoString = new String(infoData);
        if (infoString.startsWith("ERROR")) {
            audioInfo.error = infoString;
        } else {
            JSONObject info = new JSONObject(infoString);

            audioInfo.jsonInfo = info;
            audioInfo.title = !info.optString("title", "").isEmpty() ? info.getString("title")
                    : !info.optString("fulltitle", "").isEmpty() ? info.getString("fulltitle") : null;
            audioInfo.origin = !info.optString("webpage_url", "").isEmpty() ? info.getString("webpage_url")
                    : url;
            audioInfo.id = !info.optString("id", "").isEmpty() ? info.getString("id") : null;
            audioInfo.encoding = !info.optString("acodec", "").isEmpty() ? info.getString("acodec")
                    : !info.optString("ext", "").isEmpty() ? info.getString("ext") : null;
            audioInfo.description = !info.optString("description", "").isEmpty() ? info.getString("description")
                    : null;
            audioInfo.extractor = !info.optString("extractor", "").isEmpty() ? info.getString("extractor")
                    : !info.optString("extractor_key").isEmpty() ? info.getString("extractor_key") : null;
            audioInfo.thumbnail = !info.optString("thumbnail", "").isEmpty() ? info.getString("thumbnail")
                    : null;
            audioInfo.isLive = info.has("is_live") && !info.isNull("is_live") && info.getBoolean("is_live");
            audioInfo.duration = info.optInt("duration", -1) != -1
                    ? AudioTimestamp.fromSeconds(info.getInt("duration"))
                    : null;

            //Use FFprobe to find the duration because YT-DL didn't give it to us.
            if (audioInfo.duration == null) {
                List<String> ffprobeInfoArgs = new LinkedList<>();
                ffprobeInfoArgs.addAll(LocalSource.FFPROBE_INFO_ARGS);
                ffprobeInfoArgs.add("-i");
                ffprobeInfoArgs.add(info.optString("url", url));

                infoProcess = new ProcessBuilder().command(ffprobeInfoArgs).start();
                infoData = IOUtils.readFully(infoProcess.getInputStream(), -1, false);
                if (infoData != null && infoData.length > 0) {
                    info = new JSONObject(new String(infoData)).getJSONObject("format");

                    if (info.optDouble("duration", -1.0) != -1.0) {
                        int duration = Math.round((float) info.getDouble("duration"));
                        audioInfo.duration = AudioTimestamp.fromSeconds(duration);
                    }
                }
            }
        }
    } catch (IOException e) {
        audioInfo.error = e.getMessage();
        e.printStackTrace();
    } catch (JSONException e) {
        audioInfo.error = e.getMessage();
        e.printStackTrace();
    }
    return audioInfo;
}

From source file:net.sf.jabref.external.push.PushToEmacs.java

@Override
public void pushEntries(BibDatabase database, List<BibEntry> entries, String keys, MetaData metaData) {

    couldNotConnect = false;/*from w  ww  .  j a v  a2  s . co  m*/
    couldNotCall = false;
    notDefined = false;

    initParameters();
    commandPath = Globals.prefs.get(commandPathPreferenceKey);

    if ((commandPath == null) || commandPath.trim().isEmpty()) {
        notDefined = true;
        return;
    }

    commandPath = Globals.prefs.get(commandPathPreferenceKey);
    String[] addParams = Globals.prefs.get(JabRefPreferences.EMACS_ADDITIONAL_PARAMETERS).split(" ");
    try {
        String[] com = new String[addParams.length + 2];
        com[0] = commandPath;
        System.arraycopy(addParams, 0, com, 1, addParams.length);
        String prefix;
        String suffix;
        if (Globals.prefs.getBoolean(JabRefPreferences.EMACS_23)) {
            prefix = "(with-current-buffer (window-buffer) (insert ";
            suffix = "))";
        } else {
            prefix = "(insert ";
            suffix = ")";
        }

        com[com.length - 1] = OS.WINDOWS ?
        // Windows gnuclient escaping:
        // java string: "(insert \\\"\\\\cite{Blah2001}\\\")";
        // so cmd receives: (insert \"\\cite{Blah2001}\")
        // so emacs receives: (insert "\cite{Blah2001}")
                prefix.concat("\\\"\\" + getCiteCommand().replaceAll("\\\\", "\\\\\\\\") + "{" + keys + "}\\\"")
                        .concat(suffix)
                :
                // Linux gnuclient escaping:
                // java string: "(insert \"\\\\cite{Blah2001}\")"
                // so sh receives: (insert "\\cite{Blah2001}")
                // so emacs receives: (insert "\cite{Blah2001}")
                prefix.concat("\"" + getCiteCommand().replaceAll("\\\\", "\\\\\\\\") + "{" + keys + "}\"")
                        .concat(suffix);

        final Process p = Runtime.getRuntime().exec(com);

        JabRefExecutorService.INSTANCE.executeAndWait(() -> {
            try (InputStream out = p.getErrorStream()) {
                int c;
                StringBuilder sb = new StringBuilder();
                try {
                    while ((c = out.read()) != -1) {
                        sb.append((char) c);
                    }
                } catch (IOException e) {
                    LOGGER.warn("Could not read from stderr.", e);
                }
                // Error stream has been closed. See if there were any errors:
                if (!sb.toString().trim().isEmpty()) {
                    LOGGER.warn("Push to Emacs error: " + sb);
                    couldNotConnect = true;
                }
            } catch (IOException e) {
                LOGGER.warn("File problem.", e);
            }
        });
    } catch (IOException excep) {
        couldNotCall = true;
        LOGGER.warn("Problem pushing to Emacs.", excep);
    }
}

From source file:Main.java

public static String runScript(String script) {
    String sRet;/*from w ww.  jav a  2s .  c  o  m*/
    try {
        final Process m_process = Runtime.getRuntime().exec(script);
        final StringBuilder sbread = new StringBuilder();
        Thread tout = new Thread(new Runnable() {
            public void run() {
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(m_process.getInputStream()), 8192);
                String ls_1;
                try {
                    while ((ls_1 = bufferedReader.readLine()) != null) {
                        sbread.append(ls_1).append("\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        tout.start();

        final StringBuilder sberr = new StringBuilder();
        Thread terr = new Thread(new Runnable() {
            public void run() {
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(m_process.getErrorStream()), 8192);
                String ls_1;
                try {
                    while ((ls_1 = bufferedReader.readLine()) != null) {
                        sberr.append(ls_1).append("\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        terr.start();

        m_process.waitFor();
        while (tout.isAlive()) {
            Thread.sleep(50);
        }
        if (terr.isAlive())
            terr.interrupt();
        String stdout = sbread.toString();
        String stderr = sberr.toString();
        sRet = stdout + stderr;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return sRet;
}

From source file:com.music.scheduled.BackupJob.java

private void createBackup(String host, String port, String user, String password, String db) throws Exception {

    String fileName = "backup-" + DATE_TIME_FORMAT.print(new DateTime());
    String baseFilePath = new File(baseDir + fileName).getAbsolutePath();
    String sqlFilePath = baseFilePath + ".sql";

    String execString = "mysqldump --host=" + host + " --port=" + port + " --user=" + user
            + (StringUtils.isNotBlank(password) ? " --password=" + password : "")
            + " --compact --complete-insert --extended-insert --single-transaction "
            + "--skip-comments --skip-triggers --default-character-set=utf8 " + db + " --result-file="
            + sqlFilePath;//from w w w.  j  a  v a  2 s . c o  m

    Process process = Runtime.getRuntime().exec(execString);
    if (log.isDebugEnabled()) {
        log.debug("Output: " + IOUtils.toString(process.getInputStream()));
        log.debug("Error: " + IOUtils.toString(process.getErrorStream()));
    }
    if (process.waitFor() == 0) {

        zipBackup(baseFilePath);
    }

    File zipFile = new File(baseFilePath + ".zip");
    InputStream is = new BufferedInputStream(new FileInputStream(zipFile));
    fileStorageService.storeFile(finalBackupDir + fileName + ".zip", is, zipFile.length());

    // result = "SET FOREIGN_KEY_CHECKS = 0;\\n" + result
    // + "\\nSET FOREIGN_KEY_CHECKS = 1;";
}

From source file:com.tw.go.plugin.task.GoPluginImpl.java

private int executeCommand(String workingDirectory, Map<String, String> environmentVariables, String... command)
        throws IOException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.directory(new File(workingDirectory));
    if (environmentVariables != null && !environmentVariables.isEmpty()) {
        processBuilder.environment().putAll(environmentVariables);
    }/*from w  w  w .j a  v  a  2 s  . c o  m*/
    Process process = processBuilder.start();

    JobConsoleLogger.getConsoleLogger().readOutputOf(process.getInputStream());
    JobConsoleLogger.getConsoleLogger().readErrorOf(process.getErrorStream());

    return process.waitFor();
}

From source file:edu.wisc.doit.tcrypt.TokenEncryptDecryptIT.java

@Test
public void testOpenSSLEncJavaDec() throws Exception {
    //Encrypt with openssl
    final File encryptFileScript = setupTempFile("encryptToken.sh");
    encryptFileScript.setExecutable(true);

    final File publicKey = setupTempFile("my.wisc.edu-public.pem");

    final String expected = "foobar";
    final ProcessBuilder pb = new ProcessBuilder(encryptFileScript.getAbsolutePath(),
            publicKey.getAbsolutePath(), expected);

    final Process p = pb.start();
    final int ret = p.waitFor();
    if (ret != 0) {
        final String pOut = IOUtils.toString(p.getInputStream(), TokenEncrypter.CHARSET).trim();
        System.out.println(pOut);
        final String pErr = IOUtils.toString(p.getErrorStream(), TokenEncrypter.CHARSET).trim();
        System.out.println(pErr);
    }//from ww w. ja v  a 2 s  . c  o  m
    assertEquals(0, ret);

    final String encrypted = IOUtils.toString(p.getInputStream(), TokenEncrypter.CHARSET).trim();

    //Decrypt with java
    final String actual = this.tokenDecrypter.decrypt(encrypted);

    //Verify
    assertEquals(expected, actual);
}

From source file:edu.wisc.doit.tcrypt.TokenEncryptDecryptIT.java

@Test
public void testJavaEncOpenSSLDec() throws Exception {
    //Encrypt with Java
    final String expected = "foobar";
    final String encrypted = this.tokenEncrypter.encrypt(expected);

    //Decrypt with OpenSSL
    final File decryptFileScript = setupTempFile("decryptToken.sh");
    decryptFileScript.setExecutable(true);

    final File privateKey = setupTempFile("my.wisc.edu-private.pem");

    final ProcessBuilder pb = new ProcessBuilder(decryptFileScript.getAbsolutePath(),
            privateKey.getAbsolutePath(), encrypted);

    final Process p = pb.start();
    final int ret = p.waitFor();
    if (ret != 0) {
        final String pOut = IOUtils.toString(p.getInputStream(), TokenEncrypter.CHARSET).trim();
        System.out.println(pOut);
        final String pErr = IOUtils.toString(p.getErrorStream(), TokenEncrypter.CHARSET).trim();
        System.out.println(pErr);
    }//from   ww  w . j a va  2s. c  om
    assertEquals(0, ret);

    final String actual = IOUtils.toString(p.getInputStream(), TokenEncrypter.CHARSET).trim();

    //Verify
    assertEquals(expected, actual);
}

From source file:nju.edu.cn.LicenseRecognitionResource.java

private String executeCommand(String command) {
    StringBuffer output = new StringBuffer();

    Process p;
    try {/*  w w  w .j  a v  a 2  s  .c  o  m*/
        p = Runtime.getRuntime().exec(command);
        p.waitFor();

        BufferedReader inputReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        String line = "";

        String newLineSeparator = System.getProperty("line.separator");
        while ((line = inputReader.readLine()) != null) {
            output.append(line + newLineSeparator);
        }

        line = "";
        while ((line = errorReader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return output.toString();
}

From source file:com.tw.go.plugin.material.artifactrepository.yum.exec.command.ProcessRunner.java

public ProcessOutput execute(String[] command, Map<String, String> envMap) {
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    Process process = null;
    ProcessOutput processOutput = null;//from w  ww  . j  a  v  a2  s .c  o m
    try {
        processBuilder.environment().putAll(envMap);
        process = processBuilder.start();
        int returnCode = process.waitFor();
        List outputStream = IOUtils.readLines(process.getInputStream());
        List errorStream = IOUtils.readLines(process.getErrorStream());
        processOutput = new ProcessOutput(returnCode, outputStream, errorStream);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
    } finally {
        if (process != null) {
            closeQuietly(process.getInputStream());
            closeQuietly(process.getErrorStream());
            closeQuietly(process.getOutputStream());
            process.destroy();
        }
    }
    return processOutput;
}

From source file:android.databinding.compilationTest.BaseCompilationTest.java

protected CompilationResult runGradle(String... params) throws IOException, InterruptedException {
    setExecutable();/* w ww.j  a  v a2s.  c  o m*/
    File pathToExecutable = new File(testFolder, "gradlew");
    List<String> args = new ArrayList<>();
    args.add(pathToExecutable.getAbsolutePath());
    args.add("-P" + PRINT_ENCODED_ERRORS_PROPERTY + "=true");
    args.add("--project-cache-dir");
    args.add(new File("../.caches/", name.getMethodName()).getAbsolutePath());
    Collections.addAll(args, params);
    ProcessBuilder builder = new ProcessBuilder(args);
    builder.environment().putAll(System.getenv());
    String javaHome = System.getProperty("java.home");
    if (StringUtils.isNotBlank(javaHome)) {
        builder.environment().put("JAVA_HOME", javaHome);
    }
    builder.directory(testFolder);
    Process process = builder.start();
    String output = IOUtils.toString(process.getInputStream());
    String error = IOUtils.toString(process.getErrorStream());
    int result = process.waitFor();
    return new CompilationResult(result, output, error);
}