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:com.adaptris.core.MarshallingBaseCase.java

public void testUncheckedMarshal_ToOutputStreamWithException() throws Exception {
    AdaptrisMarshaller marshaller = createMarshaller();
    Adapter adapter = createMarshallingObject();
    try {//from w ww .  j  av  a 2  s .  com
        AdaptrisMarshaller.uncheckedMarshal(marshaller, adapter, () -> {
            return new OutputStream() {
                @Override
                public void write(int c) throws IOException {
                    throw new IOException("testUncheckedMarshal_ToOutputStreamWithException");
                }
            };
        });
        fail();
    } catch (RuntimeException expected) {

    }
}

From source file:org.eclipse.wb.internal.core.utils.XmlWriter.java

/**
 * Opens CDATA section and returns the {@link OutputStream} to write data to it. The user
 * responsible to close the stream before any other operations with {@link XmlWriter}. Closing
 * stream automatically closes CDATA section.
 * //from w w  w. j av  a 2 s .  com
 * @return the {@link OutputStream} to write CDATA values.
 */
public OutputStream streamCDATA() {
    checkOpen();
    final TagInfo currentTag = peek();
    if (hasState(currentTag, TAG_STATE_OPEN)) {
        if (hasState(currentTag, TAG_STATE_HAS_VALUE)) {
            throw new IllegalStateException("Current tag already have the value written.");
        }
        m_printWriter.println("<![CDATA[");
        addState(currentTag, TAG_STATE_CDATA_OPEN);
        return new OutputStream() {
            @Override
            public void write(int b) throws IOException {
                m_printWriter.print((char) b);
            }

            @Override
            public void close() throws IOException {
                m_printWriter.print("]]>");
                removeState(currentTag, TAG_STATE_CDATA_OPEN);
                addState(currentTag, TAG_STATE_HAS_VALUE);
            }
        };
    }
    throw new IllegalStateException("No open tag to write CDATA contents.");
}

From source file:eu.stratosphere.test.util.AbstractTestBase.java

public static PrintStream getNullPrintStream() {
    return new PrintStream(new OutputStream() {
        @Override/*from   w w  w  .ja v a  2s.  c  o  m*/
        public void write(int b) throws IOException {
        }
    });
}

From source file:kx.c.java

/** Initializes a new {@link c} instance for the purposes of serialization only.  */
public c() {/*from ww w  .j a  v a2 s .  c  o  m*/
    vt = '\3';
    l = false;
    i = new DataInputStream(new InputStream() {
        @Override
        public int read() throws IOException {
            throw new UnsupportedOperationException("nyi");
        }
    });
    o = new OutputStream() {
        @Override
        public void write(int b) throws IOException {
            throw new UnsupportedOperationException("nyi");
        }
    };
}

From source file:eu.cassandra.platform.gui.GUI.java

/**
 * Redirects output streams to the GUI./*  w ww . j av a2  s. c o  m*/
 */
@SuppressWarnings("unused")
private void redirectSystemStreams() {
    OutputStream out = new OutputStream() {
        @Override
        public void write(int b) throws IOException {
            updateTextArea(String.valueOf((char) b));
        }

        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            updateTextArea(new String(b, off, len));
        }

        @Override
        public void write(byte[] b) throws IOException {
            write(b, 0, b.length);
        }
    };
    System.setOut(new PrintStream(out, true));
    System.setErr(new PrintStream(out, true));
}

From source file:com.vuze.android.remote.service.VuzeService.java

@Override
public void onCreate() {
    super.onCreate();
    if (CorePrefs.DEBUG_CORE) {
        Log.d(TAG, "VuzeService: onCreate");
    }//from  w  ww. j  a  v  a2  s .  c  o  m

    instance = this;
    if (BuildConfig.DEBUG) {
        //android.os.Debug.waitForDebugger();
    }

    if (!AndroidUtils.hasPermisssion(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        // TODO: implement check
        Log.d(TAG, "onCreate: No WRITE_EXTERNAL_STORAGE permission");
    }

    // requires WRITE_EXTERNAL_STORAGE
    File storageRoot = Environment.getExternalStorageDirectory();

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
        File dirDoc = Environment.getExternalStoragePublicDirectory("Documents");
        File dirDl = Environment.getExternalStoragePublicDirectory("Download");
        File dirVideo = Environment.getExternalStoragePublicDirectory("Movies");
        File dirAudio = Environment.getExternalStoragePublicDirectory("Music");
        if (CorePrefs.DEBUG_CORE) {
            Log.d("VuzeService", "Doc=" + dirDoc + "\nDL=" + dirDl + "\nVideo=" + dirVideo + "\nAudio="
                    + dirAudio + "\nStorage=" + storageRoot);
        }

    }

    File vuzeDownloadDir = new File(new File(storageRoot, "Vuze"), "Downloads");
    File internalRoot = this.getApplicationContext().getFilesDir();
    vuzeCoreConfigRoot = new File(internalRoot, ".vuze");

    if (!vuzeCoreConfigRoot.exists() || !vuzeDownloadDir.exists()) {
        File vuzeCustomDir = new File(vuzeCoreConfigRoot, "custom");
        vuzeCustomDir.mkdirs();
        try {
            File configFile = new File(vuzeCustomDir, "VuzeRemote.config");
            FileWriter fileWriter = new FileWriter(configFile, false);
            fileWriter.write(
                    "Default\\ save\\ path=string:" + vuzeDownloadDir.getAbsolutePath().replace("\\", "\\\\"));
            fileWriter.close();
        } catch (IOException e) {
        }
        vuzeDownloadDir.mkdirs();
    }

    if (CorePrefs.DEBUG_CORE) {
        Log.d(TAG, "onCreate: config root=" + vuzeCoreConfigRoot + ";manager=" + vuzeManager);
    }

    if (vuzeManager == null) {

        // TODO: If non-cellular only:
        // - Check ConnectivityManager.getActiveNetworkInfo().getType
        // - if TYPE_MOBILE, bind to "lo" or "127.0.0.1" before core start
        // - if non TYPE_MOBILE, check what's in UP state (ex. eth0, wlan0).
        // Should not be rmnet
        // - if not rmnet, bind before core start
        // ALSO
        // on network change, do the above, restarting core (shut down and start
        // again) if bind needs to change
        // If any network (cellular or otherwise)
        // - Ensure binding is blank, restart core if needed

        NetworkState networkState = VuzeRemoteApp.getNetworkState();
        networkState.addListener(this); // triggers

        buildCustomFile();
        vuzeManager = new VuzeManager(vuzeCoreConfigRoot);
        staticCore = vuzeManager.getCore();

        if (!AndroidUtils.DEBUG) {
            System.setOut(new PrintStream(new OutputStream() {
                public void write(int b) {
                    //DO NOTHING
                }
            }));
        }

        SimpleTimer.addPeriodicEvent("Update Notification", 30000, new TimerEventPerformer() {
            @Override
            public void perform(TimerEvent event) {
                updateNotification();
            }
        });

        PairingManager pairingManager = PairingManagerFactory.getSingleton();
        if (pairingManager != null) {
            try {
                Field ui = pairingManager.getClass().getDeclaredField("ui");
                ui.setAccessible(true);
                ui.set(pairingManager, this);
            } catch (Throwable t) {
                if (CorePrefs.DEBUG_CORE) {
                    Log.e(TAG, "onCreate: ", t);
                }
            }
        }
        if (CorePrefs.getPrefOnlyPluggedIn()) {
            boolean wasConnected = AndroidUtils.isPowerConnected(VuzeRemoteApp.getContext());
            boolean isConnected = AndroidUtils.isPowerConnected(VuzeRemoteApp.getContext());

            if (wasConnected != isConnected) {
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "state changed while starting up.. stop core and try again");
                }

                restartService();
                return;
            }
        }
        staticCore.addLifecycleListener(new AzureusCoreLifecycleAdapter() {

            @Override
            public void started(AzureusCore core) {
                // not called if listener is added after core is started!
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "started: core");
                }

                coreStarted = true;
                sendStuff(MSG_OUT_CORE_STARTED, null);

                updateNotification();

                core.getGlobalManager().addListener(new GlobalManagerListener() {

                    @Override
                    public void downloadManagerAdded(DownloadManager dm) {

                    }

                    @Override
                    public void downloadManagerRemoved(DownloadManager dm) {

                    }

                    @Override
                    public void destroyInitiated() {

                    }

                    @Override
                    public void destroyed() {

                    }

                    @Override
                    public void seedingStatusChanged(boolean seeding_only_mode,
                            boolean potentially_seeding_only_mode) {
                        VuzeService.this.seeding_only_mode = seeding_only_mode;
                        if (CorePrefs.DEBUG_CORE) {
                            Log.d(TAG, "seedingStatusChanged: " + seeding_only_mode);
                        }

                        if (seeding_only_mode) {
                            CorePrefs.releasePowerLock();
                        } else {
                            CorePrefs.adjustPowerLock();
                        }
                    }
                });
            }

            @Override
            public void componentCreated(AzureusCore core, AzureusCoreComponent component) {
                // GlobalManager is always called, even if already created
                if (component instanceof GlobalManager) {

                    String s = NetworkAdmin.getSingleton().getNetworkInterfacesAsString();
                    if (CorePrefs.DEBUG_CORE) {
                        Log.d(TAG, "started: " + s);
                    }

                }
                if (component instanceof PluginInterface) {
                    String pluginID = ((PluginInterface) component).getPluginID();
                    if (CorePrefs.DEBUG_CORE) {
                        Log.d(TAG, "plugin " + pluginID + " started");
                    }

                    if (pluginID.equals("xmwebui")) {
                        webUIStarted = true;
                        sendStuff(MSG_OUT_WEBUI_STARTED, null);
                        updateNotification();
                    }
                } else {
                    Log.d(TAG, "component " + component.getClass().getSimpleName() + " started");
                }
            }

            @Override
            public void stopped(AzureusCore core) {
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "stopped: core");
                }

                core.removeLifecycleListener(this);

                sendStuff(MSG_OUT_CORE_STOPPED, null);

                // This will never get called if there's a non-deamon thread
                // (measurement-1 from GA, also Binder_2, Binder_1).  Instead,
                // System.exit(0) is called, which kills the service.
                // The service is restarted (STICKY) by android & everything starts
                // up nicely.

                // in case we do get here, keep exit path consistent
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "stopped: core!");
                }

                NetworkState networkState = VuzeRemoteApp.getNetworkState();
                networkState.removeListener(VuzeService.this);

                // Delay exitVM otherwise Vuze core will error with:
                //Listener dispatch timeout: failed = com.vuze.android.remote
                // .service.VuzeService
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (CorePrefs.DEBUG_CORE) {
                            Log.d(TAG, "stopped: delayed exit vm");
                        }

                        SESecurityManager.exitVM(0);
                    }
                });
                thread.setDaemon(false);
                thread.start();
                //System.exit(0);
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "stopped: core!!");
                }

            }

            @Override
            public void stopping(AzureusCore core) {
                if (CorePrefs.DEBUG_CORE) {
                    Log.d(TAG, "stopping: core");
                }

                isCoreStopping = true;

                VuzeEasyTracker.getInstance().stop();
                sendStuff(MSG_OUT_CORE_STOPPING, null);
                CorePrefs.releasePowerLock();

                updateNotification();
            }
        });
    } else {
        if (CorePrefs.DEBUG_CORE) {
            Log.d(TAG, "onCreate: vuzeManager already created");
        }
    }
}

From source file:org.kchine.r.server.DirectJNI.java

public String runR(ExecutionUnit eu, HashMap<String, Object> clientProperties) {

    if (Thread.currentThread() == _rEngine) {
        throw new RuntimeException("runR called from within the R MainLoop Thread");
    } else {/*from  w  w  w .ja va 2  s . c om*/
        _mainLock.lock();
        _clientProperties = clientProperties;
        try {
            boolean hasConsoleInput = (eu.getConsoleInput() != null && !eu.getConsoleInput().equals(""));
            String consoleLog = null;

            _runRlock.lock();
            try {
                _sharedExecutionUnit = eu;

                try {
                    _availableCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            } finally {
                _runRlock.unlock();
            }

            consoleLog = _sharedBuffer.toString();

            if (hasConsoleInput && consoleLog.trim().equals("")) {

                System.setOut(new PrintStream(new OutputStream() {
                    public void write(final byte[] b) throws IOException {
                        _o.write(b);
                        if (new String(b).startsWith(_continueStr)) {
                            HashMap<String, Object> attrs = new HashMap<String, Object>();
                            attrs.put("log", _continueStr);
                            notifyRActionListeners(new RConsoleAction("APPEND_CONSOLE_CONTINUE", attrs));
                        }
                    }

                    public void write(final byte[] b, final int off, final int len) throws IOException {
                        _o.write(b, off, len);
                        if (new String(b, off, len).startsWith(_continueStr)) {
                            HashMap<String, Object> attrs = new HashMap<String, Object>();
                            attrs.put("log", _continueStr);
                            notifyRActionListeners(new RConsoleAction("APPEND_CONSOLE_CONTINUE", attrs));
                        }
                    }

                    public void write(final int b) throws IOException {
                        _o.write(b);
                    }
                }));

                _runRlock.lock();
                try {
                    _sharedExecutionUnit = new ExecutionUnit() {
                        public void run(Rengine e) {
                        }

                        public boolean emptyConsoleBufferBefore() {
                            return false;
                        }

                        public String getConsoleInput() {
                            return " ";
                        }
                    };

                    try {
                        _availableCondition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                } finally {
                    _runRlock.unlock();
                }

                System.setOut(_o);

            }

            return _sharedBuffer.toString();

        } finally {
            _clientProperties = null;
            _mainLock.unlock();
        }

    }
}

From source file:org.fusesource.meshkeeper.distribution.provisioner.embedded.Execute.java

/**
 * Starts a process defined by the command line.
 * Ant will not wait for this process, nor log its output.
 *
 * @throws java.io.IOException The exception is thrown, if launching
 *            of the subprocess failed.//from w ww  .j  ava 2s . com
 * @since Ant 1.6
 */
public void spawn() throws IOException {
    createWorkingDir();
    final Process process = launch(getCommandline(), getEnvironment(), workingDirectory, useVMLauncher);
    if (Os.isFamily("windows")) {
        try {
            Thread.sleep(ONE_SECOND);
        } catch (InterruptedException e) {
            LOG.debug("interruption in the sleep after having spawned a" + " process");
        }
    }
    OutputStream dummyOut = new OutputStream() {
        public void write(int b) throws IOException {
            // Method intended to swallow whatever comes at it
        }
    };

    ExecuteStreamHandler handler = new PumpStreamHandler(dummyOut);
    handler.setProcessErrorStream(process.getErrorStream());
    handler.setProcessOutputStream(process.getInputStream());
    handler.start();
    process.getOutputStream().close();

}

From source file:com.jug.MotherMachine.java

/**
 * Created and shows the console window and redirects System.out and
 * System.err to it.// w w w .  j  ava 2 s  .com
 */
private void initConsoleWindow() {
    frameConsoleWindow = new JFrame("MotherMachine Console Window");
    //      frameConsoleWindow.setResizable( false );
    consoleWindowTextArea = new JTextArea();

    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.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:io.druid.cli.PullDependencies.java

private DefaultTeslaAether getAetherClient() {
    /*/*from  www. j  a  va 2s .com*/
    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 new DefaultTeslaAether(localRepository,
                remoteRepositories.toArray(new Repository[remoteRepositories.size()]));
    }

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

            }

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

            }

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

            }
        }, false, StringUtils.UTF8_STRING));
        return new DefaultTeslaAether(localRepository,
                remoteRepositories.toArray(new Repository[remoteRepositories.size()]));
    } catch (UnsupportedEncodingException e) {
        // should never happen
        throw new IllegalStateException(e);
    } finally {
        System.setOut(oldOut);
    }
}