Java Code Examples for java.nio.ByteBuffer.compact()

The following are Jave code examples for showing how to use compact() of the java.nio.ByteBuffer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: outcomes   File: Main.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws IOException {

        RandomAccessFile file = new RandomAccessFile(FILE_PATH, "rw");

        FileChannel channel = file.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(48);

        int read = channel.read(byteBuffer);
        while (read != -1) {
            byteBuffer.flip();

            while (byteBuffer.hasRemaining()) {
                System.out.print((char)byteBuffer.get());
            }

            byteBuffer.compact();
            read = channel.read(byteBuffer);
        }
        file.close();
    }
 
Example 2
Project: LuaViewPlayground   File: ChannelTools.java   View Source Code Vote up 6 votes
/**
     * copy
     *
     * @param src
     * @param dest
     * @throws IOException
     */
    public static void fastCopy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException {
        final ByteBuffer buffer = ByteBuffer.allocateDirect(8 * 1024);
        int count = 0;

        while ((count = src.read(buffer)) != -1) {
//            LogUtil.d("luaviewp-fastCopy", count, buffer.capacity(), buffer.remaining(), buffer.array().length);
            // prepare the buffer to be drained
            buffer.flip();
            // write to the channel, may block
            dest.write(buffer);
            // If partial transfer, shift remainder down
            // If buffer is empty, same as doing clear()
            buffer.compact();
        }
        // EOF will leave buffer in fill state
        buffer.flip();
        // make sure the buffer is fully drained.
        while (buffer.hasRemaining()) {
            dest.write(buffer);
        }
    }
 
Example 3
Project: alfresco-repository   File: HttpClientTransmitterImpl.java   View Source Code Vote up 6 votes
private static void channelCopy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException
{
    final ByteBuffer buffer = ByteBuffer.allocateDirect(2 * 1024);
    while (src.read(buffer) != -1)
    {
        // prepare the buffer to be drained
        buffer.flip();
        // write to the channel, may block
         dest.write(buffer);

        // If partial transfer, shift remainder down
        // If buffer is empty, same as doing clear()
        buffer.compact();
    }

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

    // make sure the buffer is fully drained.
    while (buffer.hasRemaining())
    {
        dest.write(buffer);
    }
}
 
Example 4
Project: MetadataEditor   File: WavTagWriter.java   View Source Code Vote up 6 votes
/**
 * Delete Tag Chunk
 * <p/>
 * Can be used when chunk is not the last chunk
 * <p/>
 * Continually copy a 4mb chunk, write the chunk and repeat until the rest of the file after the tag
 * is rewritten
 *
 * @param fc
 * @param endOfExistingChunk
 * @param lengthTagChunk
 * @throws IOException
 */
private void deleteTagChunk(final FileChannel fc, int endOfExistingChunk, final int lengthTagChunk) throws IOException {
    //Position for reading after the tag
    fc.position(endOfExistingChunk);

    final ByteBuffer buffer = ByteBuffer.allocate((int) TagOptionSingleton.getInstance().getWriteChunkSize());
    while (fc.read(buffer) >= 0 || buffer.position() != 0) {
        buffer.flip();
        final long readPosition = fc.position();
        fc.position(readPosition - lengthTagChunk - buffer.limit());
        fc.write(buffer);
        fc.position(readPosition);
        buffer.compact();
    }
    //Truncate the file after the last chunk
    final long newLength = fc.size() - lengthTagChunk;
    logger.config(loggingName + " Setting new length to:" + newLength);
    fc.truncate(newLength);
}
 
Example 5
Project: openjdk-jdk10   File: AsyncSSLDelegate.java   View Source Code Vote up 6 votes
ByteBufferReference shift(ByteBufferReference ref1, ByteBufferReference ref2) {
    ByteBuffer buf1 = ref1.get();
    if (buf1.capacity() < engine.getSession().getPacketBufferSize()) {
        ByteBufferReference newRef = getNetBuffer();
        ByteBuffer newBuf = newRef.get();
        newBuf.put(buf1);
        buf1 = newBuf;
        ref1.clear();
        ref1 = newRef;
    } else {
        buf1.compact();
    }
    ByteBuffer buf2 = ref2.get();
    Utils.copy(buf2, buf1, Math.min(buf1.remaining(), buf2.remaining()));
    buf1.flip();
    return ref1;
}
 
Example 6
Project: openjdk-jdk10   File: AsyncSSLDelegate.java   View Source Code Vote up 6 votes
ByteBufferReference combine(ByteBufferReference ref1, ByteBufferReference ref2) {
    ByteBuffer buf1 = ref1.get();
    ByteBuffer buf2 = ref2.get();
    int avail1 = buf1.capacity() - buf1.remaining();
    if (buf2.remaining() < avail1) {
        buf1.compact();
        buf1.put(buf2);
        buf1.flip();
        ref2.clear();
        return ref1;
    }
    int newsize = buf1.remaining() + buf2.remaining();
    ByteBuffer newbuf = ByteBuffer.allocate(newsize); // getting rid of buffer pools
    newbuf.put(buf1);
    newbuf.put(buf2);
    newbuf.flip();
    ref1.clear();
    ref2.clear();
    return ByteBufferReference.of(newbuf);
}
 
Example 7
Project: ModLoaderInstaller   File: FileUtils.java   View Source Code Vote up 5 votes
public static void xorFiles(SeekableByteChannel inputA, SeekableByteChannel inputB,
                            SeekableByteChannel outputChannel, long limit) throws IOException {
	ByteBuffer aBuffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
	ByteBuffer bBuffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
	ByteBuffer outBuffer = ByteBuffer.allocateDirect(BUFFER_SIZE);

	do {
		if (inputA.position() == inputA.size()) inputA.position(0);
		if (inputB.position() == inputB.size()) inputB.position(0);

		inputA.read(aBuffer);
		inputB.read(bBuffer);
		aBuffer.flip();
		bBuffer.flip();
		int cap = min(aBuffer.remaining(), bBuffer.remaining(), outBuffer.remaining());
		for (int i = 0; i < cap; i += 8) {
			long a = aBuffer.getLong();
			long b = bBuffer.getLong();
			outBuffer.putLong(a ^ b);
		}
		aBuffer.compact();
		bBuffer.compact();

		outBuffer.flip();
		long bytesRequired = limit - outputChannel.size();
		if (outBuffer.limit() > bytesRequired) outBuffer.limit((int) bytesRequired);
		outputChannel.write(outBuffer);
		outBuffer.compact();
	} while (outputChannel.size() < limit);
}
 
Example 8
Project: mycat-src-1.6.1-RELEASE   File: AbstractConnection.java   View Source Code Vote up 5 votes
private ByteBuffer compactReadBuffer(ByteBuffer buffer, int offset) {
	if(buffer == null) {
		return null;
	}
	buffer.limit(buffer.position());
	buffer.position(offset);
	buffer = buffer.compact();
	readBufferOffset = 0;
	return buffer;
}
 
Example 9
Project: dble   File: AIOSocketWR.java   View Source Code Vote up 5 votes
/**
 * return true ,means no more data
 *
 * @return
 */
private boolean write0() {
    if (!writing.compareAndSet(false, true)) {
        return false;
    }
    ByteBuffer theBuffer = con.writeBuffer;
    if (theBuffer == null || !theBuffer.hasRemaining()) { // writeFinished,if buffer not NULL,recycle
        if (theBuffer != null) {
            con.recycle(theBuffer);
            con.writeBuffer = null;

        }
        // poll again
        ByteBuffer buffer = con.writeQueue.poll();
        // more data
        if (buffer != null) {
            if (buffer.limit() == 0) {
                con.recycle(buffer);
                con.writeBuffer = null;
                con.close("quit cmd");
                writing.set(false);
                return true;
            } else {
                con.writeBuffer = buffer;
                asyncWrite(buffer);
                return false;
            }
        } else {
            // no buffer
            writing.set(false);
            return true;
        }
    } else {
        theBuffer.compact();
        asyncWrite(theBuffer);
        return false;
    }

}
 
Example 10
Project: DreamSocket   File: MessageDecode.java   View Source Code Vote up 5 votes
public final void decode(SocketAddress address, byte[] array, int offset, int length) {
    ByteBuffer buffer = mAddressByteBufferMap.get(address);
    if (buffer == null) {
        buffer = ByteBuffer.allocate(CACHE_BUFFER_LENGTH);
        mAddressByteBufferMap.put(address, buffer);
        buffer.flip();
        LoggerFactory.getLogger().info("创建 " + address.toString() + " 数据缓冲区ByteBuffer");
    }
    LoggerFactory.getLogger().info(String.format("%s 上次未解码 position=%d limit=%d", address.toString(), buffer.position(), buffer.limit()));
    if (buffer.limit() + length > buffer.capacity()) {
        LoggerFactory.getLogger().warn(address.toString() + " -> decode缓存区已满,读取的数据被丢弃!!!!!");
        return;
    }
    buffer.compact();
    buffer.put(array, offset, length);
    buffer.flip();
    buffer.mark();
    LoggerFactory.getLogger().info(String.format("%s 合并未解码 position=%d limit=%d", address.toString(), buffer.position(), buffer.limit()));
    LoggerFactory.getLogger().info(address.toString() + " 开始解码数据");
    while (buffer.hasRemaining() && (decode(address, buffer) != null)) {
        LoggerFactory.getLogger().info(address.toString() + " 成功解码一条数据");
        buffer.compact();
        buffer.flip();
        buffer.mark();
    }
    LoggerFactory.getLogger().info(address.toString() + " 退出解码");
    buffer.reset();
    LoggerFactory.getLogger().info(String.format("%s 未解码数据 position=%d limit=%d", address.toString(), buffer.position(), buffer.limit()));
}
 
Example 11
Project: lams   File: HttpServerConnection.java   View Source Code Vote up 5 votes
/**
 * Pushes back the given data. This should only be used by transfer coding handlers that have read past
 * the end of the request when handling pipelined requests
 *
 * @param unget The buffer to push back
 */
public void ungetRequestBytes(final Pooled<ByteBuffer> unget) {
    if (getExtraBytes() == null) {
        setExtraBytes(unget);
    } else {
        Pooled<ByteBuffer> eb = getExtraBytes();
        ByteBuffer buf = eb.getResource();
        final ByteBuffer ugBuffer = unget.getResource();

        if (ugBuffer.limit() - ugBuffer.remaining() > buf.remaining()) {
            //stuff the existing data after the data we are ungetting
            ugBuffer.compact();
            ugBuffer.put(buf);
            ugBuffer.flip();
            eb.free();
            setExtraBytes(unget);
        } else {
            //TODO: this is horrible, but should not happen often
            final byte[] data = new byte[ugBuffer.remaining() + buf.remaining()];
            int first = ugBuffer.remaining();
            ugBuffer.get(data, 0, ugBuffer.remaining());
            buf.get(data, first, buf.remaining());
            eb.free();
            unget.free();
            final ByteBuffer newBuffer = ByteBuffer.wrap(data);
            setExtraBytes(new ImmediatePooled<>(newBuffer));
        }
    }
}
 
Example 12
Project: lams   File: BufferedTextMessage.java   View Source Code Vote up 5 votes
public void readBlocking(StreamSourceFrameChannel channel) throws IOException {
    Pooled<ByteBuffer> pooled = channel.getWebSocketChannel().getBufferPool().allocate();
    final ByteBuffer buffer = pooled.getResource();
    try {
        for (; ; ) {
            int res = channel.read(buffer);
            if (res == -1) {
                buffer.flip();
                data.write(buffer);
                this.complete = true;
                return;
            } else if (res == 0) {
                channel.awaitReadable();
            }
            checkMaxSize(channel, res);
            if (!buffer.hasRemaining()) {
                buffer.flip();
                data.write(buffer);
                buffer.compact();
                if (!bufferFullMessage) {
                    //if we are not reading the full message we return
                    return;
                }
            }
        }
    } finally {
        pooled.free();
    }
}
 
Example 13
Project: spark_deep   File: NioServer.java   View Source Code Vote up 5 votes
public static void handleWrite(SelectionKey key) throws IOException {
	ByteBuffer buf = (ByteBuffer) key.attachment();
	buf.flip();
	SocketChannel sc = (SocketChannel) key.channel();
	while (buf.hasRemaining()) {
		sc.write(buf);
	}
	buf.compact();
}
 
Example 14
Project: xtf   File: IOUtils.java   View Source Code Vote up 5 votes
public static void copy(ReadableByteChannel src, WritableByteChannel dest) throws IOException {
	final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);

	while (src.read(buffer) != -1) {
		buffer.flip();
		dest.write(buffer);
		buffer.compact();
	}
	buffer.flip();
	dest.write(buffer);
}
 
Example 15
Project: gemoc-studio   File: IFileUtils.java   View Source Code Vote up 5 votes
private static boolean isStreamEqual(InputStream i1, InputStream i2)
        throws IOException {

    ReadableByteChannel ch1 = Channels.newChannel(i1);
    ReadableByteChannel ch2 = Channels.newChannel(i2);

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

    try {
        while (true) {

            int n1 = ch1.read(buf1);
            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();
        }

    } finally {
        if (i1 != null) i1.close();
        if (i2 != null) i2.close();
    }
}
 
Example 16
Project: dble   File: AbstractConnection.java   View Source Code Vote up 5 votes
private ByteBuffer compactReadBuffer(ByteBuffer buffer, int offset) {
    if (buffer == null) {
        return null;
    }
    buffer.limit(buffer.position());
    buffer.position(offset);
    buffer = buffer.compact();
    readBufferOffset = 0;
    return buffer;
}
 
Example 17
Project: L2jBrasil   File: SelectorThread.java   View Source Code Vote up 4 votes
private final void readPacket(final SelectionKey key, final MMOConnection<T> con)
{
    if (!con.isClosed())
    {
        ByteBuffer buf;
        if ((buf = con.getReadBuffer()) == null)
            buf = READ_BUFFER;

        // if we try to to do a read with no space in the buffer it will
        // read 0 bytes
        // going into infinite loop
        if (buf.position() == buf.limit())
            System.exit(0);

        int result = -2;

        try
        {
            result = con.read(buf);
        }
        catch (IOException e)
        {
            // error handling goes bellow
        }

        if (result > 0)
        {
            buf.flip();

            final T client = con.getClient();

            for (int i = 0; i < MAX_READ_PER_PASS; i++)
                if (!tryReadPacket(key, client, buf, con))
                    return;

            // only reachable if MAX_READ_PER_PASS has been reached
            // check if there are some more bytes in buffer
            // and allocate/compact to prevent content lose.
            if (buf.remaining() > 0)
            {
                // did we use the READ_BUFFER ?
                if (buf == READ_BUFFER)
                    // move the pending byte to the connections READ_BUFFER
                    allocateReadBuffer(con);
                else
                    // move the first byte to the beginning :)
                    buf.compact();
            }
        }
        else
        {
            switch (result)
            {
                case 0:
                case -1:
                    closeConnectionImpl(key, con);
                    break;
                case -2:
                    con.getClient().onForcedDisconnection();
                    closeConnectionImpl(key, con);
                    break;
            }
        }
    }
}
 
Example 18
Project: L2J-Global   File: SelectorThread.java   View Source Code Vote up 4 votes
private final void readPacket(SelectionKey key, MMOConnection<T> con)
{
	if (con.isClosed())
	{
		return;
	}
	ByteBuffer buf = con.getReadBuffer();
	if (buf == null)
	{
		buf = READ_BUFFER;
	}
	
	// if we try to to do a read with no space in the buffer it will read 0 bytes going into infinite loop
	if (buf.position() == buf.limit())
	{
		System.exit(0);
	}
	
	int result = -2;
	
	try
	{
		result = con.read(buf);
	}
	catch (IOException e)
	{
		// error handling goes bellow
	}
	
	if (result > 0)
	{
		buf.flip();
		
		final T client = con.getClient();
		
		for (int i = 0; i < MAX_READ_PER_PASS; i++)
		{
			if (!tryReadPacket(key, client, buf, con))
			{
				return;
			}
		}
		
		// only reachable if MAX_READ_PER_PASS has been reached
		// check if there are some more bytes in buffer
		// and allocate/compact to prevent content lose.
		if (buf.remaining() > 0)
		{
			// did we use the READ_BUFFER ?
			if (buf == READ_BUFFER)
			{
				// move the pending byte to the connections READ_BUFFER
				allocateReadBuffer(con);
			}
			else
			{
				// move the first byte to the beginning :)
				buf.compact();
			}
		}
	}
	else
	{
		switch (result)
		{
			case 0:
			case -1:
			{
				closeConnectionImpl(key, con);
				break;
			}
			case -2:
			{
				con.getClient().onForcedDisconnection();
				closeConnectionImpl(key, con);
				break;
			}
		}
	}
}
 
Example 19
Project: L2J-Global   File: SelectorThread.java   View Source Code Vote up 4 votes
private final boolean tryReadPacket(SelectionKey key, T client, ByteBuffer buf, MMOConnection<T> con)
{
	switch (buf.remaining())
	{
		case 0:
		{
			// buffer is full nothing to read
			return false;
		}
		case 1:
		{
			// we don`t have enough data for header so we need to read
			key.interestOps(key.interestOps() | SelectionKey.OP_READ);
			
			// did we use the READ_BUFFER ?
			if (buf == READ_BUFFER)
			{
				// move the pending byte to the connections READ_BUFFER
				allocateReadBuffer(con);
			}
			else
			{
				// move the first byte to the beginning :)
				buf.compact();
			}
			return false;
		}
		default:
		{
			// data size excluding header size :>
			final int dataPending = (buf.getShort() & 0xFFFF) - HEADER_SIZE;
			
			// do we got enough bytes for the packet?
			if (dataPending <= buf.remaining())
			{
				// avoid parsing dummy packets (packets without body)
				if (dataPending > 0)
				{
					final int pos = buf.position();
					parseClientPacket(pos, buf, dataPending, client);
					buf.position(pos + dataPending);
				}
				
				if (buf.hasRemaining())
				{
					return true;
				}
				if (buf != READ_BUFFER)
				{
					con.setReadBuffer(null);
					recycleBuffer(buf);
				}
				else
				{
					READ_BUFFER.clear();
				}
				return false;
			}
			
			// we don`t have enough bytes for the dataPacket so we need to read
			key.interestOps(key.interestOps() | SelectionKey.OP_READ);
			
			// move it`s position
			buf.position(buf.position() - HEADER_SIZE);
			// did we use the READ_BUFFER ?
			if (buf == READ_BUFFER)
			{
				// move the pending byte to the connections READ_BUFFER
				allocateReadBuffer(con);
			}
			else
			{
				buf.compact();
			}
			return false;
		}
	}
}
 
Example 20
Project: xiongzhenggang.github.io   File: TestServiceNio.java   View Source Code Vote up 4 votes
public static void handleWrite(SelectionKey key) throws IOException{//准备写

        ByteBuffer buf = (ByteBuffer)key.attachment();

        buf.flip();

        SocketChannel sc = (SocketChannel) key.channel();

        while(buf.hasRemaining()){

            sc.write(buf);

        }

        buf.compact();

    }