Example usage for java.nio.channels WritableByteChannel write

List of usage examples for java.nio.channels WritableByteChannel write

Introduction

In this page you can find the example usage for java.nio.channels WritableByteChannel write.

Prototype

public int write(ByteBuffer src) throws IOException;

Source Link

Document

Writes a sequence of bytes to this channel from the given buffer.

Usage

From source file:org.esxx.Response.java

public static void writeObject(Object object, ContentType ct, OutputStream out) throws IOException {

    if (object == null) {
        return;//w w  w .  j av a  2  s  .c  o  m
    }

    // Unwrap wrapped objects
    object = JS.toJavaObject(object);

    // Convert complex types to primitive types
    if (object instanceof Node) {
        ESXX esxx = ESXX.getInstance();

        if (ct.match("message/rfc822")) {
            try {
                String xml = esxx.serializeNode((Node) object);
                org.esxx.xmtp.XMTPParser xmtpp = new org.esxx.xmtp.XMTPParser();
                javax.mail.Message msg = xmtpp.convertMessage(new StringReader(xml));
                object = new ByteArrayOutputStream();
                msg.writeTo(new FilterOutputStream((OutputStream) object) {
                    @Override
                    public void write(int b) throws IOException {
                        if (b == '\r') {
                            return;
                        } else if (b == '\n') {
                            out.write('\r');
                            out.write('\n');
                        } else {
                            out.write(b);
                        }
                    }
                });
            } catch (javax.xml.stream.XMLStreamException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            } catch (javax.mail.MessagingException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            }
        } else {
            object = esxx.serializeNode((Node) object);
        }
    } else if (object instanceof Scriptable) {
        if (ct.match("application/x-www-form-urlencoded")) {
            String cs = Parsers.getParameter(ct, "charset", "UTF-8");

            object = StringUtil.encodeFormVariables(cs, (Scriptable) object);
        } else if (ct.match("text/csv")) {
            object = jsToCSV(ct, (Scriptable) object);
        } else {
            object = jsToJSON(object).toString();
        }
    } else if (object instanceof byte[]) {
        object = new ByteArrayInputStream((byte[]) object);
    } else if (object instanceof File) {
        object = new FileInputStream((File) object);
    }

    // Serialize primitive types
    if (object instanceof ByteArrayOutputStream) {
        ByteArrayOutputStream bos = (ByteArrayOutputStream) object;

        bos.writeTo(out);
    } else if (object instanceof ByteBuffer) {
        // Write result as-is to output stream
        WritableByteChannel wbc = Channels.newChannel(out);
        ByteBuffer bb = (ByteBuffer) object;

        bb.rewind();

        while (bb.hasRemaining()) {
            wbc.write(bb);
        }

        wbc.close();
    } else if (object instanceof InputStream) {
        IO.copyStream((InputStream) object, out);
    } else if (object instanceof Reader) {
        // Write stream as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);

        IO.copyReader((Reader) object, ow);
    } else if (object instanceof String) {
        // Write string as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);
        ow.write((String) object);
        ow.flush();
    } else if (object instanceof RenderedImage) {
        Iterator<ImageWriter> i = ImageIO.getImageWritersByMIMEType(ct.getBaseType());

        if (!i.hasNext()) {
            throw new ESXXException("No ImageWriter available for " + ct.getBaseType());
        }

        ImageWriter writer = i.next();

        writer.setOutput(ImageIO.createImageOutputStream(out));
        writer.write((RenderedImage) object);
    } else {
        throw new UnsupportedOperationException("Unsupported object class type: " + object.getClass());
    }
}

From source file:net.vexelon.myglob.utils.Utils.java

/**
 * Reads an input stream into a byte array
 * @param source/*from   w  ww.  j av a  2 s .c o  m*/
 * @return Byte array of input stream data
 * @throws IOException
 */
public static byte[] read(InputStream source) throws IOException {
    ReadableByteChannel srcChannel = Channels.newChannel(source);
    ByteArrayOutputStream baos = new ByteArrayOutputStream(
            source.available() > 0 ? source.available() : BUFFER_PAGE_SIZE);
    WritableByteChannel destination = Channels.newChannel(baos);

    try {
        ByteBuffer buffer = ByteBuffer.allocate(BUFFER_PAGE_SIZE);
        while (srcChannel.read(buffer) > 0) {
            buffer.flip();
            while (buffer.hasRemaining()) {
                destination.write(buffer);
            }
            buffer.clear();
        }
        return baos.toByteArray();
    } catch (IOException e) {
        throw e;
    } finally {
        try {
            if (srcChannel != null)
                srcChannel.close();
        } catch (IOException e) {
        }
        try {
            if (source != null)
                source.close();
        } catch (IOException e) {
        }
        try {
            if (destination != null)
                destination.close();
        } catch (IOException e) {
        }
    }
}

From source file:com.meltmedia.cadmium.core.FileSystemManager.java

public static void streamCopy(InputStream streamIn, OutputStream streamOut, boolean leaveOutputOpen)
        throws IOException {
    ReadableByteChannel input = Channels.newChannel(streamIn);
    WritableByteChannel output = Channels.newChannel(streamOut);

    ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);

    while (input.read(buffer) != -1) {
        buffer.flip();//from   w  w  w. j a  va  2  s .  co m

        output.write(buffer);

        buffer.compact();
    }

    buffer.flip();

    // Make sure the buffer is empty
    while (buffer.hasRemaining()) {
        output.write(buffer);
    }

    input.close();
    if (!leaveOutputOpen) {
        output.close();
    }
}

From source file:Main.java

public static void copy(ReadableByteChannel in, WritableByteChannel out) throws IOException {
    // First, we need a buffer to hold blocks of copied bytes.
    ByteBuffer buffer = ByteBuffer.allocateDirect(32 * 1024);

    // Now loop until no more bytes to read and the buffer is empty
    while (in.read(buffer) != -1 || buffer.position() > 0) {
        // The read() call leaves the buffer in "fill mode". To prepare
        // to write bytes from the bufferwe have to put it in "drain mode"
        // by flipping it: setting limit to position and position to zero
        buffer.flip();//from w ww.ja  v a2  s.c om

        // Now write some or all of the bytes out to the output channel
        out.write(buffer);

        // Compact the buffer by discarding bytes that were written,
        // and shifting any remaining bytes. This method also
        // prepares the buffer for the next call to read() by setting the
        // position to the limit and the limit to the buffer capacity.
        buffer.compact();
    }
}

From source file:com.mgmtp.perfload.perfalyzer.util.IoUtilities.java

/**
 * Copies the content from one channel to another.
 *
 * @param srcChannel/*from   w  w  w  .  j ava 2  s.  c o m*/
 *       the source channel to copy from
 * @param destChannel
 *       the destination channel to copy to
 */
public static void copy(final ReadableByteChannel srcChannel, final WritableByteChannel destChannel)
        throws IOException {
    final ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
    while (srcChannel.read(buffer) != -1) {
        // flip the buffer so it can be written to the destination channel
        buffer.flip();

        // write to the destination channel
        destChannel.write(buffer);

        // If partial transfer, shift remainder down so it does not get lost
        // If buffer is empty, this is the same as calling clear()
        buffer.compact();
    }

    // EOF will leave buffer in fill state
    buffer.flip();

    // make sure the buffer is fully drained
    while (buffer.hasRemaining()) {
        destChannel.write(buffer);
    }
}

From source file:com.sunchenbin.store.feilong.core.io.IOWriteUtil.java

/**
 * NIO API ?? ()./*  ww w .j  a  va  2s .  c  o  m*/
 * 
 * <h3>NIO</h3>
 * 
 * <blockquote>
 * <p>
 * nionew io,jdk1.4,??<br>
 * nio??<br>
 * </p>
 * 
 * <p>
 * ??,<br>
 * ?,,??? ????cpu,?cpu? <br>
 * ? Java IO ,? IO,NIO ?? IO
 * </p>
 * 
 * <p>
 * The new I/O (NIO) APIs introduced in v 1.4 provide new features and improved performance in the areas of buffer management, scalable
 * network and file I/O, character-set support, and regular-expression matching. The NIO APIs supplement the I/O facilities in the
 * java.io package.
 * </p>
 * 
 * <p>
 * The NIO APIs include the following features:
 * </p>
 * 
 * <ol>
 * <li>Buffers for data of primitive types</li>
 * <li>Character-set encoders and decoders</li>
 * <li>A pattern-matching facility based on Perl-style regular expressions</li>
 * <li>Channels, a new primitive I/O abstraction</li>
 * <li>A file interface that supports locks and memory mapping</li>
 * <li>A multiplexed, non-blocking I/O facility for writing scalable servers</li>
 * </ol>
 * </blockquote>
 * 
 * <p>
 * As creme de la creme with regard to performance,you could use NIO {@link java.nio.channels.Channels} and {@link java.nio.ByteBuffer}.
 * </p>
 *
 * @param bufferLength
 *            the buffer length
 * @param inputStream
 *            the input stream
 * @param outputStream
 *            the output stream
 * @since 1.0.8
 * @since jdk1.4
 */
private static void writeUseNIO(int bufferLength, InputStream inputStream, OutputStream outputStream) {
    Date beginDate = new Date();
    ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
    WritableByteChannel writableByteChannel = Channels.newChannel(outputStream);
    ByteBuffer byteBuffer = ByteBuffer.allocate(bufferLength);

    try {
        int loopCount = 0;
        int sumSize = 0;
        while (readableByteChannel.read(byteBuffer) != -1) {
            byteBuffer.flip();
            sumSize += writableByteChannel.write(byteBuffer);
            byteBuffer.clear();
            loopCount++;
        }
        if (LOGGER.isDebugEnabled()) {
            String formatSize = FileUtil.formatSize(sumSize);
            String time = DateExtensionUtil.getIntervalForView(beginDate, new Date());
            LOGGER.debug("Write data over,sumSize:[{}],bufferLength:[{}],loopCount:[{}],time:{}", formatSize,
                    bufferLength, loopCount, time);
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(writableByteChannel);
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(readableByteChannel);
    }
}

From source file:com.feilong.commons.core.io.IOWriteUtil.java

/**
 * NIO API ?? ()./*w w w  . j  a va2  s. c  om*/
 *
 * @param bufferLength
 *            the buffer length
 * @param inputStream
 *            the input stream
 * @param outputStream
 *            the output stream
 * @throws UncheckedIOException
 *             the unchecked io exception
 * @since 1.0.8
 */
private static void writeUseNIO(int bufferLength, InputStream inputStream, OutputStream outputStream)
        throws UncheckedIOException {
    int i = 0;
    int sumSize = 0;
    int j = 0;

    ///2 
    //As creme de la creme with regard to performance, you could use NIO Channels and ByteBuffer. 

    ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
    WritableByteChannel writableByteChannel = Channels.newChannel(outputStream);

    ByteBuffer byteBuffer = ByteBuffer.allocate(bufferLength);

    try {
        while (readableByteChannel.read(byteBuffer) != -1) {
            byteBuffer.flip();
            j = writableByteChannel.write(byteBuffer);
            sumSize += j;
            byteBuffer.clear();
            i++;
        }

        if (log.isDebugEnabled()) {
            log.debug("Write data over,sumSize:[{}],bufferLength:[{}],loopCount:[{}]",
                    FileUtil.formatSize(sumSize), bufferLength, i);
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        try {
            if (writableByteChannel != null) {
                outputStream.close();
                writableByteChannel.close();
            }
            if (readableByteChannel != null) {
                inputStream.close();
                readableByteChannel.close();
            }
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}

From source file:com.flexive.shared.FxFileUtils.java

/**
 * Copy data from source to destination nio channel
 *
 * @param source      source channel//from w w w . ja  va  2  s.c o m
 * @param destination destination channel
 * @return total number of bytes copied
 * @throws java.io.IOException on errors
 */
public static long copyNIOChannel(ReadableByteChannel source, WritableByteChannel destination)
        throws IOException {
    ByteBuffer xferBuffer = ByteBuffer.allocateDirect(4096);
    long count = 0, read, written;
    while (true) {
        read = source.read(xferBuffer);
        if (read < 0)
            return count;
        xferBuffer.flip();
        written = destination.write(xferBuffer);
        if (written > 0) {
            count += written;
            if (xferBuffer.hasRemaining())
                xferBuffer.compact();
            else
                xferBuffer.clear();
        } else {
            while (xferBuffer.hasRemaining()) {
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    LOG.warn(e);
                }
                written = destination.write(xferBuffer);
                if (written > 0) {
                    count += written;
                    if (xferBuffer.hasRemaining())
                        xferBuffer.compact();
                }
            }
            if (!xferBuffer.hasRemaining())
                xferBuffer.clear();
        }
    }
}

From source file:cn.tc.ulife.platform.msg.http.util.HttpUtil.java

/**
 * ??//from   w  w  w  .j  a  v a  2  s . c om
 *
 * @param is
 * @return
 * @throws IOException
 */
public static String readStreamAsStr(InputStream is) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    WritableByteChannel dest = Channels.newChannel(bos);
    ReadableByteChannel src = Channels.newChannel(is);
    ByteBuffer bb = ByteBuffer.allocate(4096);

    while (src.read(bb) != -1) {
        bb.flip();
        dest.write(bb);
        bb.clear();
    }
    src.close();
    dest.close();

    return new String(bos.toByteArray(), Constants.ENCODING);
}

From source file:com.glaf.core.util.FileUtils.java

public static byte[] getBytes(InputStream inputStream) {
    if (inputStream == null) {
        return null;
    }// w w  w.  ja  va  2  s.  c  o  m
    ByteArrayOutputStream output = null;
    try {
        ByteBuffer buffer = ByteBuffer.allocate(8192);
        ReadableByteChannel readChannel = Channels.newChannel(inputStream);
        output = new ByteArrayOutputStream(32 * 1024);
        WritableByteChannel writeChannel = Channels.newChannel(output);
        while ((readChannel.read(buffer)) > 0 || buffer.position() != 0) {
            buffer.flip();
            writeChannel.write(buffer);
            buffer.compact();
        }
        return output.toByteArray();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        if (output != null) {
            try {
                output.close();
                output = null;
            } catch (IOException ex) {
            }
        }
    }
}