List performCommand()

in src/main/java/org/apache/commons/io/FileSystemUtils.java [468:509]


    List<String> performCommand(final String[] cmdAttribs, final int max, final Duration timeout) throws IOException {
        //
        // This method does what it can to avoid the 'Too many open files' error
        // based on trial and error and these links:
        // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692
        // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4801027
        // http://forum.java.sun.com/thread.jspa?threadID=533029&messageID=2572018
        // however, it's still not perfect as the JDK support is so poor
        // (see commons-exec or Ant for a better multithreaded multi-OS solution)
        //
        final Process proc = openProcess(cmdAttribs);
        final Thread monitor = ThreadMonitor.start(timeout);
        try (InputStream in = proc.getInputStream();
                OutputStream out = proc.getOutputStream();
                // default Charset is most likely appropriate here
                InputStream err = proc.getErrorStream();
                // If in is null here, InputStreamReader throws NullPointerException
                BufferedReader inr = new BufferedReader(new InputStreamReader(in, Charset.defaultCharset()))) {

            final List<String> lines = inr.lines().limit(max).map(line -> line.toLowerCase(Locale.getDefault()).trim()).collect(Collectors.toList());
            proc.waitFor();
            ThreadMonitor.stop(monitor);

            if (proc.exitValue() != 0) {
                // Command problem, throw exception
                throw new IOException("Command line returned OS error code '" + proc.exitValue() + "' for command " + Arrays.asList(cmdAttribs));
            }
            if (lines.isEmpty()) {
                // Unknown problem, throw exception
                throw new IOException("Command line did not return any info for command " + Arrays.asList(cmdAttribs));
            }

            return lines;

        } catch (final InterruptedException ex) {
            throw new IOException("Command line threw an InterruptedException for command " + Arrays.asList(cmdAttribs) + " timeout=" + timeout, ex);
        } finally {
            if (proc != null) {
                proc.destroy();
            }
        }
    }