Example usage for java.nio ByteBuffer flip

List of usage examples for java.nio ByteBuffer flip

Introduction

In this page you can find the example usage for java.nio ByteBuffer flip.

Prototype

public final Buffer flip() 

Source Link

Document

Flips this buffer.

Usage

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

/**
 * NIO API ?? ()./*from  w ww . j  a v  a 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 ?? ()./*  ww  w  . j av  a  2 s.c  o m*/
 *
 * @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.chicm.cmraft.rpc.PacketUtils.java

public static RpcCall parseRpcRequestFromChannel(AsynchronousSocketChannel channel, BlockingService service)
        throws InterruptedException, ExecutionException, IOException {
    RpcCall call = null;//w  w w .j  a va 2  s.  c  om
    long t = System.currentTimeMillis();
    InputStream in = Channels.newInputStream(channel);
    byte[] datasize = new byte[MESSAGE_LENGHT_FIELD_SIZE];
    in.read(datasize);
    int nDataSize = bytes2Int(datasize);

    int len = 0;
    ByteBuffer buf = ByteBuffer.allocateDirect(nDataSize);
    for (; len < nDataSize;) {
        len += channel.read(buf).get();
    }
    if (len < nDataSize) {
        LOG.error("SOCKET READ FAILED, len:" + len);
        return call;
    }
    byte[] data = new byte[nDataSize];
    buf.flip();
    buf.get(data);
    int offset = 0;
    CodedInputStream cis = CodedInputStream.newInstance(data, offset, nDataSize - offset);
    int headerSize = cis.readRawVarint32();
    offset += cis.getTotalBytesRead();
    RequestHeader header = RequestHeader.newBuilder().mergeFrom(data, offset, headerSize).build();

    offset += headerSize;
    cis.skipRawBytes(headerSize);
    cis.resetSizeCounter();
    int bodySize = cis.readRawVarint32();
    offset += cis.getTotalBytesRead();
    //LOG.debug("header parsed:" + header.toString());

    MethodDescriptor md = service.getDescriptorForType().findMethodByName(header.getRequestName());
    Builder builder = service.getRequestPrototype(md).newBuilderForType();
    Message body = null;
    if (builder != null) {
        body = builder.mergeFrom(data, offset, bodySize).build();
        //LOG.debug("server : request parsed:" + body.toString());
    }
    call = new RpcCall(header.getId(), header, body, md);
    if (LOG.isTraceEnabled()) {
        LOG.trace("Parse Rpc request from socket: " + call.getCallId() + ", takes"
                + (System.currentTimeMillis() - t) + " ms");
    }

    return call;
}

From source file:com.chicm.cmraft.rpc.PacketUtils.java

public static RpcCall parseRpcResponseFromChannel(AsynchronousSocketChannel channel, BlockingService service)
        throws InterruptedException, ExecutionException, IOException {
    RpcCall call = null;/*from  w w w  .  j  a va  2  s . c o m*/
    long t = System.currentTimeMillis();
    InputStream in = Channels.newInputStream(channel);
    byte[] datasize = new byte[MESSAGE_LENGHT_FIELD_SIZE];
    in.read(datasize);
    int nDataSize = bytes2Int(datasize);

    LOG.debug("message size: " + nDataSize);

    int len = 0;
    ByteBuffer buf = ByteBuffer.allocateDirect(nDataSize);
    for (; len < nDataSize;) {
        len += channel.read(buf).get();
    }
    if (len < nDataSize) {
        LOG.error("SOCKET READ FAILED, len:" + len);
        return call;
    }
    byte[] data = new byte[nDataSize];
    buf.flip();
    buf.get(data);
    int offset = 0;
    CodedInputStream cis = CodedInputStream.newInstance(data, offset, nDataSize - offset);
    int headerSize = cis.readRawVarint32();
    offset += cis.getTotalBytesRead();
    ResponseHeader header = ResponseHeader.newBuilder().mergeFrom(data, offset, headerSize).build();

    offset += headerSize;
    cis.skipRawBytes(headerSize);
    cis.resetSizeCounter();
    int bodySize = cis.readRawVarint32();
    offset += cis.getTotalBytesRead();

    MethodDescriptor md = service.getDescriptorForType().findMethodByName(header.getResponseName());
    Builder builder = service.getResponsePrototype(md).newBuilderForType();
    Message body = null;
    if (builder != null) {
        body = builder.mergeFrom(data, offset, bodySize).build();
    }
    call = new RpcCall(header.getId(), header, body, md);
    if (LOG.isTraceEnabled()) {
        LOG.trace("Parse Rpc response from socket: " + call.getCallId() + ", takes"
                + (System.currentTimeMillis() - t) + " ms");
    }

    return call;
}

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

/**
 * Copy data from source to destination nio channel
 *
 * @param source      source channel//from  w  w w . j  av  a2  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  ww w . j av  a  2s.  c o m*/
 *
 * @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:org.apache.cassandra.db.index.sasi.disk.TokenTreeTest.java

private static DecoratedKey dk(Long token) {
    ByteBuffer buf = ByteBuffer.allocate(8);
    buf.putLong(token);/*w  w w.j  av  a2s  .c o  m*/
    buf.flip();
    Long hashed = MurmurHash.hash2_64(buf, buf.position(), buf.remaining(), 0);
    return new DecoratedKey(new LongToken(hashed), buf);
}

From source file:org.apache.xmlgraphics.util.io.Base64Test.java

/**
 * Returns true if the contents of <tt>is1</tt> match the contents of
 * <tt>is2</tt>/*from  www  .  ja  va  2  s .  c o  m*/
 *
 * @throws IOException
 */
public static boolean compareStreams(final InputStream i1, final InputStream i2, final boolean skipws)
        throws IOException {
    try (final ReadableByteChannel ch1 = Channels.newChannel(i1)) {
        try (final ReadableByteChannel ch2 = Channels.newChannel(i2)) {

            final ByteBuffer buf1 = ByteBuffer.allocateDirect(1024);
            final ByteBuffer buf2 = ByteBuffer.allocateDirect(1024);

            while (true) {

                final int n1 = ch1.read(buf1);
                final int n2 = ch2.read(buf2);

                if (n1 == -1 || n2 == -1) {
                    return n1 == n2;
                }

                buf1.flip();
                buf2.flip();

                for (int i = 0; i < Math.min(n1, n2); ++i) {
                    if (buf1.get() != buf2.get()) {
                        return false;
                    }
                }

                buf1.compact();
                buf2.compact();
            }
        }
    }
}

From source file:com.gamesalutes.utils.ByteUtils.java

/**
 * Returns a <code>ByteBuffer</code> containing the byte representation
 * of the serializable object <code>obj</code>.
 * // w ww .j a va2 s . c  om
 * @param obj the <code>Object</code> to convert to its byte representation
 * @param buf an existing buffer to use for storage or <code>null</code> to create new buffer.
 *        If <code>buf</code> is not large enough it will be expanded using {@link #growBuffer(ByteBuffer, int)}
 * @return <code>ByteBuffer</code> containing the byte representation
 * of <code>obj</code>.
 * 
 * @throws IOException if <code>obj</code> is not serializable or error occurs while writing the bytes
 */
public static ByteBuffer getObjectBytes(Object obj, ByteBuffer buf) throws IOException {
    if (buf == null)
        buf = ByteBuffer.allocate(READ_BUFFER_SIZE);

    // note the input position
    int startPos = buf.position();
    ByteBufferChannel channel = new ByteBufferChannel(buf);
    ObjectOutputStream out = null;
    try {
        out = new ObjectOutputStream(Channels.newOutputStream(channel));
        out.writeObject(obj);
        out.flush();
    } finally {
        MiscUtils.closeStream(out);
    }

    ByteBuffer returnBuf = channel.getByteBuffer();
    returnBuf.flip();
    // reset starting position to be that of input buffer
    returnBuf.position(startPos);
    return returnBuf;
}

From source file:it.geosolutions.tools.io.file.IOUtils.java

/**
 * Copies the content of the source channel onto the destination channel.
 * /*from   w w w. java 2s . c  o m*/
 * @param bufferSize
 *            size of the temp buffer to use for this copy.
 * @param source
 *            the source {@link ReadableByteChannel}.
 * @param destination
 *            the destination {@link WritableByteChannel};.
 * @throws IOException
 *             in case something bad happens.
 */
public static void copyChannel(int bufferSize, ReadableByteChannel source, WritableByteChannel destination)
        throws IOException {

    Objects.notNull(source, destination);
    if (!source.isOpen() || !destination.isOpen())
        throw new IllegalStateException("Source and destination channels must be open.");

    final java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocateDirect(bufferSize);
    while (source.read(buffer) != -1) {
        // prepare the buffer for draining
        buffer.flip();

        // write to destination
        while (buffer.hasRemaining())
            destination.write(buffer);

        // clear
        buffer.clear();

    }

}