Example usage for java.io OutputStream OutputStream

List of usage examples for java.io OutputStream OutputStream

Introduction

In this page you can find the example usage for java.io OutputStream OutputStream.

Prototype

OutputStream

Source Link

Usage

From source file:org.apache.druid.cli.PullDependencies.java

@SuppressForbidden(reason = "System#out")
private DefaultTeslaAether getAetherClient() {
    /*//from w  w  w  .  ja  v  a2  s. c o  m
    DefaultTeslaAether logs a bunch of stuff to System.out, which is annoying.  We choose to disable that
    unless debug logging is turned on.  "Disabling" it, however, is kinda bass-ackwards.  We copy out a reference
    to the current System.out, and set System.out to a noop output stream.  Then after DefaultTeslaAether has pulled
    The reference we swap things back.
            
    This has implications for other things that are running in parallel to this.  Namely, if anything else also grabs
    a reference to System.out or tries to log to it while we have things adjusted like this, then they will also log
    to nothingness.  Fortunately, the code that calls this is single-threaded and shouldn't hopefully be running
    alongside anything else that's grabbing System.out.  But who knows.
    */

    final List<String> remoteUriList = Lists.newArrayList();
    if (!noDefaultRemoteRepositories) {
        remoteUriList.addAll(DEFAULT_REMOTE_REPOSITORIES);
    }
    remoteUriList.addAll(remoteRepositories);

    List<Repository> remoteRepositories = Lists.newArrayList();
    for (String uri : remoteUriList) {
        try {
            URI u = new URI(uri);
            Repository r = new Repository(uri);

            if (u.getUserInfo() != null) {
                String[] auth = u.getUserInfo().split(":", 2);
                if (auth.length == 2) {
                    r.setUsername(auth[0]);
                    r.setPassword(auth[1]);
                } else {
                    log.warn(
                            "Invalid credentials in repository URI, expecting [<user>:<password>], got [%s] for [%s]",
                            u.getUserInfo(), uri);
                }
            }
            remoteRepositories.add(r);
        } catch (URISyntaxException e) {
            throw Throwables.propagate(e);
        }
    }

    if (log.isTraceEnabled() || log.isDebugEnabled()) {
        return createTeslaAether(remoteRepositories);
    }

    PrintStream oldOut = System.out;
    try {
        System.setOut(new PrintStream(new OutputStream() {
            @Override
            public void write(int b) {

            }

            @Override
            public void write(byte[] b) {

            }

            @Override
            public void write(byte[] b, int off, int len) {

            }
        }, false, StringUtils.UTF8_STRING));
        return createTeslaAether(remoteRepositories);
    } catch (UnsupportedEncodingException e) {
        // should never happen
        throw new IllegalStateException(e);
    } finally {
        System.setOut(oldOut);
    }
}

From source file:com.esri.geoevent.test.performance.ui.OrchestratorController.java

private void redirectSystemOutAndErrToTextArea() {
    OutputStream out = new OutputStream() {
        @Override/*from   w  ww . ja  va 2  s .  c  o  m*/
        public void write(int b) throws IOException {
            Platform.runLater(() -> outputBuffer.append(String.valueOf((char) b)));
        }
    };
    System.setOut(new PrintStream(out, true));
    OutputStream err = new OutputStream() {
        @Override
        public void write(int b) throws IOException {
            Platform.runLater(() -> outputBuffer.append(String.valueOf((char) b)));
        }
    };
    System.setErr(new PrintStream(err, true));
}

From source file:com.datatorrent.stram.cli.ApexCli.java

protected PrintStream suppressOutput() {
    PrintStream originalStream = System.out;
    if (raw) {// w  ww  . jav  a2 s .c  o m
        PrintStream dummyStream = new PrintStream(new OutputStream() {
            @Override
            public void write(int b) {
                // no-op
            }

        });
        System.setOut(dummyStream);
    }
    return originalStream;
}

From source file:fur.shadowdrake.minecraft.InstallPanel.java

private boolean doPostDownload() throws NetworkException {
    boolean b;/*from  w ww . ja va  2 s. c  o m*/
    PrintStream originalOut = System.out;
    log.setIndeterminate();
    log.setStatusText("running post-download");
    System.setOut(new PrintStream(new OutputStream() {
        @Override
        public void write(int b) throws IOException {
            byte[] x = new byte[1];
            x[0] = (byte) b;
            log.print(new String(x));
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            log.print(new String(b, off, len));
        }
    }));
    try {
        URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { new File(workingDir).toURI().toURL() });
        Class postDownloadClass = urlClassLoader.loadClass("PostDownload");
        Constructor constructor = postDownloadClass.getConstructor();
        Object pd = constructor.newInstance();
        Method method = postDownloadClass.getMethod("invoke", new Class[] { String.class, String.class });
        b = (boolean) method.invoke(pd, config.getInstallDir().getAbsolutePath(), workingDir);
        if (b) {
            showReadMe();
        }
        return b;
    } catch (MalformedURLException | ClassNotFoundException | NoSuchMethodException | SecurityException
            | InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException | NoClassDefFoundError ex) {
        Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, null, ex);
        log.println("Executing post-download failed.");
    } finally {
        System.setOut(originalOut);
        log.reset();
    }
    return false;
}

From source file:org.exist.launcher.Launcher.java

public PrintStream createLoggingProxy(final PrintStream realStream) {
    final OutputStream out = new OutputStream() {
        @Override//from www  .j a  v  a 2 s. c o  m
        public void write(int i) throws IOException {
            realStream.write(i);
            String s = String.valueOf((char) i);
            Launcher.this.setChanged();
            Launcher.this.notifyObservers(s);
        }

        @Override
        public void write(byte[] bytes) throws IOException {
            realStream.write(bytes);
            String s = new String(bytes);
            Launcher.this.setChanged();
            Launcher.this.notifyObservers(s);
        }

        @Override
        public void write(byte[] bytes, int offset, int len) throws IOException {
            realStream.write(bytes, offset, len);
            String s = new String(bytes, offset, len);
            Launcher.this.setChanged();
            Launcher.this.notifyObservers(s);
        }
    };
    return new PrintStream(out);
}

From source file:org.apache.asterix.test.common.TestExecutor.java

private static String getProcessOutput(Process p) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Future<Integer> future = Executors.newSingleThreadExecutor()
            .submit(() -> IOUtils.copy(p.getInputStream(), new OutputStream() {
                @Override/* ww  w  . j  a v a 2 s .  co m*/
                public void write(int b) throws IOException {
                    baos.write(b);
                    System.out.write(b);
                }

                @Override
                public void flush() throws IOException {
                    baos.flush();
                    System.out.flush();
                }

                @Override
                public void close() throws IOException {
                    baos.close();
                    System.out.close();
                }
            }));
    p.waitFor();
    future.get();
    ByteArrayInputStream bisIn = new ByteArrayInputStream(baos.toByteArray());
    StringWriter writerIn = new StringWriter();
    IOUtils.copy(bisIn, writerIn, StandardCharsets.UTF_8);
    StringWriter writerErr = new StringWriter();
    IOUtils.copy(p.getErrorStream(), writerErr, StandardCharsets.UTF_8);

    StringBuffer stdOut = writerIn.getBuffer();
    if (writerErr.getBuffer().length() > 0) {
        StringBuilder sbErr = new StringBuilder();
        sbErr.append("script execution failed - error message:\n"
                + "-------------------------------------------\n" + "stdout: ").append(stdOut)
                .append("\nstderr: ").append(writerErr.getBuffer())
                .append("-------------------------------------------");
        LOGGER.info(sbErr.toString());
        throw new Exception(sbErr.toString());
    }
    return stdOut.toString();
}

From source file:org.apache.geode.internal.cache.GemFireCacheImpl.java

/**
 * This is for debugging cache-open issues (esp.
 * {@link org.apache.geode.cache.CacheExistsException})
 *///from   w  w w . j  a v a  2s.  c  om
@Override
public String toString() {
    final StringBuffer sb = new StringBuffer();
    sb.append("GemFireCache[");
    sb.append("id = " + System.identityHashCode(this));
    sb.append("; isClosing = " + this.isClosing);
    sb.append("; isShutDownAll = " + isCacheAtShutdownAll());
    sb.append("; created = " + this.creationDate);
    sb.append("; server = " + this.isServer);
    sb.append("; copyOnRead = " + this.copyOnRead);
    sb.append("; lockLease = " + this.lockLease);
    sb.append("; lockTimeout = " + this.lockTimeout);
    // sb.append("; rootRegions = (" + this.rootRegions + ")");
    // sb.append("; cacheServers = (" + this.cacheServers + ")");
    // sb.append("; regionAttributes = (" + this.listRegionAttributes());
    // sb.append("; gatewayHub = " + gatewayHub);
    if (this.creationStack != null) {
        sb.append("\nCreation context:\n");
        OutputStream os = new OutputStream() {
            @Override
            public void write(int i) {
                sb.append((char) i);
            }
        };
        PrintStream ps = new PrintStream(os);
        this.creationStack.printStackTrace(ps);
    }
    sb.append("]");
    return sb.toString();
}

From source file:com.jug.MoMA.java

/**
 * Created and shows the console window and redirects System.out and
 * System.err to it./*from w w  w  .j  a v a 2 s.c om*/
 */
private void initConsoleWindow() {
    frameConsoleWindow = new JFrame(String.format("%s Console Window", this.VERSION_STRING));
    // frameConsoleWindow.setResizable( false );
    consoleWindowTextArea = new JTextArea();
    consoleWindowTextArea.setLineWrap(true);
    consoleWindowTextArea.setWrapStyleWord(true);

    final int centerX = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 2;
    final int centerY = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight() / 2;
    frameConsoleWindow.setBounds(centerX - GUI_CONSOLE_WIDTH / 2, centerY - GUI_HEIGHT / 2, GUI_CONSOLE_WIDTH,
            GUI_HEIGHT);
    final JScrollPane scrollPane = new JScrollPane(consoleWindowTextArea);
    //      scrollPane.setHorizontalScrollBarPolicy( ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER );
    scrollPane.setBorder(BorderFactory.createEmptyBorder(0, 15, 0, 0));
    frameConsoleWindow.getContentPane().add(scrollPane);

    final OutputStream out = new OutputStream() {

        private final PrintStream original = new PrintStream(System.out);

        @Override
        public void write(final int b) throws IOException {
            updateConsoleTextArea(String.valueOf((char) b));
            original.print(String.valueOf((char) b));
        }

        @Override
        public void write(final byte[] b, final int off, final int len) throws IOException {
            updateConsoleTextArea(new String(b, off, len));
            original.print(new String(b, off, len));
        }

        @Override
        public void write(final byte[] b) throws IOException {
            write(b, 0, b.length);
        }
    };

    final OutputStream err = new OutputStream() {

        private final PrintStream original = new PrintStream(System.out);

        @Override
        public void write(final int b) throws IOException {
            updateConsoleTextArea(String.valueOf((char) b));
            original.print(String.valueOf((char) b));
        }

        @Override
        public void write(final byte[] b, final int off, final int len) throws IOException {
            updateConsoleTextArea(new String(b, off, len));
            original.print(new String(b, off, len));
        }

        @Override
        public void write(final byte[] b) throws IOException {
            write(b, 0, b.length);
        }
    };

    System.setOut(new PrintStream(out, true));
    System.setErr(new PrintStream(err, true));
}

From source file:org.apache.nifi.controller.repository.FileSystemRepository.java

private OutputStream write(final ContentClaim claim, final boolean append) throws IOException {
    if (claim == null) {
        throw new NullPointerException("ContentClaim cannot be null");
    }/*from   w w w  .ja  va  2 s.co m*/

    if (!(claim instanceof StandardContentClaim)) {
        // we know that we will only create Content Claims that are of type StandardContentClaim, so if we get anything
        // else, just throw an Exception because it is not valid for this Repository
        throw new IllegalArgumentException("Cannot write to " + claim
                + " because that Content Claim does belong to this Content Repository");
    }

    final StandardContentClaim scc = (StandardContentClaim) claim;
    if (claim.getLength() > 0) {
        throw new IllegalArgumentException(
                "Cannot write to " + claim + " because it has already been written to.");
    }

    ByteCountingOutputStream claimStream = writableClaimStreams.get(scc.getResourceClaim());
    final int initialLength = append ? (int) Math.max(0, scc.getLength()) : 0;

    final ByteCountingOutputStream bcos = claimStream;
    final OutputStream out = new OutputStream() {
        private long bytesWritten = 0L;
        private boolean recycle = true;
        private boolean closed = false;

        @Override
        public String toString() {
            return "FileSystemRepository Stream [" + scc + "]";
        }

        @Override
        public synchronized void write(final int b) throws IOException {
            if (closed) {
                throw new IOException("Stream is closed");
            }

            try {
                bcos.write(b);
            } catch (final IOException ioe) {
                recycle = false;
                throw new IOException("Failed to write to " + this, ioe);
            }

            bytesWritten++;
            scc.setLength(bytesWritten + initialLength);
        }

        @Override
        public synchronized void write(final byte[] b) throws IOException {
            if (closed) {
                throw new IOException("Stream is closed");
            }

            try {
                bcos.write(b);
            } catch (final IOException ioe) {
                recycle = false;
                throw new IOException("Failed to write to " + this, ioe);
            }

            bytesWritten += b.length;
            scc.setLength(bytesWritten + initialLength);
        }

        @Override
        public synchronized void write(final byte[] b, final int off, final int len) throws IOException {
            if (closed) {
                throw new IOException("Stream is closed");
            }

            try {
                bcos.write(b, off, len);
            } catch (final IOException ioe) {
                recycle = false;
                throw new IOException("Failed to write to " + this, ioe);
            }

            bytesWritten += len;

            scc.setLength(bytesWritten + initialLength);
        }

        @Override
        public synchronized void flush() throws IOException {
            if (closed) {
                throw new IOException("Stream is closed");
            }

            bcos.flush();
        }

        @Override
        public synchronized void close() throws IOException {
            closed = true;

            if (alwaysSync) {
                ((FileOutputStream) bcos.getWrappedStream()).getFD().sync();
            }

            if (scc.getLength() < 0) {
                // If claim was not written to, set length to 0
                scc.setLength(0L);
            }

            // if we've not yet hit the threshold for appending to a resource claim, add the claim
            // to the writableClaimQueue so that the Resource Claim can be used again when create()
            // is called. In this case, we don't have to actually close the file stream. Instead, we
            // can just add it onto the queue and continue to use it for the next content claim.
            final long resourceClaimLength = scc.getOffset() + scc.getLength();
            if (recycle && resourceClaimLength < MAX_APPENDABLE_CLAIM_LENGTH) {
                final ClaimLengthPair pair = new ClaimLengthPair(scc.getResourceClaim(), resourceClaimLength);

                // We are checking that writableClaimStreams contains the resource claim as a key, as a sanity check.
                // It should always be there. However, we have encountered a bug before where we archived content before
                // we should have. As a result, the Resource Claim and the associated OutputStream were removed from the
                // writableClaimStreams map, and this caused a NullPointerException. Worse, the call here to
                // writableClaimQueue.offer() means that the ResourceClaim was then reused, which resulted in an endless
                // loop of NullPointerException's being thrown. As a result, we simply ensure that the Resource Claim does
                // in fact have an OutputStream associated with it before adding it back to the writableClaimQueue.
                final boolean enqueued = writableClaimStreams.get(scc.getResourceClaim()) != null
                        && writableClaimQueue.offer(pair);

                if (enqueued) {
                    LOG.debug("Claim length less than max; Adding {} back to Writable Claim Queue", this);
                } else {
                    writableClaimStreams.remove(scc.getResourceClaim());
                    resourceClaimManager.freeze(scc.getResourceClaim());

                    bcos.close();

                    LOG.debug("Claim length less than max; Closing {} because could not add back to queue",
                            this);
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Stack trace: ", new RuntimeException("Stack Trace for closing " + this));
                    }
                }
            } else {
                // we've reached the limit for this claim. Don't add it back to our queue.
                // Instead, just remove it and move on.

                // Mark the claim as no longer being able to be written to
                resourceClaimManager.freeze(scc.getResourceClaim());

                // ensure that the claim is no longer on the queue
                writableClaimQueue.remove(new ClaimLengthPair(scc.getResourceClaim(), resourceClaimLength));

                bcos.close();
                LOG.debug("Claim lenth >= max; Closing {}", this);
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Stack trace: ", new RuntimeException("Stack Trace for closing " + this));
                }
            }
        }
    };

    LOG.debug("Writing to {}", out);
    if (LOG.isTraceEnabled()) {
        LOG.trace("Stack trace: ", new RuntimeException("Stack Trace for writing to " + out));
    }

    return out;
}