Java Code Examples for org.jboss.netty.buffer.ChannelBuffer#capacity()
The following examples show how to use
org.jboss.netty.buffer.ChannelBuffer#capacity() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MemcachedBinaryResponseEncoder.java From fqueue with Apache License 2.0 | 6 votes |
public ChannelBuffer constructHeader(MemcachedBinaryCommandDecoder.BinaryCommand bcmd, ChannelBuffer extrasBuffer, ChannelBuffer keyBuffer, ChannelBuffer valueBuffer, short responseCode, int opaqueValue, long casUnique) { // take the ResponseMessage and turn it into a binary payload. ChannelBuffer header = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 24); header.writeByte((byte)0x81); // magic header.writeByte(bcmd.code); // opcode short keyLength = (short) (keyBuffer != null ? keyBuffer.capacity() :0); header.writeShort(keyLength); int extrasLength = extrasBuffer != null ? extrasBuffer.capacity() : 0; header.writeByte((byte) extrasLength); // extra length = flags + expiry header.writeByte((byte)0); // data type unused header.writeShort(responseCode); // status code int dataLength = valueBuffer != null ? valueBuffer.capacity() : 0; header.writeInt(dataLength + keyLength + extrasLength); // data length header.writeInt(opaqueValue); // opaque header.writeLong(casUnique); return header; }
Example 2
Source File: MemcachedBinaryResponseEncoder.java From fqueue with Apache License 2.0 | 6 votes |
public ChannelBuffer constructHeader(MemcachedBinaryCommandDecoder.BinaryCommand bcmd, ChannelBuffer extrasBuffer, ChannelBuffer keyBuffer, ChannelBuffer valueBuffer, short responseCode, int opaqueValue, long casUnique) { // take the ResponseMessage and turn it into a binary payload. ChannelBuffer header = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 24); header.writeByte((byte)0x81); // magic header.writeByte(bcmd.code); // opcode short keyLength = (short) (keyBuffer != null ? keyBuffer.capacity() :0); header.writeShort(keyLength); int extrasLength = extrasBuffer != null ? extrasBuffer.capacity() : 0; header.writeByte((byte) extrasLength); // extra length = flags + expiry header.writeByte((byte)0); // data type unused header.writeShort(responseCode); // status code int dataLength = valueBuffer != null ? valueBuffer.capacity() : 0; header.writeInt(dataLength + keyLength + extrasLength); // data length header.writeInt(opaqueValue); // opaque header.writeLong(casUnique); return header; }
Example 3
Source File: CompositeChannelBuffer.java From simple-netty-source with Apache License 2.0 | 6 votes |
public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { if (index > capacity() - length || dstIndex > dst.capacity() - length) { throw new IndexOutOfBoundsException("Too many bytes to be read - Needs " + (index + length) + " or " + (dstIndex + length) + ", maximum is " + capacity() + " or " + dst.capacity()); } if (index < 0) { throw new IndexOutOfBoundsException("Index must be >= 0"); } if (length == 0) { return; } int i = componentId(index); while (length > 0) { ChannelBuffer s = components[i]; int adjustment = indices[i]; int localLength = Math.min(length, s.capacity() - (index - adjustment)); s.getBytes(index - adjustment, dst, dstIndex, localLength); index += localLength; dstIndex += localLength; length -= localLength; i ++; } }
Example 4
Source File: CompositeChannelBuffer.java From simple-netty-source with Apache License 2.0 | 6 votes |
public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { int componentId = componentId(index); if (index > capacity() - length || srcIndex > src.capacity() - length) { throw new IndexOutOfBoundsException("Too many bytes to be written - Needs " + (index + length) + " or " + (srcIndex + length) + ", maximum is " + capacity() + " or " + src.capacity()); } int i = componentId; while (length > 0) { ChannelBuffer s = components[i]; int adjustment = indices[i]; int localLength = Math.min(length, s.capacity() - (index - adjustment)); s.setBytes(index - adjustment, src, srcIndex, localLength); index += localLength; srcIndex += localLength; length -= localLength; i ++; } }
Example 5
Source File: SlicedChannelBuffer.java From simple-netty-source with Apache License 2.0 | 6 votes |
public SlicedChannelBuffer(ChannelBuffer buffer, int index, int length) { if (index < 0 || index > buffer.capacity()) { throw new IndexOutOfBoundsException("Invalid index of " + index + ", maximum is " + buffer.capacity()); } if (index + length > buffer.capacity()) { throw new IndexOutOfBoundsException("Invalid combined index of " + (index + length) + ", maximum is " + buffer.capacity()); } this.buffer = buffer; adjustment = index; this.length = length; writerIndex(length); }
Example 6
Source File: RaopRtpAudioDecryptionHandler.java From Android-Airplay-Server with MIT License | 5 votes |
@Override protected synchronized Object decode(final ChannelHandlerContext ctx, final Channel channel, final Object msg) throws Exception { //check the message type if (msg instanceof RaopRtpPacket.Audio) { final RaopRtpPacket.Audio audioPacket = (RaopRtpPacket.Audio)msg; final ChannelBuffer audioPayload = audioPacket.getPayload(); /* Cipher is restarted for every packet. We simply overwrite the * encrypted data with the corresponding plain text */ aesCipher.init(Cipher.DECRYPT_MODE, m_aesKey, m_aesIv); for(int i = 0; (i + 16) <= audioPayload.capacity(); i += 16) { byte[] block = new byte[16];//buffer for decrypting the data //copy the bytes to the buffer audioPayload.getBytes(i, block); //decrypt the 16 bytes block block = aesCipher.update(block); //set it back to the channel audioPayload.setBytes(i, block); } } return msg; }
Example 7
Source File: ChannelBuffers.java From simple-netty-source with Apache License 2.0 | 5 votes |
private static int firstIndexOf(ChannelBuffer buffer, int fromIndex, int toIndex, byte value) { fromIndex = Math.max(fromIndex, 0); if (fromIndex >= toIndex || buffer.capacity() == 0) { return -1; } for (int i = fromIndex; i < toIndex; i ++) { if (buffer.getByte(i) == value) { return i; } } return -1; }
Example 8
Source File: ChannelBuffers.java From simple-netty-source with Apache License 2.0 | 5 votes |
private static int lastIndexOf(ChannelBuffer buffer, int fromIndex, int toIndex, byte value) { fromIndex = Math.min(fromIndex, buffer.capacity()); if (fromIndex < 0 || buffer.capacity() == 0) { return -1; } for (int i = fromIndex - 1; i >= toIndex; i --) { if (buffer.getByte(i) == value) { return i; } } return -1; }
Example 9
Source File: ChannelBuffers.java From simple-netty-source with Apache License 2.0 | 5 votes |
private static int firstIndexOf( ChannelBuffer buffer, int fromIndex, int toIndex, ChannelBufferIndexFinder indexFinder) { fromIndex = Math.max(fromIndex, 0); if (fromIndex >= toIndex || buffer.capacity() == 0) { return -1; } for (int i = fromIndex; i < toIndex; i ++) { if (indexFinder.find(buffer, i)) { return i; } } return -1; }
Example 10
Source File: ChannelBuffers.java From simple-netty-source with Apache License 2.0 | 5 votes |
private static int lastIndexOf( ChannelBuffer buffer, int fromIndex, int toIndex, ChannelBufferIndexFinder indexFinder) { fromIndex = Math.min(fromIndex, buffer.capacity()); if (fromIndex < 0 || buffer.capacity() == 0) { return -1; } for (int i = fromIndex - 1; i >= toIndex; i --) { if (indexFinder.find(buffer, i)) { return i; } } return -1; }
Example 11
Source File: TruncatedChannelBuffer.java From simple-netty-source with Apache License 2.0 | 5 votes |
public TruncatedChannelBuffer(ChannelBuffer buffer, int length) { if (length > buffer.capacity()) { throw new IndexOutOfBoundsException("Length is too large, got " + length + " but can't go higher than " + buffer.capacity()); } this.buffer = buffer; this.length = length; writerIndex(length); }
Example 12
Source File: FrameDecoder.java From android-netty with Apache License 2.0 | 5 votes |
protected ChannelBuffer updateCumulation(ChannelHandlerContext ctx, ChannelBuffer input) { ChannelBuffer newCumulation; int readableBytes = input.readableBytes(); if (readableBytes > 0) { int inputCapacity = input.capacity(); // If input.readableBytes() == input.capacity() (i.e. input is // full), // there's nothing to save from creating a new cumulation buffer // even if input.capacity() exceeds the threshold, because the new // cumulation // buffer will have the same capacity and content with input. if (readableBytes < inputCapacity && inputCapacity > copyThreshold) { // At least one byte was consumed by callDecode() and // input.capacity() // exceeded the threshold. cumulation = newCumulation = newCumulationBuffer(ctx, input.readableBytes()); cumulation.writeBytes(input); } else { // Nothing was consumed by callDecode() or input.capacity() did // not // exceed the threshold. if (input.readerIndex() != 0) { cumulation = newCumulation = input.slice(); } else { cumulation = newCumulation = input; } } } else { cumulation = newCumulation = null; } return newCumulation; }
Example 13
Source File: MemcachedFrameDecoder.java From fqueue with Apache License 2.0 | 4 votes |
@Override protected Object decode(ChannelHandlerContext ctx, org.jboss.netty.channel.Channel channel, ChannelBuffer buffer) throws Exception { // check the state. if we're WAITING_FOR_DATA that means instead of // breaking into lines, we need N bytes // otherwise, we're waiting for input if (status.state == SessionStatus.State.WAITING_FOR_DATA) { if (buffer.readableBytes() < status.bytesNeeded + MemcachedResponseEncoder.CRLF.capacity()) return null; // verify delimiter matches at the right location ChannelBuffer dest = buffer.slice(status.bytesNeeded + buffer.readerIndex(), 2); StatsCounter.bytes_written.addAndGet(status.bytesNeeded); if (!dest.equals(MemcachedResponseEncoder.CRLF)) { // before we throw error... we're ready for the next command status.ready(); // error, no delimiter at end of payload throw new IncorrectlyTerminatedPayloadException("payload not terminated correctly"); } else { status.processingMultiline(); // There's enough bytes in the buffer and the delimiter is at // the end. Read it. ChannelBuffer result = buffer.slice(buffer.readerIndex(), status.bytesNeeded); buffer.skipBytes(status.bytesNeeded + MemcachedResponseEncoder.CRLF.capacity()); return result; } } else { int minFrameLength = Integer.MAX_VALUE; ChannelBuffer foundDelimiter = null; // command length int frameLength = buffer.bytesBefore(buffer.readerIndex(), buffer.readableBytes(), ChannelBufferIndexFinder.CRLF); if (frameLength >= 0 && frameLength < minFrameLength && buffer.readableBytes() >= frameLength + 2) { minFrameLength = frameLength; foundDelimiter = MemcachedResponseEncoder.CRLF; } if (foundDelimiter != null) { int minDelimLength = foundDelimiter.capacity(); if (discardingTooLongFrame) { // We've just finished discarding a very large frame. // Throw an exception and go back to the initial state. long tooLongFrameLength = this.tooLongFrameLength; this.tooLongFrameLength = 0L; discardingTooLongFrame = false; buffer.skipBytes(minFrameLength + minDelimLength); fail(tooLongFrameLength + minFrameLength + minDelimLength); } if (minFrameLength > maxFrameLength) { // Discard read frame. buffer.skipBytes(minFrameLength + minDelimLength); StatsCounter.bytes_written.addAndGet(minFrameLength + minDelimLength); fail(minFrameLength); } ChannelBuffer frame = buffer.slice(buffer.readerIndex(), minFrameLength); buffer.skipBytes(minFrameLength + minDelimLength); status.processing(); StatsCounter.bytes_written.addAndGet(minFrameLength + minDelimLength); return frame; } else { if (buffer.readableBytes() > maxFrameLength) { // Discard the content of the buffer until a delimiter is // found. tooLongFrameLength = buffer.readableBytes(); buffer.skipBytes(buffer.readableBytes()); discardingTooLongFrame = true; StatsCounter.bytes_written.addAndGet(tooLongFrameLength); } return null; } } }
Example 14
Source File: MemcachedBinaryCommandDecoder.java From fqueue with Apache License 2.0 | 4 votes |
protected Object decode(ChannelHandlerContext channelHandlerContext, Channel channel, ChannelBuffer channelBuffer) throws Exception { // need at least 24 bytes, to get header if (channelBuffer.readableBytes() < 24) return null; // get the header channelBuffer.markReaderIndex(); ChannelBuffer headerBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 24); channelBuffer.readBytes(headerBuffer); short magic = headerBuffer.readUnsignedByte(); // magic should be 0x80 if (magic != 0x80) { headerBuffer.resetReaderIndex(); throw new MalformedCommandException("binary request payload is invalid, magic byte incorrect"); } short opcode = headerBuffer.readUnsignedByte(); short keyLength = headerBuffer.readShort(); short extraLength = headerBuffer.readUnsignedByte(); short dataType = headerBuffer.readUnsignedByte(); // unused short reserved = headerBuffer.readShort(); // unused int totalBodyLength = headerBuffer.readInt(); int opaque = headerBuffer.readInt(); long cas = headerBuffer.readLong(); // we want the whole of totalBodyLength; otherwise, keep waiting. if (channelBuffer.readableBytes() < totalBodyLength) { channelBuffer.resetReaderIndex(); return null; } // This assumes correct order in the enum. If that ever changes, we will have to scan for 'code' field. BinaryCommand bcmd = BinaryCommand.values()[opcode]; Command cmdType = bcmd.correspondingCommand; CommandMessage cmdMessage = CommandMessage.command(cmdType); cmdMessage.noreply = bcmd.noreply; cmdMessage.cas_key = cas; cmdMessage.opaque = opaque; cmdMessage.addKeyToResponse = bcmd.addKeyToResponse; // get extras. could be empty. ChannelBuffer extrasBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, extraLength); channelBuffer.readBytes(extrasBuffer); // get the key if any if (keyLength != 0) { ChannelBuffer keyBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, keyLength); channelBuffer.readBytes(keyBuffer); ArrayList<String> keys = new ArrayList<String>(); String key = keyBuffer.toString(USASCII); keys.add(key); // TODO this or UTF-8? ISO-8859-1? cmdMessage.keys = keys; if (cmdType == Command.ADD || cmdType == Command.SET || cmdType == Command.REPLACE || cmdType == Command.APPEND || cmdType == Command.PREPEND) { // TODO these are backwards from the spec, but seem to be what spymemcached demands -- which has the mistake?! short expire = (short) (extrasBuffer.capacity() != 0 ? extrasBuffer.readUnsignedShort() : 0); short flags = (short) (extrasBuffer.capacity() != 0 ? extrasBuffer.readUnsignedShort() : 0); // the remainder of the message -- that is, totalLength - (keyLength + extraLength) should be the payload int size = totalBodyLength - keyLength - extraLength; cmdMessage.element = new LocalCacheElement(key, flags, expire != 0 && expire < CacheElement.THIRTY_DAYS ? LocalCacheElement.Now() + expire : expire, 0L); cmdMessage.element.setData(new byte[size]); channelBuffer.readBytes(cmdMessage.element.getData(), 0, size); } else if (cmdType == Command.INCR || cmdType == Command.DECR) { long initialValue = extrasBuffer.readUnsignedInt(); long amount = extrasBuffer.readUnsignedInt(); long expiration = extrasBuffer.readUnsignedInt(); cmdMessage.incrAmount = (int) amount; cmdMessage.incrDefault = (int) initialValue; cmdMessage.incrExpiry = (int) expiration; } } return cmdMessage; }
Example 15
Source File: MemcachedFrameDecoder.java From fqueue with Apache License 2.0 | 4 votes |
@Override protected Object decode(ChannelHandlerContext ctx, org.jboss.netty.channel.Channel channel, ChannelBuffer buffer) throws Exception { // check the state. if we're WAITING_FOR_DATA that means instead of // breaking into lines, we need N bytes // otherwise, we're waiting for input if (status.state == SessionStatus.State.WAITING_FOR_DATA) { if (buffer.readableBytes() < status.bytesNeeded + MemcachedResponseEncoder.CRLF.capacity()) return null; // verify delimiter matches at the right location ChannelBuffer dest = buffer.slice(status.bytesNeeded + buffer.readerIndex(), 2); StatsCounter.bytes_written.addAndGet(status.bytesNeeded); if (!dest.equals(MemcachedResponseEncoder.CRLF)) { // before we throw error... we're ready for the next command status.ready(); // error, no delimiter at end of payload throw new IncorrectlyTerminatedPayloadException("payload not terminated correctly"); } else { status.processingMultiline(); // There's enough bytes in the buffer and the delimiter is at // the end. Read it. ChannelBuffer result = buffer.slice(buffer.readerIndex(), status.bytesNeeded); buffer.skipBytes(status.bytesNeeded + MemcachedResponseEncoder.CRLF.capacity()); return result; } } else { int minFrameLength = Integer.MAX_VALUE; ChannelBuffer foundDelimiter = null; // command length int frameLength = buffer.bytesBefore(buffer.readerIndex(), buffer.readableBytes(), ChannelBufferIndexFinder.CRLF); if (frameLength >= 0 && frameLength < minFrameLength && buffer.readableBytes() >= frameLength + 2) { minFrameLength = frameLength; foundDelimiter = MemcachedResponseEncoder.CRLF; } if (foundDelimiter != null) { int minDelimLength = foundDelimiter.capacity(); if (discardingTooLongFrame) { // We've just finished discarding a very large frame. // Throw an exception and go back to the initial state. long tooLongFrameLength = this.tooLongFrameLength; this.tooLongFrameLength = 0L; discardingTooLongFrame = false; buffer.skipBytes(minFrameLength + minDelimLength); fail(tooLongFrameLength + minFrameLength + minDelimLength); } if (minFrameLength > maxFrameLength) { // Discard read frame. buffer.skipBytes(minFrameLength + minDelimLength); StatsCounter.bytes_written.addAndGet(minFrameLength + minDelimLength); fail(minFrameLength); } ChannelBuffer frame = buffer.slice(buffer.readerIndex(), minFrameLength); buffer.skipBytes(minFrameLength + minDelimLength); status.processing(); StatsCounter.bytes_written.addAndGet(minFrameLength + minDelimLength); return frame; } else { if (buffer.readableBytes() > maxFrameLength) { // Discard the content of the buffer until a delimiter is // found. tooLongFrameLength = buffer.readableBytes(); buffer.skipBytes(buffer.readableBytes()); discardingTooLongFrame = true; StatsCounter.bytes_written.addAndGet(tooLongFrameLength); } return null; } } }
Example 16
Source File: MemcachedBinaryCommandDecoder.java From fqueue with Apache License 2.0 | 4 votes |
protected Object decode(ChannelHandlerContext channelHandlerContext, Channel channel, ChannelBuffer channelBuffer) throws Exception { // need at least 24 bytes, to get header if (channelBuffer.readableBytes() < 24) return null; // get the header channelBuffer.markReaderIndex(); ChannelBuffer headerBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 24); channelBuffer.readBytes(headerBuffer); short magic = headerBuffer.readUnsignedByte(); // magic should be 0x80 if (magic != 0x80) { headerBuffer.resetReaderIndex(); throw new MalformedCommandException("binary request payload is invalid, magic byte incorrect"); } short opcode = headerBuffer.readUnsignedByte(); short keyLength = headerBuffer.readShort(); short extraLength = headerBuffer.readUnsignedByte(); short dataType = headerBuffer.readUnsignedByte(); // unused short reserved = headerBuffer.readShort(); // unused int totalBodyLength = headerBuffer.readInt(); int opaque = headerBuffer.readInt(); long cas = headerBuffer.readLong(); // we want the whole of totalBodyLength; otherwise, keep waiting. if (channelBuffer.readableBytes() < totalBodyLength) { channelBuffer.resetReaderIndex(); return null; } // This assumes correct order in the enum. If that ever changes, we will have to scan for 'code' field. BinaryCommand bcmd = BinaryCommand.values()[opcode]; Command cmdType = bcmd.correspondingCommand; CommandMessage cmdMessage = CommandMessage.command(cmdType); cmdMessage.noreply = bcmd.noreply; cmdMessage.cas_key = cas; cmdMessage.opaque = opaque; cmdMessage.addKeyToResponse = bcmd.addKeyToResponse; // get extras. could be empty. ChannelBuffer extrasBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, extraLength); channelBuffer.readBytes(extrasBuffer); // get the key if any if (keyLength != 0) { ChannelBuffer keyBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, keyLength); channelBuffer.readBytes(keyBuffer); ArrayList<String> keys = new ArrayList<String>(); String key = keyBuffer.toString(USASCII); keys.add(key); // TODO this or UTF-8? ISO-8859-1? cmdMessage.keys = keys; if (cmdType == Command.ADD || cmdType == Command.SET || cmdType == Command.REPLACE || cmdType == Command.APPEND || cmdType == Command.PREPEND) { // TODO these are backwards from the spec, but seem to be what spymemcached demands -- which has the mistake?! short expire = (short) (extrasBuffer.capacity() != 0 ? extrasBuffer.readUnsignedShort() : 0); short flags = (short) (extrasBuffer.capacity() != 0 ? extrasBuffer.readUnsignedShort() : 0); // the remainder of the message -- that is, totalLength - (keyLength + extraLength) should be the payload int size = totalBodyLength - keyLength - extraLength; cmdMessage.element = new LocalCacheElement(key, flags, expire != 0 && expire < CacheElement.THIRTY_DAYS ? LocalCacheElement.Now() + expire : expire, 0L); cmdMessage.element.setData(new byte[size]); channelBuffer.readBytes(cmdMessage.element.getData(), 0, size); } else if (cmdType == Command.INCR || cmdType == Command.DECR) { long initialValue = extrasBuffer.readUnsignedInt(); long amount = extrasBuffer.readUnsignedInt(); long expiration = extrasBuffer.readUnsignedInt(); cmdMessage.incrAmount = (int) amount; cmdMessage.incrDefault = (int) initialValue; cmdMessage.incrExpiry = (int) expiration; } } return cmdMessage; }