List of usage examples for io.netty.buffer ByteBuf writerIndex
public abstract int writerIndex();
From source file:org.opendaylight.openflowjava.protocol.impl.util.OF13MatchSerializer.java
License:Open Source License
@Override public void serialize(Match match, ByteBuf outBuffer) { if (match == null) { LOG.debug("Match is null"); return;//w w w . j ava2 s . c om } int matchStartIndex = outBuffer.writerIndex(); serializeType(match, outBuffer); int matchLengthIndex = outBuffer.writerIndex(); outBuffer.writeShort(EncodeConstants.EMPTY_LENGTH); serializeMatchEntries(match.getMatchEntry(), outBuffer); // Length of ofp_match (excluding padding) int matchLength = outBuffer.writerIndex() - matchStartIndex; outBuffer.setShort(matchLengthIndex, matchLength); int paddingRemainder = matchLength % EncodeConstants.PADDING; if (paddingRemainder != 0) { outBuffer.writeZero(EncodeConstants.PADDING - paddingRemainder); } }
From source file:org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception { logger.trace("readable bytes {}, records read {}, incomplete record bytes {}", buf.readableBytes(), recordsRead, lastRecordBytes); if (lastRecordBytes == 0) { if (buf.readableBytes() < 4) { return; //wait for more data }/*from www. j av a 2s .c om*/ skipSpaces(buf); byte[] buff = new byte[4]; buf.getBytes(buf.readerIndex(), buff); ByteSourceJsonBootstrapper strapper = new ByteSourceJsonBootstrapper(jacksonIOContext, buff, 0, 4); JsonEncoding jsonEncoding = strapper.detectEncoding(); if (!JsonEncoding.UTF8.equals(jsonEncoding)) { throw new InvalidEncodingException(jsonEncoding.getJavaName(), "currently only UTF-8 is supported"); } } int index = lastRecordBytes + buf.readerIndex(); for (; index < buf.writerIndex(); index++) { switch (buf.getByte(index)) { case '{': if (!inS) { leftCurlies++; } break; case '}': if (!inS) { rightCurlies++; } break; case '"': if (buf.getByte(index - 1) != '\\') { inS = !inS; } break; default: break; } if (leftCurlies != 0 && leftCurlies == rightCurlies && !inS) { ByteBuf slice = buf.readSlice(1 + index - buf.readerIndex()); JsonParser jp = jacksonJsonFactory.createParser(new ByteBufInputStream(slice)); JsonNode root = jp.readValueAsTree(); out.add(root); leftCurlies = rightCurlies = lastRecordBytes = 0; recordsRead++; break; } if (index - buf.readerIndex() >= maxFrameLength) { fail(ctx, index - buf.readerIndex()); } } // end of stream, save the incomplete record index to avoid reexamining the whole on next run if (index >= buf.writerIndex()) { lastRecordBytes = buf.readableBytes(); return; } }
From source file:org.opendaylight.ovsdb.lib.jsonrpc.JsonRpcDecoder.java
License:Open Source License
private void print(ByteBuf buf, int startPos, int chars, String message) { if (null == message) { message = ""; }//from www .j a v a 2s . com if (startPos > buf.writerIndex()) { logger.trace("startPos out of bounds"); } byte[] bytes = new byte[startPos + chars <= buf.writerIndex() ? chars : buf.writerIndex() - startPos]; buf.getBytes(startPos, bytes); logger.trace("{} ={}", message, new String(bytes)); }
From source file:org.opendaylight.protocol.bgp.linkstate.spi.TlvUtil.java
License:Open Source License
/** * Util method for writing TLV header.// w w w .ja va 2 s . c o m * * @param type TLV type (2B) * @param value TLV value (2B) * @param byteAggregator final ByteBuf where the tlv should be serialized */ public static void writeTLV(final int type, final ByteBuf value, final ByteBuf byteAggregator) { byteAggregator.writeShort(type); byteAggregator.writeShort(value.writerIndex()); byteAggregator.writeBytes(value); if (LOG.isDebugEnabled()) { value.readerIndex(0); LOG.debug("Serialized tlv type {} to: {}", type, ByteBufUtil.hexDump(value)); } }
From source file:org.opendaylight.protocol.bgp.parser.impl.message.BGPOpenMessageParser.java
License:Open Source License
/** * Serializes given BGP Open message to byte array, without the header. * * @param msg BGP Open message to be serialized. * @param bytes ByteBuf where the message will be serialized *//*from w w w. j av a 2s. co m*/ @Override public void serializeMessage(final Notification msg, final ByteBuf bytes) { Preconditions.checkArgument(msg instanceof Open, "Message needs to be of type Open"); final Open open = (Open) msg; final ByteBuf msgBody = Unpooled.buffer(); msgBody.writeByte(BGP_VERSION); // When our AS number does not fit into two bytes, we report it as AS_TRANS int openAS = open.getMyAsNumber(); if (openAS > Values.UNSIGNED_SHORT_MAX_VALUE) { openAS = AS_TRANS; } msgBody.writeShort(openAS); msgBody.writeShort(open.getHoldTimer()); msgBody.writeBytes(Ipv4Util.bytesForAddress(open.getBgpIdentifier())); final ByteBuf paramsBuffer = Unpooled.buffer(); if (open.getBgpParameters() != null) { for (final BgpParameters param : open.getBgpParameters()) { this.reg.serializeParameter(param, paramsBuffer); } } msgBody.writeByte(paramsBuffer.writerIndex()); msgBody.writeBytes(paramsBuffer); MessageUtil.formatMessage(TYPE, msgBody, bytes); }
From source file:org.opendaylight.protocol.bgp.parser.impl.message.BGPUpdateMessageParser.java
License:Open Source License
@Override public void serializeMessage(final Notification message, final ByteBuf bytes) { Preconditions.checkArgument(message instanceof Update, "Message needs to be of type Update"); final Update update = (Update) message; final ByteBuf messageBody = Unpooled.buffer(); final WithdrawnRoutes withdrawnRoutes = update.getWithdrawnRoutes(); if (withdrawnRoutes != null) { final ByteBuf withdrawnRoutesBuf = Unpooled.buffer(); for (final Ipv4Prefix prefix : withdrawnRoutes.getWithdrawnRoutes()) { ByteBufWriteUtil.writeMinimalPrefix(prefix, withdrawnRoutesBuf); }/*from w w w . ja va2s. c o m*/ messageBody.writeShort(withdrawnRoutesBuf.writerIndex()); messageBody.writeBytes(withdrawnRoutesBuf); } else { messageBody.writeZero(WITHDRAWN_ROUTES_LENGTH_SIZE); } if (update.getAttributes() != null) { final ByteBuf pathAttributesBuf = Unpooled.buffer(); this.reg.serializeAttribute(update.getAttributes(), pathAttributesBuf); messageBody.writeShort(pathAttributesBuf.writerIndex()); messageBody.writeBytes(pathAttributesBuf); } else { messageBody.writeZero(TOTAL_PATH_ATTR_LENGTH_SIZE); } final Nlri nlri = update.getNlri(); if (nlri != null && nlri.getNlri() != null) { for (final Ipv4Prefix prefix : nlri.getNlri()) { ByteBufWriteUtil.writeMinimalPrefix(prefix, messageBody); } } MessageUtil.formatMessage(TYPE, messageBody, bytes); }
From source file:org.opendaylight.protocol.bgp.parser.impl.ParserTest.java
License:Open Source License
@Test public void testNotificationMsg() throws BGPParsingException, BGPDocumentedException { Notification notMsg = new NotifyBuilder().setErrorCode(BGPError.OPT_PARAM_NOT_SUPPORTED.getCode()) .setErrorSubcode(BGPError.OPT_PARAM_NOT_SUPPORTED.getSubcode()).setData(new byte[] { 4, 9 }) .build();/* w w w. j a v a 2 s. c o m*/ final ByteBuf bytes = Unpooled.buffer(); ParserTest.reg.serializeMessage(notMsg, bytes); assertArrayEquals(notificationBMsg, ByteArray.subByte(bytes.array(), 0, bytes.writerIndex())); Notification m = ParserTest.reg.parseMessage(Unpooled.copiedBuffer(bytes)); assertTrue(m instanceof Notify); assertEquals(BGPError.OPT_PARAM_NOT_SUPPORTED, BGPError.forValue(((Notify) m).getErrorCode(), ((Notify) m).getErrorSubcode())); assertArrayEquals(new byte[] { 4, 9 }, ((Notify) m).getData()); notMsg = new NotifyBuilder().setErrorCode(BGPError.CONNECTION_NOT_SYNC.getCode()) .setErrorSubcode(BGPError.CONNECTION_NOT_SYNC.getSubcode()).build(); bytes.clear(); ParserTest.reg.serializeMessage(notMsg, bytes); m = ParserTest.reg.parseMessage(Unpooled.copiedBuffer(bytes)); assertTrue(m instanceof Notify); assertEquals(BGPError.CONNECTION_NOT_SYNC, BGPError.forValue(((Notify) m).getErrorCode(), ((Notify) m).getErrorSubcode())); assertNull(((Notify) m).getData()); }
From source file:org.opendaylight.protocol.bgp.parser.impl.PathAttributeParserTest.java
License:Open Source License
@Test public void testSerializingAigpAttribute() throws BGPDocumentedException, BGPParsingException { final byte[] value = new byte[] { 1, 0, 11, 0, 0, 0, 0, 0, 0, 0, 8 }; final ByteBuf inputData = Unpooled.buffer(); final ByteBuf testBuffer = Unpooled.buffer(); AttributeUtil.formatAttribute(AttributeUtil.OPTIONAL, AigpAttributeParser.TYPE, Unpooled.copiedBuffer(value), inputData); final BGPExtensionProviderContext providerContext = ServiceLoaderBGPExtensionProviderContext .getSingletonInstance();// ww w. j a v a2s. c om final Attributes pathAttributes = providerContext.getAttributeRegistry().parseAttributes(inputData); final Aigp aigp = pathAttributes.getAigp(); final AttributesBuilder pathAttributesBuilder = new AttributesBuilder(); pathAttributesBuilder.setAigp(aigp); final AigpAttributeParser parser = new AigpAttributeParser(); parser.serializeAttribute(pathAttributesBuilder.build(), testBuffer); final byte[] unparserData = inputData.copy(0, inputData.writerIndex()).array(); final byte[] serializedData = testBuffer.copy(0, inputData.writerIndex()).array(); assertTrue("Buffers should be the same.", Arrays.equals(unparserData, serializedData)); }
From source file:org.opendaylight.protocol.bgp.parser.spi.AttributeUtil.java
License:Open Source License
/** * Adds header to attribute value. If the length of the attribute value exceeds one-byte length field, * set EXTENDED bit and write length as 2B field. * * @param flags// w ww .j av a2s. co m * @param type of the attribute * @param value attribute value * @param buffer ByteBuf where the attribute will be copied with its header */ public static void formatAttribute(final int flags, final int type, final ByteBuf value, final ByteBuf buffer) { final int length = value.writerIndex(); final boolean extended = (length > MAX_ATTR_LENGTH_FOR_SINGLE_BYTE) ? true : false; buffer.writeByte((extended) ? (flags | EXTENDED) : flags); buffer.writeByte(type); if (extended) { buffer.writeShort(length); } else { buffer.writeByte(length); } buffer.writeBytes(value); }
From source file:org.opendaylight.protocol.bgp.parser.spi.BgpPrefixSidTlvUtil.java
License:Open Source License
/** * Utilized method for serialization of BGP prefix SID TLV * * @param type of TLV// w ww . j a v a2 s.co m * @param value of TLV * @param buffer output aggregator */ public static void formatBgpPrefixSidTlv(final int type, final ByteBuf value, final ByteBuf buffer) { buffer.writeByte(type); buffer.writeShort(value.writerIndex()); buffer.writeBytes(value); }