List of usage examples for io.netty.buffer ByteBuf discardReadBytes
public abstract ByteBuf discardReadBytes();
From source file:org.opendaylight.controller.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder.java
License:Open Source License
@Override @VisibleForTesting/* w w w. j a va 2 s.com*/ public void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws IOException, SAXException, NetconfDocumentedException { if (in.readableBytes() == 0) { LOG.debug("No more content in incoming buffer."); return; } in.markReaderIndex(); try { if (LOG.isTraceEnabled()) { LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in)); } byte[] bytes = new byte[in.readableBytes()]; in.readBytes(bytes); logMessage(bytes); // Extract bytes containing header with additional metadata String additionalHeader = null; if (startsWithAdditionalHeader(bytes)) { // Auth information containing username, ip address... extracted for monitoring int endOfAuthHeader = getAdditionalHeaderEndIndex(bytes); if (endOfAuthHeader > -1) { byte[] additionalHeaderBytes = Arrays.copyOfRange(bytes, 0, endOfAuthHeader + 2); additionalHeader = additionalHeaderToString(additionalHeaderBytes); bytes = Arrays.copyOfRange(bytes, endOfAuthHeader + 2, bytes.length); } } Document doc = XmlUtil.readXmlToDocument(new ByteArrayInputStream(bytes)); final NetconfMessage message = getNetconfMessage(additionalHeader, doc); if (message instanceof NetconfHelloMessage) { Preconditions.checkState(helloReceived == false, "Multiple hello messages received, unexpected hello: %s", message); out.add(message); helloReceived = true; // Non hello message, suspend the message and insert into cache } else { Preconditions.checkState(helloReceived, "Hello message not received, instead received: %s", message); LOG.debug("Netconf message received during negotiation, caching {}", message); nonHelloMessages.add(message); } } finally { in.discardReadBytes(); } }
From source file:org.opendaylight.controller.netconf.util.handler.NetconfChunkAggregator.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { while (in.isReadable()) { switch (state) { case HEADER_ONE: { final byte b = in.readByte(); if (b != '\n') { logger.debug("Got byte {} while waiting for {}", b, (byte) '\n'); throw new IllegalStateException("Malformed chunk header encountered (byte 0)"); }/*from w w w. j a va 2s . com*/ state = State.HEADER_TWO; initChunk(); break; } case HEADER_TWO: { final byte b = in.readByte(); if (b != '#') { logger.debug("Got byte {} while waiting for {}", b, (byte) '#'); throw new IllegalStateException("Malformed chunk header encountered (byte 1)"); } state = State.HEADER_LENGTH_FIRST; break; } case HEADER_LENGTH_FIRST: { final byte b = in.readByte(); chunkSize = processHeaderLengthFirst(b); state = State.HEADER_LENGTH_OTHER; break; } case HEADER_LENGTH_OTHER: { final byte b = in.readByte(); if (b == '\n') { state = State.DATA; break; } if (b < '0' || b > '9') { logger.debug("Got byte {} while waiting for {}-{}", b, (byte) '0', (byte) '9'); throw new IllegalStateException("Invalid chunk size encountered"); } chunkSize *= 10; chunkSize += b - '0'; if (chunkSize > maxChunkSize) { logger.debug("Parsed chunk size {}, maximum allowed is {}", chunkSize, maxChunkSize); throw new IllegalStateException("Maximum chunk size exceeded"); } break; } case DATA: /* * FIXME: this gathers all data into one big chunk before passing * it on. Make sure the pipeline can work with partial data * and then change this piece to pass the data on as it * comes through. */ if (in.readableBytes() < chunkSize) { logger.debug("Buffer has {} bytes, need {} to complete chunk", in.readableBytes(), chunkSize); in.discardReadBytes(); return; } aggregateChunks(in.readBytes((int) chunkSize)); state = State.FOOTER_ONE; break; case FOOTER_ONE: { final byte b = in.readByte(); if (b != '\n') { logger.debug("Got byte {} while waiting for {}", b, (byte) '\n'); throw new IllegalStateException("Malformed chunk footer encountered (byte 0)"); } state = State.FOOTER_TWO; chunkSize = 0; break; } case FOOTER_TWO: { final byte b = in.readByte(); if (b != '#') { logger.debug("Got byte {} while waiting for {}", b, (byte) '#'); throw new IllegalStateException("Malformed chunk footer encountered (byte 1)"); } state = State.FOOTER_THREE; break; } case FOOTER_THREE: { final byte b = in.readByte(); // In this state, either header-of-new-chunk or message-end is expected // Depends on the next character if (isHeaderLengthFirst(b)) { // Extract header length#1 from new chunk chunkSize = processHeaderLengthFirst(b); // Proceed with next chunk processing state = State.HEADER_LENGTH_OTHER; } else if (b == '#') { state = State.FOOTER_FOUR; } else { logger.debug("Got byte {} while waiting for {} or {}-{}", b, (byte) '#', (byte) '1', (byte) '9'); throw new IllegalStateException("Malformed chunk footer encountered (byte 2)"); } break; } case FOOTER_FOUR: { final byte b = in.readByte(); if (b != '\n') { logger.debug("Got byte {} while waiting for {}", b, (byte) '\n'); throw new IllegalStateException("Malformed chunk footer encountered (byte 3)"); } state = State.HEADER_ONE; out.add(chunk); chunk = null; break; } } } in.discardReadBytes(); }
From source file:org.opendaylight.controller.netconf.util.handler.NetconfEOMAggregator.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { int index = indexOfSequence(in, NetconfMessageConstants.END_OF_MESSAGE); if (index == -1) { logger.debug("Message is not complete, read again."); if (logger.isTraceEnabled()) { String str = in.toString(Charsets.UTF_8); logger.trace("Message read so far: {}", str); }//from www. j a va2s. c o m ctx.read(); } else { ByteBuf msg = in.readBytes(index); in.readBytes(NetconfMessageConstants.END_OF_MESSAGE.length); in.discardReadBytes(); logger.debug("Message is complete."); out.add(msg); } }
From source file:org.opendaylight.controller.netconf.util.handler.NetconfMessageAggregator.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { int index = indexOfSequence(in, eom); if (index == -1) { logger.debug("Message is not complete, read again."); ctx.read();//w ww . j a v a 2 s .c om } else { ByteBuf msg = in.readBytes(index); in.readBytes(eom.length); in.discardReadBytes(); logger.debug("Message is complete."); out.add(msg); } }
From source file:org.opendaylight.controller.netconf.util.handler.NetconfXMLToHelloMessageDecoder.java
License:Open Source License
@Override @VisibleForTesting/*from w w w . ja v a2s . c o m*/ public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() == 0) { LOG.debug("No more content in incoming buffer."); return; } in.markReaderIndex(); try { LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in)); byte[] bytes = new byte[in.readableBytes()]; in.readBytes(bytes); logMessage(bytes); // Extract bytes containing header with additional metadata String additionalHeader = null; if (startsWithAdditionalHeader(bytes)) { // Auth information containing username, ip address... extracted for monitoring int endOfAuthHeader = getAdditionalHeaderEndIndex(bytes); if (endOfAuthHeader > -1) { byte[] additionalHeaderBytes = Arrays.copyOfRange(bytes, 0, endOfAuthHeader + 2); additionalHeader = additionalHeaderToString(additionalHeaderBytes); bytes = Arrays.copyOfRange(bytes, endOfAuthHeader + 2, bytes.length); } } Document doc = XmlUtil.readXmlToDocument(new ByteArrayInputStream(bytes)); final NetconfMessage message; if (additionalHeader != null) { message = new NetconfHelloMessage(doc, NetconfHelloMessageAdditionalHeader.fromString(additionalHeader)); } else { message = new NetconfHelloMessage(doc); } out.add(message); } finally { in.discardReadBytes(); } }
From source file:org.opendaylight.netconf.nettyutil.handler.NetconfChunkAggregator.java
License:Open Source License
@Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws IllegalStateException { while (in.isReadable()) { switch (state) { case HEADER_ONE: { final byte b = in.readByte(); checkNewLine(b, "Malformed chunk header encountered (byte 0)"); state = State.HEADER_TWO; initChunk();/* www . j a v a 2 s. c o m*/ break; } case HEADER_TWO: { final byte b = in.readByte(); checkHash(b, "Malformed chunk header encountered (byte 1)"); state = State.HEADER_LENGTH_FIRST; break; } case HEADER_LENGTH_FIRST: { final byte b = in.readByte(); chunkSize = processHeaderLengthFirst(b); state = State.HEADER_LENGTH_OTHER; break; } case HEADER_LENGTH_OTHER: { final byte b = in.readByte(); if (b == '\n') { state = State.DATA; break; } if (b < '0' || b > '9') { LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM, b, (byte) '0', (byte) '9'); throw new IllegalStateException("Invalid chunk size encountered"); } chunkSize *= 10; chunkSize += b - '0'; checkChunkSize(); break; } case DATA: /* * FIXME: this gathers all data into one big chunk before passing * it on. Make sure the pipeline can work with partial data * and then change this piece to pass the data on as it * comes through. */ if (in.readableBytes() < chunkSize) { LOG.debug("Buffer has {} bytes, need {} to complete chunk", in.readableBytes(), chunkSize); in.discardReadBytes(); return; } aggregateChunks(in.readBytes((int) chunkSize)); state = State.FOOTER_ONE; break; case FOOTER_ONE: { final byte b = in.readByte(); checkNewLine(b, "Malformed chunk footer encountered (byte 0)"); state = State.FOOTER_TWO; chunkSize = 0; break; } case FOOTER_TWO: { final byte b = in.readByte(); checkHash(b, "Malformed chunk footer encountered (byte 1)"); state = State.FOOTER_THREE; break; } case FOOTER_THREE: { final byte b = in.readByte(); // In this state, either header-of-new-chunk or message-end is expected // Depends on the next character extractNewChunkOrMessageEnd(b); break; } case FOOTER_FOUR: { final byte b = in.readByte(); checkNewLine(b, "Malformed chunk footer encountered (byte 3)"); state = State.HEADER_ONE; out.add(chunk); chunk = null; break; } } } in.discardReadBytes(); }
From source file:org.opendaylight.netconf.nettyutil.handler.NetconfXMLToHelloMessageDecoder.java
License:Open Source License
@Override @VisibleForTesting/* www. j av a 2 s . co m*/ public void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws IOException, SAXException, NetconfDocumentedException { if (in.readableBytes() == 0) { LOG.debug("No more content in incoming buffer."); return; } in.markReaderIndex(); try { if (LOG.isTraceEnabled()) { LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in)); } byte[] bytes = new byte[in.readableBytes()]; in.readBytes(bytes); logMessage(bytes); // Extract bytes containing header with additional metadata String additionalHeader = null; if (startsWithAdditionalHeader(bytes)) { // Auth information containing username, ip address... extracted for monitoring int endOfAuthHeader = getAdditionalHeaderEndIndex(bytes); if (endOfAuthHeader > -1) { byte[] additionalHeaderBytes = Arrays.copyOfRange(bytes, 0, endOfAuthHeader); additionalHeader = additionalHeaderToString(additionalHeaderBytes); bytes = Arrays.copyOfRange(bytes, endOfAuthHeader, bytes.length); } } Document doc = XmlUtil.readXmlToDocument(new ByteArrayInputStream(bytes)); final NetconfMessage message = getNetconfMessage(additionalHeader, doc); if (message instanceof NetconfHelloMessage) { Preconditions.checkState(helloReceived == false, "Multiple hello messages received, unexpected hello: %s", message); out.add(message); helloReceived = true; // Non hello message, suspend the message and insert into cache } else { Preconditions.checkState(helloReceived, "Hello message not received, instead received: %s", message); LOG.debug("Netconf message received during negotiation, caching {}", message); nonHelloMessages.add(message); } } finally { in.discardReadBytes(); } }
From source file:org.opendaylight.protocol.pcep.impl.PCEPByteToMessageDecoder.java
License:Open Source License
@Override protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) { if (!in.isReadable()) { LOG.debug("No more content in incoming buffer."); return;// w ww . j a va 2s. c om } in.markReaderIndex(); LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in)); final List<Message> errors = new ArrayList<>(); try { out.add(parse(in, errors)); } catch (final PCEPDeserializerException e) { LOG.debug("Failed to decode protocol message", e); } in.discardReadBytes(); if (!errors.isEmpty()) { // We have a bunch of messages, send them out for (final Object e : errors) { ctx.channel().writeAndFlush(e).addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture f) { if (!f.isSuccess()) { LOG.warn("Failed to send message {} to socket {}", e, ctx.channel(), f.cause()); } else { LOG.trace("Message {} sent to socket {}", e, ctx.channel()); } } }); } } }
From source file:org.openremote.agent.protocol.velbus.VelbusPacketEncoderDecoder.java
License:Open Source License
public static void decode(ByteBuf buf, List<VelbusPacket> messages) { int startIndex = buf.indexOf(0, buf.capacity() - 1, VelbusPacket.STX); if (startIndex < 0) { return;//from ww w. j av a2 s . c o m } if (startIndex > 0) { buf.readerIndex(startIndex); buf.discardReadBytes(); } if (buf.readableBytes() < 4) { return; } int dataSize = buf.getByte(3); if (buf.readableBytes() < 6 + dataSize) { return; } // Find end of packet int endIndex = buf.indexOf(4 + dataSize, MAX_PACKET_SIZE, VelbusPacket.ETX); if (endIndex < 0) { if (buf.readableBytes() > MAX_PACKET_SIZE) { buf.readerIndex(MAX_PACKET_SIZE); buf.discardReadBytes(); } return; } byte[] packetBytes = new byte[endIndex + 1]; buf.readBytes(packetBytes); buf.discardReadBytes(); VelbusPacket packet = new VelbusPacket(packetBytes); if (packet.isValid()) { messages.add(packet); } }
From source file:org.spout.api.protocol.ByteBufferChannelProcessorTest.java
License:Open Source License
@Test public void randomPassthrough() { mainThread = Thread.currentThread(); ByteBuf buffer = Unpooled.buffer(2048); ChannelHandlerContext ctx = ChannelHandlerContextFaker.setup(); ByteBufferChannelProcessor processor = new ByteBufferChannelProcessor(256); byte[] input = new byte[LENGTH]; byte[] output = new byte[LENGTH]; Random r = new Random(); for (int i = 0; i < input.length; i++) { input[i] = (byte) (r.nextInt()); }//from www. jav a 2 s .c om int writePointer = 0; int readPointer = 0; int pass = 0; while (writePointer < LENGTH && (pass++) < 512) { int toWrite = r.nextInt(512); if (r.nextInt(10) == 0) { // simulate "large" packets toWrite *= 10; } if (toWrite > buffer.writableBytes()) { toWrite = buffer.writableBytes(); } if (toWrite > LENGTH - writePointer) { toWrite = LENGTH - writePointer; } System.out.println("Writing block of size " + toWrite); buffer.writeBytes(input, writePointer, toWrite); writePointer += toWrite; ByteBuf outputBuffer = processor.write(ctx, buffer); buffer.discardReadBytes(); while (outputBuffer.isReadable()) { int toRead = r.nextInt(768); if (toRead > outputBuffer.readableBytes()) { toRead = outputBuffer.readableBytes(); } System.out.println("ToRead: " + toRead + " of " + outputBuffer.readableBytes()); outputBuffer.readBytes(output, readPointer, toRead); readPointer += toRead; outputBuffer.discardReadBytes(); } outputBuffer.release(); } buffer.release(); for (int i = 0; i < input.length; i++) { assertTrue("Mismatch at position " + i, input[i] == output[i]); } }