Java Code Examples for org.jboss.netty.buffer.ChannelBuffer#readerIndex()
The following examples show how to use
org.jboss.netty.buffer.ChannelBuffer#readerIndex() .
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: HexDump.java From onos with Apache License 2.0 | 6 votes |
public static void pcepHexDump(ChannelBuffer buff) { log.debug("==================== HEX DUMP ======================"); try { byte[] yTemp; yTemp = buff.array(); int iStartIndex = buff.readerIndex(); int iEndIndex = buff.writerIndex(); do { StringBuilder sb = new StringBuilder(); for (int k = 0; (k < 16) && (iStartIndex < iEndIndex); ++k) { if (0 == k % 4) { sb.append(" "); //blank after 4 bytes } sb.append(String.format("%02X ", yTemp[iStartIndex++])); } log.debug(sb.toString()); } while (iStartIndex < iEndIndex); } catch (Exception e) { log.error("[HexDump] Invalid buffer: " + e.toString()); } log.debug("==================================================="); }
Example 2
Source File: ChannelBufferServletInputStream.java From netty-servlet with Apache License 2.0 | 6 votes |
/** * Creates a new stream which reads data from the specified {@code buffer} * starting at the current {@code readerIndex} and ending at * {@code readerIndex + length}. * * @throws IndexOutOfBoundsException if {@code readerIndex + length} is greater than * {@code writerIndex} */ public ChannelBufferServletInputStream(ChannelBuffer buffer, int length) { if (buffer == null) { throw new NullPointerException("buffer"); } if (length < 0) { throw new IllegalArgumentException("length: " + length); } if (length > buffer.readableBytes()) { throw new IndexOutOfBoundsException("Too many bytes to be read - Needs " + length + ", maximum is " + buffer.readableBytes()); } this.buffer = buffer; startIndex = buffer.readerIndex(); endIndex = startIndex + length; buffer.markReaderIndex(); }
Example 3
Source File: TNettyTransport.java From ikasoa with MIT License | 6 votes |
public TNettyTransport(Channel channel, ChannelBuffer inputBuffer, TNettyTransportType tNettyTransportType) { this.channel = channel; this.inputBuffer = inputBuffer; this.tNettyTransportType = tNettyTransportType; this.outputBuffer = ChannelBuffers.dynamicBuffer(DEFAULT_OUTPUT_BUFFER_SIZE); this.initialReaderIndex = inputBuffer.readerIndex(); if (!inputBuffer.hasArray()) { buffer = null; bufferPosition = 0; initialBufferPosition = bufferEnd = -1; } else { buffer = inputBuffer.array(); initialBufferPosition = bufferPosition = inputBuffer.arrayOffset() + inputBuffer.readerIndex(); bufferEnd = bufferPosition + inputBuffer.readableBytes(); inputBuffer.readerIndex(inputBuffer.readerIndex() + inputBuffer.readableBytes()); } }
Example 4
Source File: FrameDecoder.java From android-netty with Apache License 2.0 | 6 votes |
private void callDecode(ChannelHandlerContext context, Channel channel, ChannelBuffer cumulation, SocketAddress remoteAddress) throws Exception { while (cumulation.readable()) { int oldReaderIndex = cumulation.readerIndex(); Object frame = decode(context, channel, cumulation); if (frame == null) { if (oldReaderIndex == cumulation.readerIndex()) { // Seems like more data is required. // Let us wait for the next notification. break; } else { // Previous data has been discarded. // Probably it is reading on. continue; } } if (oldReaderIndex == cumulation.readerIndex()) { throw new IllegalStateException("decode() method must read at least one byte " + "if it returned a frame (caused by: " + getClass() + ')'); } unfoldAndFireMessageReceived(context, remoteAddress, frame); } }
Example 5
Source File: OFFeaturesReply.java From floodlight_with_topoguard with Apache License 2.0 | 6 votes |
@Override public void readFrom(ChannelBuffer data) { super.readFrom(data); this.datapathId = data.readLong(); this.buffers = data.readInt(); this.tables = data.readByte(); data.readerIndex(data.readerIndex() + 3); // pad this.capabilities = data.readInt(); this.actions = data.readInt(); if (this.ports == null) { this.ports = new ArrayList<OFPhysicalPort>(); } else { this.ports.clear(); } int portCount = (super.getLengthU() - 32) / OFPhysicalPort.MINIMUM_LENGTH; OFPhysicalPort port; for (int i = 0; i < portCount; ++i) { port = new OFPhysicalPort(); port.readFrom(data); this.ports.add(port); } }
Example 6
Source File: OFPortStatus.java From floodlight_with_topoguard with Apache License 2.0 | 5 votes |
@Override public void readFrom(ChannelBuffer data) { super.readFrom(data); this.reason = data.readByte(); data.readerIndex(data.readerIndex() + 7); // skip 7 bytes of padding if (this.desc == null) this.desc = new OFPhysicalPort(); this.desc.readFrom(data); }
Example 7
Source File: AbstractChannelBuffer.java From simple-netty-source with Apache License 2.0 | 5 votes |
public void writeBytes(ChannelBuffer src, int length) { if (length > src.readableBytes()) { throw new IndexOutOfBoundsException("Too many bytes to write - Need " + length + ", maximum is " + src.readableBytes()); } writeBytes(src, src.readerIndex(), length); src.readerIndex(src.readerIndex() + length); }
Example 8
Source File: AbstractChannelBuffer.java From simple-netty-source with Apache License 2.0 | 5 votes |
public void setBytes(int index, ChannelBuffer src, int length) { if (length > src.readableBytes()) { throw new IndexOutOfBoundsException("Too many bytes to write: Need " + length + ", maximum is " + src.readableBytes()); } setBytes(index, src, src.readerIndex(), length); src.readerIndex(src.readerIndex() + length); }
Example 9
Source File: BgpUpdate.java From onos with Apache License 2.0 | 5 votes |
/** * Parses a message that contains encoded IPv4 network prefixes. * <p> * The IPv4 prefixes are encoded in the form: * <Length, Prefix> where Length is the length in bits of the IPv4 prefix, * and Prefix is the IPv4 prefix (padded with trailing bits to the end * of an octet). * * @param totalLength the total length of the data to parse * @param message the message with data to parse * @return a collection of parsed IPv4 network prefixes * @throws BgpMessage.BgpParseException */ private static Collection<Ip4Prefix> parsePackedIp4Prefixes( int totalLength, ChannelBuffer message) throws BgpMessage.BgpParseException { Collection<Ip4Prefix> result = new ArrayList<>(); if (totalLength == 0) { return result; } // Parse the data byte[] buffer = new byte[Ip4Address.BYTE_LENGTH]; int dataEnd = message.readerIndex() + totalLength; while (message.readerIndex() < dataEnd) { int prefixBitlen = message.readUnsignedByte(); int prefixBytelen = (prefixBitlen + 7) / 8; // Round-up if (message.readerIndex() + prefixBytelen > dataEnd) { String errorMsg = "Malformed Network Prefixes"; throw new BgpMessage.BgpParseException(errorMsg); } message.readBytes(buffer, 0, prefixBytelen); Ip4Prefix prefix = Ip4Prefix.valueOf(Ip4Address.valueOf(buffer), prefixBitlen); result.add(prefix); } return result; }
Example 10
Source File: MessageDecoder.java From chuidiang-ejemplos with GNU Lesser General Public License v3.0 | 5 votes |
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { System.out.println(ctx.canHandleUpstream()); List<List<Byte>> objectsDecoded = new LinkedList<>(); int initialIndex = buffer.readerIndex(); int readableBytes = buffer.readableBytes(); List<Byte> bytes = new LinkedList<>(); for (int i = initialIndex; i < initialIndex + readableBytes; i++) { if (buffer.getByte(i) == 0) { buffer.readerIndex(i + 1); objectsDecoded.add(bytes); bytes = new LinkedList<>(); } else { bytes.add(buffer.getByte(i)); } } if (objectsDecoded.size()>0){ return objectsDecoded; } return null; }
Example 11
Source File: NettyHeader.java From Elasticsearch with Apache License 2.0 | 5 votes |
public static void writeHeader(ChannelBuffer buffer, long requestId, byte status, Version version) { int index = buffer.readerIndex(); buffer.setByte(index, 'E'); index += 1; buffer.setByte(index, 'S'); index += 1; // write the size, the size indicates the remaining message size, not including the size int buffer.setInt(index, buffer.readableBytes() - 6); index += 4; buffer.setLong(index, requestId); index += 8; buffer.setByte(index, status); index += 1; buffer.setInt(index, version.id); }
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: ThriftFrameDecoder.java From ikasoa with MIT License | 5 votes |
protected ChannelBuffer tryDecodeUnframedMessage(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, TProtocolFactory inputProtocolFactory) throws TException { int messageLength = 0; int messageStartReaderIndex = buffer.readerIndex(); try { TNettyTransport decodeAttemptTransport = new TNettyTransport(channel, buffer, TNettyTransportType.UNFRAMED); int initialReadBytes = decodeAttemptTransport.getReadByteCount(); TProtocol inputProtocol = inputProtocolFactory.getProtocol(decodeAttemptTransport); inputProtocol.readMessageBegin(); TProtocolUtil.skip(inputProtocol, TType.STRUCT); inputProtocol.readMessageEnd(); messageLength = decodeAttemptTransport.getReadByteCount() - initialReadBytes; } catch (TTransportException | IndexOutOfBoundsException e) { return null; } finally { if (buffer.readerIndex() - messageStartReaderIndex > maxFrameSize) Channels.fireExceptionCaught(ctx, new TooLongFrameException(String.format("Maximum frame size of %d exceeded .", maxFrameSize))); buffer.readerIndex(messageStartReaderIndex); } if (messageLength <= 0) return null; ChannelBuffer messageBuffer = extractFrame(buffer, messageStartReaderIndex, messageLength); buffer.readerIndex(messageStartReaderIndex + messageLength); return messageBuffer; }
Example 14
Source File: BgpUpdate.java From onos with Apache License 2.0 | 5 votes |
/** * Parses a message that contains encoded IPv6 network prefixes. * <p> * The IPv6 prefixes are encoded in the form: * <Length, Prefix> where Length is the length in bits of the IPv6 prefix, * and Prefix is the IPv6 prefix (padded with trailing bits to the end * of an octet). * * @param totalLength the total length of the data to parse * @param message the message with data to parse * @return a collection of parsed IPv6 network prefixes * @throws BgpMessage.BgpParseException */ private static Collection<Ip6Prefix> parsePackedIp6Prefixes( int totalLength, ChannelBuffer message) throws BgpMessage.BgpParseException { Collection<Ip6Prefix> result = new ArrayList<>(); if (totalLength == 0) { return result; } // Parse the data byte[] buffer = new byte[Ip6Address.BYTE_LENGTH]; int dataEnd = message.readerIndex() + totalLength; while (message.readerIndex() < dataEnd) { int prefixBitlen = message.readUnsignedByte(); int prefixBytelen = (prefixBitlen + 7) / 8; // Round-up if (message.readerIndex() + prefixBytelen > dataEnd) { String errorMsg = "Malformed Network Prefixes"; throw new BgpMessage.BgpParseException(errorMsg); } message.readBytes(buffer, 0, prefixBytelen); Ip6Prefix prefix = Ip6Prefix.valueOf(Ip6Address.valueOf(buffer), prefixBitlen); result.add(prefix); } return result; }
Example 15
Source File: LZFCompressor.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override public boolean isCompressed(ChannelBuffer buffer) { int offset = buffer.readerIndex(); return buffer.readableBytes() >= 3 && buffer.getByte(offset) == LZFChunk.BYTE_Z && buffer.getByte(offset + 1) == LZFChunk.BYTE_V && (buffer.getByte(offset + 2) == LZFChunk.BLOCK_TYPE_COMPRESSED || buffer.getByte(offset + 2) == LZFChunk.BLOCK_TYPE_NON_COMPRESSED); }
Example 16
Source File: DeflateCompressor.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override public boolean isCompressed(ChannelBuffer buffer) { if (buffer.readableBytes() < HEADER.length) { return false; } final int offset = buffer.readerIndex(); for (int i = 0; i < HEADER.length; ++i) { if (buffer.getByte(offset + i) != HEADER[i]) { return false; } } return true; }
Example 17
Source File: CompositeChannelBuffer.java From simple-netty-source with Apache License 2.0 | 4 votes |
/** * Same with {@link #slice(int, int)} except that this method returns a list. */ public List<ChannelBuffer> decompose(int index, int length) { if (length == 0) { return Collections.emptyList(); } if (index + length > capacity()) { throw new IndexOutOfBoundsException("Too many bytes to decompose - Need " + (index + length) + ", capacity is " + capacity()); } int componentId = componentId(index); List<ChannelBuffer> slice = new ArrayList<ChannelBuffer>(components.length); // The first component ChannelBuffer first = components[componentId].duplicate(); first.readerIndex(index - indices[componentId]); ChannelBuffer buf = first; int bytesToSlice = length; do { int readableBytes = buf.readableBytes(); if (bytesToSlice <= readableBytes) { // Last component buf.writerIndex(buf.readerIndex() + bytesToSlice); slice.add(buf); break; } else { // Not the last component slice.add(buf); bytesToSlice -= readableBytes; componentId ++; // Fetch the next component. buf = components[componentId].duplicate(); } } while (bytesToSlice > 0); // Slice all components because only readable bytes are interesting. for (int i = 0; i < slice.size(); i ++) { slice.set(i, slice.get(i).slice()); } return slice; }
Example 18
Source File: SizeHeaderFrameDecoder.java From Elasticsearch with Apache License 2.0 | 4 votes |
@Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { if (buffer.readableBytes() < 6) { return null; } int readerIndex = buffer.readerIndex(); if (buffer.getByte(readerIndex) != 'E' || buffer.getByte(readerIndex + 1) != 'S') { // special handling for what is probably HTTP if (bufferStartsWith(buffer, readerIndex, "GET ") || bufferStartsWith(buffer, readerIndex, "POST ") || bufferStartsWith(buffer, readerIndex, "PUT ") || bufferStartsWith(buffer, readerIndex, "HEAD ") || bufferStartsWith(buffer, readerIndex, "DELETE ") || bufferStartsWith(buffer, readerIndex, "OPTIONS ") || bufferStartsWith(buffer, readerIndex, "PATCH ") || bufferStartsWith(buffer, readerIndex, "TRACE ")) { throw new HttpOnTransportException("This is not a HTTP port"); } // we have 6 readable bytes, show 4 (should be enough) throw new StreamCorruptedException("invalid internal transport message format, got (" + Integer.toHexString(buffer.getByte(readerIndex) & 0xFF) + "," + Integer.toHexString(buffer.getByte(readerIndex + 1) & 0xFF) + "," + Integer.toHexString(buffer.getByte(readerIndex + 2) & 0xFF) + "," + Integer.toHexString(buffer.getByte(readerIndex + 3) & 0xFF) + ")"); } int dataLen = buffer.getInt(buffer.readerIndex() + 2); if (dataLen == NettyHeader.PING_DATA_SIZE) { // discard the messages we read and continue, this is achieved by skipping the bytes // and returning null buffer.skipBytes(6); return null; } if (dataLen <= 0) { throw new StreamCorruptedException("invalid data length: " + dataLen); } // safety against too large frames being sent if (dataLen > NINETY_PER_HEAP_SIZE) { throw new TooLongFrameException( "transport content length received [" + new ByteSizeValue(dataLen) + "] exceeded [" + new ByteSizeValue(NINETY_PER_HEAP_SIZE) + "]"); } if (buffer.readableBytes() < dataLen + 6) { return null; } buffer.skipBytes(6); return buffer; }
Example 19
Source File: LinkTlv.java From onos with Apache License 2.0 | 4 votes |
/** * Reads bytes from channel buffer . * * @param channelBuffer channel buffer instance * @throws OspfParseException might throws exception while parsing packet */ public void readFrom(ChannelBuffer channelBuffer) throws OspfParseException { while (channelBuffer.readableBytes() > 0) { TlvHeader tlvHeader = new TlvHeader(); tlvHeader.setTlvType(channelBuffer.readUnsignedShort()); tlvHeader.setTlvLength(channelBuffer.readUnsignedShort()); if (LinkSubTypes.LINK_TYPE.value() == tlvHeader.tlvType()) { LinkType linktype = new LinkType(tlvHeader); linktype.readFrom(channelBuffer.readBytes(tlvHeader.tlvLength())); subTlv.add(linktype); if (tlvHeader.tlvLength() < OspfUtil.FOUR_BYTES) { int readerIndex = channelBuffer.readerIndex() + (OspfUtil.FOUR_BYTES - tlvHeader.tlvLength()); channelBuffer.readerIndex(readerIndex); } } else if (LinkSubTypes.LINK_ID.value() == tlvHeader.tlvType()) { LinkId linkId = new LinkId(tlvHeader); linkId.readFrom(channelBuffer.readBytes(tlvHeader.tlvLength())); subTlv.add(linkId); } else if (LinkSubTypes.LOCAL_INTERFACE_IP_ADDRESS.value() == tlvHeader.tlvType()) { LocalInterfaceIpAddress localInterfaceIpAddress = new LocalInterfaceIpAddress(tlvHeader); localInterfaceIpAddress.readFrom(channelBuffer.readBytes(tlvHeader.tlvLength())); subTlv.add(localInterfaceIpAddress); } else if (LinkSubTypes.REMOTE_INTERFACE_IP_ADDRESS.value() == tlvHeader.tlvType()) { RemoteInterfaceIpAddress remoteInterfaceIpAddress = new RemoteInterfaceIpAddress(tlvHeader); remoteInterfaceIpAddress.readFrom(channelBuffer.readBytes(tlvHeader.tlvLength())); subTlv.add(remoteInterfaceIpAddress); } else if (LinkSubTypes.TRAFFIC_ENGINEERING_METRIC.value() == tlvHeader.tlvType()) { TrafficEngineeringMetric trafficEngineeringMetric = new TrafficEngineeringMetric(tlvHeader); trafficEngineeringMetric.readFrom(channelBuffer.readBytes(tlvHeader.tlvLength())); subTlv.add(trafficEngineeringMetric); } else if (LinkSubTypes.MAXIMUM_BANDWIDTH.value() == tlvHeader.tlvType()) { MaximumBandwidth maximumBandwidth = new MaximumBandwidth(tlvHeader); maximumBandwidth.readFrom(channelBuffer.readBytes(tlvHeader.tlvLength())); subTlv.add(maximumBandwidth); } else if (LinkSubTypes.MAXIMUM_RESERVABLE_BANDWIDTH.value() == tlvHeader.tlvType()) { MaximumReservableBandwidth maximumReservableBandwidth = new MaximumReservableBandwidth(tlvHeader); maximumReservableBandwidth.readFrom(channelBuffer.readBytes(tlvHeader.tlvLength())); subTlv.add(maximumReservableBandwidth); } else if (LinkSubTypes.UNRESERVED_BANDWIDTH.value() == tlvHeader.tlvType()) { UnreservedBandwidth unreservedBandwidth = new UnreservedBandwidth(tlvHeader); unreservedBandwidth.readFrom(channelBuffer.readBytes(tlvHeader.tlvLength())); subTlv.add(unreservedBandwidth); } else if (LinkSubTypes.ADMINISTRATIVE_GROUP.value() == tlvHeader.tlvType()) { AdministrativeGroup administrativeGroup = new AdministrativeGroup(tlvHeader); administrativeGroup.readFrom(channelBuffer.readBytes(tlvHeader.tlvLength())); subTlv.add(administrativeGroup); } else { UnknownLinkSubType unknownLinkSubType = new UnknownLinkSubType(tlvHeader); unknownLinkSubType.readFrom(channelBuffer.readBytes(tlvHeader.tlvLength())); subTlv.add(unknownLinkSubType); } } }
Example 20
Source File: PcepMessageVer1.java From onos with Apache License 2.0 | 4 votes |
@Override public PcepMessage readFrom(ChannelBuffer cb) throws PcepParseException, PcepOutOfBoundMessageException { if (cb.readableBytes() < MINIMUM_LENGTH) { throw new PcepParseException("Packet should have minimum length: " + MINIMUM_LENGTH); } try { int start = cb.readerIndex(); // fixed value property version == 1 byte version = cb.readByte(); version = (byte) (version >> PcepMessageVer1.SHIFT_FLAG); if (version != (byte) PACKET_VERSION) { throw new PcepParseException("Wrong version. Expected=PcepVersion.Message_1(1), got=" + version); } byte type = cb.readByte(); short length = cb.readShort(); cb.readerIndex(start); // Check the out-of-bound message. // If the message is out-of-bound then throw PcepOutOfBoundException. if ((length - MINIMUM_COMMON_HEADER_LENGTH) > cb.readableBytes()) { throw new PcepOutOfBoundMessageException("Message is out-of-bound."); } if (type == (byte) PcepType.OPEN.getType()) { log.debug("OPEN MESSAGE is received"); return PcepOpenMsgVer1.READER.readFrom(cb.readBytes(length)); } else if (type == (byte) PcepType.KEEP_ALIVE.getType()) { log.debug("KEEPALIVE MESSAGE is received"); return PcepKeepaliveMsgVer1.READER.readFrom(cb.readBytes(length)); } else if (type == (byte) PcepType.ERROR.getType()) { log.debug("ERROR MESSAGE is received"); return PcepErrorMsgVer1.READER.readFrom(cb.readBytes(length)); } else if (type == (byte) PcepType.CLOSE.getType()) { log.debug("CLOSE MESSAGE is received"); return PcepCloseMsgVer1.READER.readFrom(cb.readBytes(length)); } else if (type == (byte) PcepType.REPORT.getType()) { log.debug("REPORT MESSAGE is received"); return PcepReportMsgVer1.READER.readFrom(cb.readBytes(length)); } else if (type == (byte) PcepType.UPDATE.getType()) { log.debug("UPDATE MESSAGE is received"); return PcepUpdateMsgVer1.READER.readFrom(cb.readBytes(length)); } else if (type == (byte) PcepType.INITIATE.getType()) { log.debug("INITIATE MESSAGE is received"); return PcepInitiateMsgVer1.READER.readFrom(cb.readBytes(length)); } else if (type == (byte) PcepType.LS_REPORT.getType()) { log.debug("LS REPORT MESSAGE is received"); return PcepLSReportMsgVer1.READER.readFrom(cb.readBytes(length)); } else if (type == (byte) PcepType.LABEL_RANGE_RESERV.getType()) { log.debug("LABEL RANGE RESERVE MESSAGE is received"); return PcepLabelRangeResvMsgVer1.READER.readFrom(cb.readBytes(length)); } else if (type == (byte) PcepType.LABEL_UPDATE.getType()) { log.debug("LABEL UPDATE MESSAGE is received"); return PcepLabelUpdateMsgVer1.READER.readFrom(cb.readBytes(length)); } else { throw new PcepParseException("ERROR: UNKNOWN MESSAGE is received. Msg Type: " + type); } } catch (IndexOutOfBoundsException e) { throw new PcepParseException(PcepErrorDetailInfo.ERROR_TYPE_1, PcepErrorDetailInfo.ERROR_VALUE_1); } }