Decode buffers.

@param dataBuffer the buffer of the data (payload)
@param headersBuffer the buffer of the headers
@return a new Service message with {@link ByteBuf} data and with parsed headers.
@throws MessageCodecException when decode fails
496992
public ServiceMessage decode(ByteBuf dataBuffer, ByteBuf headersBuffer)
      throws MessageCodecException {
    ServiceMessage.Builder builder = ServiceMessage.builder();

    if (dataBuffer.isReadable()) {
      builder.data(dataBuffer);
    }
    if (headersBuffer.isReadable()) {
      try (ByteBufInputStream stream = new ByteBufInputStream(headersBuffer, true)) {
        builder.headers(headersCodec.decode(stream));
      } catch (Throwable ex) {
        ReferenceCountUtil.safestRelease(dataBuffer); // release data buf as well
        throw new MessageCodecException("Failed to decode message headers", ex);
      }
    }

    return builder.build();
  }
1356002
private static Result<?> decodeVariableHeader(ByteBuf buffer, MqttFixedHeader mqttFixedHeader) {
        switch (mqttFixedHeader.messageType()) {
            case CONNECT:
                return decodeConnectionVariableHeader(buffer);

            case CONNACK:
                return decodeConnAckVariableHeader(buffer);

            case SUBSCRIBE:
            case UNSUBSCRIBE:
            case SUBACK:
            case UNSUBACK:
            case PUBACK:
            case PUBREC:
            case PUBCOMP:
            case PUBREL:
                return decodeMessageIdVariableHeader(buffer);

            case PUBLISH:
                return decodePublishVariableHeader(buffer, mqttFixedHeader);

            case PINGREQ:
            case PINGRESP:
            case DISCONNECT:
                // Empty variable header
                return new Result<Object>(null, 0);
        }
        return new Result<Object>(null, 0); //should never reach here
    }
1243622
public static IntCountsHistogram decodeFromByteBuffer(final ByteBuffer buffer,
                                                    final long minBarForHighestTrackableValue) {
        return (IntCountsHistogram) decodeFromByteBuffer(buffer, IntCountsHistogram.class,
                minBarForHighestTrackableValue);
    }
363422
@Benchmark
  @BenchmarkMode(Mode.SampleTime)
  @OutputTimeUnit(TimeUnit.NANOSECONDS)
  public ByteBuf encodeClientHeaders() throws Exception {
    scratchBuffer.clear();
    Http2Headers headers =
        Utils.convertClientHeaders(metadata, scheme, defaultPath, authority, Utils.HTTP_METHOD,
            userAgent);
    headersEncoder.encodeHeaders(1, headers, scratchBuffer);
    return scratchBuffer;
  }
672400
public Obuffer decodeFrame(Header header, Bitstream stream)
		throws DecoderException
	{
		try
		{
			if (!initialized)
			{
				initialize(header);
			}
			
			int layer = header.layer();
			
			output.clear_buffer();
			
			FrameDecoder decoder = retrieveDecoder(header, stream, layer);
			
			decoder.decodeFrame();
					
			output.write_buffer(1);
		}
		catch (RuntimeException ex)
		{
			// UUPS - this frame seems to be corrupt - let's continue to the next one
		}
		
		return output;	
	}
976989
public static ByteBuf toByteBuf(ChannelHandlerContext ctx, Throwable cause) {
        if (cause == null || cause.getMessage() == null) {
            return Unpooled.EMPTY_BUFFER;
        }

        return ByteBufUtil.writeUtf8(ctx.alloc(), cause.getMessage());
    }
743729
protected void clientMessageHandler(DirectBuffer buffer, int offset, int length, Header header) {
        /**
         *  All incoming messages here are supposed to be "just messages", only unicast communication
         *  All of them should implement MeaningfulMessage interface
         */
        // TODO: to be implemented
        //  log.info("clientMessageHandler message request incoming");

        byte[] data = new byte[length];
        buffer.getBytes(offset, data);

        MeaningfulMessage message = (MeaningfulMessage) VoidMessage.fromBytes(data);
        completed.put(message.getTaskId(), message);
    }
608319
public static void storeBuffer(ByteBuf buf, Object message, RequestContext ctx) {
        IdentityHashMap<Object, ByteBuf> buffers = ctx.attr(BUFFERS).get();
        if (buffers == null) {
            buffers = new IdentityHashMap<>();
            ctx.attr(BUFFERS).set(buffers);
        }
        buffers.put(message, buf);
    }
126591
public void decode(int streamId, ByteBuf in, Http2Headers headers, boolean validateHeaders) throws Http2Exception {
        Http2HeadersSink sink = new Http2HeadersSink(streamId, headers, maxHeaderListSize, validateHeaders);
        decode(in, sink);

        // Now that we've read all of our headers we can perform the validation steps. We must
        // delay throwing until this point to prevent dynamic table corruption.
        sink.finish();
    }
240986
private void receiveMessage(ClientSocket client, DataInputStream buffer, byte from, StateConnection expected)
            throws IOException
    {
        if (ServerImpl.checkValidity(client, from, expected))
        {
            final byte dest = buffer.readByte();
            final byte type = buffer.readByte();
            final int size = buffer.readInt();
            if (size > 0)
            {
                final byte[] clientData = new byte[size];
                if (buffer.read(clientData) != -1) // CHECKSTYLE IGNORE LINE: TrailingComment|NestedIfDepth
                {
                    final DataInputStream clientBuffer = new DataInputStream(new ByteArrayInputStream(clientData));
                    decodeMessage(type, from, dest, clientBuffer);
                }
            }
            final int headerSize = 4;
            bandwidth += headerSize + size;
        }
    }
372140
public static Histogram decodeFromByteBuffer(final ByteBuffer buffer,
                                                 final long minBarForHighestTrackableValue) {
        return (Histogram) decodeFromByteBuffer(buffer, Histogram.class, minBarForHighestTrackableValue);
    }
601078
@Override
    public int decode ( byte[] buffer, int bufferIndex, int len ) throws SMBProtocolDecodingException {
        int start = bufferIndex;

        this.capabilities = SMBUtil.readInt4(buffer, bufferIndex);
        bufferIndex += 4;

        System.arraycopy(buffer, bufferIndex, this.serverGuid, 0, 16);
        bufferIndex += 16;

        this.securityMode = SMBUtil.readInt2(buffer, bufferIndex);
        this.dialect = SMBUtil.readInt2(buffer, bufferIndex + 2);
        bufferIndex += 4;

        return bufferIndex - start;
    }
603882
public static H2HeaderField decodeHeader(WsByteBuffer buffer, H2HeaderTable table, boolean isFirstHeader,
                                             boolean isTrailerBlock, H2ConnectionSettings settings) throws CompressionException {

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.entry(tc, "decodeHeader");
        }

        if (!table.isDynamicTableValid()) {
            throw new CompressionException("The context for this dynamic table is not valid.");
        }

        if (buffer == null || !buffer.hasRemaining()) {
            throw new CompressionException("Invalid attempt to decode empty or null buffer.");
        }

        //Get first byte for header being decoded
        byte currentByte = buffer.get();
        buffer.position(buffer.position() - 1);
        //Format this instruction byte so that 4 LSB are set to '1',
        //allowing for quick assessment of what instruction this byte
        //contains.
        byte maskedByte = HpackUtils.format(currentByte, HpackConstants.MASK_0F);

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Operation Byte: " + HpackUtils.byteToHexString(currentByte));
        }

        int decodedInteger = 0;
        H2HeaderField header = null;

        //If the MSB is 1, the masked byte will be negative since this is
        //a signed byte.
        if (maskedByte < HpackConstants.MASK_00) {

            //Check against the byte '1000000' as the index value of 0
            //for indexed headers is not used and MUST be treated as a
            //decoding error.
            if (currentByte == HpackConstants.MASK_80) {
                throw new CompressionException("An indexed header cannot have an index of 0");
            }
            //Look for the corresponding integer representation - each byte for
            //the integer representation decoder, for this case, has N = 7.

            decodedInteger = IntegerRepresentation.decode(buffer, ByteFormatType.INDEXED);

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Operation byte indicated header is already indexed at index location: " + decodedInteger +
                             ". Searching table...");
            }

            //Get both header name and value using the given index location.

            header = table.getHeaderEntry(decodedInteger);

            if (header == null) {
                throw new CompressionException("Received an invalid header index");
            }
            checkIsValidH2Header(header, isTrailerBlock);

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Found header: [" + header.getName() + ", " + header.getValue() + "]");
            }

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.exit(tc, "decodeHeader");
            }
            return header;
        }

        //Not currently index - verify literal index type and handle
        //accordingly. There are three types of possible encodings for a <HeaderField>.
        //Bits 7, 6, and 5 will tell us what type of encoding this is. There is
        //also the possibility of a table update command.
        else {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Header not fully indexed in table, determining indexing type.");
            }

            /*
             * If bit 7 is '1', then this LiteralIndexType.INCREMENTAL
             *
             * Literal Header Field with Incremental Indexing
             * +---+---+---+---+---+---+---+---+
             * | 0 | 1 | Index (6+) ---------- |
             * +---+---+-----------------------+
             */
            if (maskedByte >= HpackConstants.MASK_4F) {

                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Indexing decode type: INCREMENTAL");
                }

                header = decodeHeader(buffer, table, ByteFormatType.INCREMENTAL);

            } else if (maskedByte >= HpackConstants.MASK_2F) {
                if (!isFirstHeader) {
                    throw new CompressionException("dynamic table size update must occur at the beginning of the first header block");
                }

                int fragmentLength = IntegerRepresentation.decode(buffer, ByteFormatType.TABLE_UPDATE);
                if (settings != null && fragmentLength > settings.getHeaderTableSize()) {
                    throw new CompressionException("dynamic table size update size was larger than SETTINGS_HEADER_TABLE_SIZE");
                }
                table.updateTableSize(fragmentLength);

                return null;
            }

            /*
             * Bit 7 is '0' & bits 6-5 match '01', then this is
             * LiteralIndexType.NEVERINDEX
             */
            else if (maskedByte == HpackConstants.MASK_1F) {

                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Indexing decode type: NEVERINDEX");
                }

                header = decodeHeader(buffer, table, ByteFormatType.NEVERINDEX);

            }

            /*
             * Bit 7 is '0' & bits 6-5 match '00', then this is
             * LiteralIndexType.NOINDEXING
             */
            else if (maskedByte == HpackConstants.MASK_0F) {

                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Indexing decode type: NOINDEXING");
                }

                header = decodeHeader(buffer, table, ByteFormatType.NOINDEXING);

            }

        }

        checkIsValidH2Header(header, isTrailerBlock);

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "Decoded the header: [" + header.getName() + ", " + header.getValue() + "]");
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.exit(tc, "decodeHeader");
        }

        return header;

    }
461207
String decodeCString(ByteBuf buffer) throws IOException {
        int length = buffer.bytesBefore(BsonConstants.STRING_TERMINATION);
        if (length < 0)
            throw new IOException("string termination not found");

        String result = buffer.toString(buffer.readerIndex(), length, StandardCharsets.UTF_8);
        buffer.skipBytes(length + 1);
        return result;
    }
1255749
public byte decodeBuffer(InputStream in)[] throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        decodeBuffer(in, outStream);
        return (outStream.toByteArray());
    }
184078
private static MqttFixedHeader decodeFixedHeader(ByteBuf buffer) {
        short b1 = buffer.readUnsignedByte();

        MqttMessageType messageType = MqttMessageType.valueOf(b1 >> 4);
        boolean dupFlag = (b1 & 0x08) == 0x08;
        int qosLevel = (b1 & 0x06) >> 1;
        boolean retain = (b1 & 0x01) != 0;

        int remainingLength = 0;
        int multiplier = 1;
        short digit;
        int loops = 0;
        do {
            digit = buffer.readUnsignedByte();
            remainingLength += (digit & 127) * multiplier;
            multiplier *= 128;
            loops++;
        } while ((digit & 128) != 0 && loops < 4);

        // MQTT protocol limits Remaining Length to 4 bytes
        if (loops == 4 && (digit & 128) != 0) {
            throw new DecoderException("remaining length exceeds 4 digits (" + messageType + ')');
        }
        MqttFixedHeader decodedFixedHeader =
                new MqttFixedHeader(messageType, dupFlag, MqttQoS.valueOf(qosLevel), retain, remainingLength);
        return validateFixedHeader(resetUnusedFields(decodedFixedHeader));
    }
275817
static ByteBuf doEncode(ByteBufAllocator byteBufAllocator, MqttMessage message) {

        switch (message.fixedHeader().messageType()) {
            case CONNECT:
                return encodeConnectMessage(byteBufAllocator, (MqttConnectMessage) message);

            case CONNACK:
                return encodeConnAckMessage(byteBufAllocator, (MqttConnAckMessage) message);

            case PUBLISH:
                return encodePublishMessage(byteBufAllocator, (MqttPublishMessage) message);

            case SUBSCRIBE:
                return encodeSubscribeMessage(byteBufAllocator, (MqttSubscribeMessage) message);

            case UNSUBSCRIBE:
                return encodeUnsubscribeMessage(byteBufAllocator, (MqttUnsubscribeMessage) message);

            case SUBACK:
                return encodeSubAckMessage(byteBufAllocator, (MqttSubAckMessage) message);

            case UNSUBACK:
            case PUBACK:
            case PUBREC:
            case PUBREL:
            case PUBCOMP:
                return encodeMessageWithOnlySingleByteFixedHeaderAndMessageId(byteBufAllocator, message);

            case PINGREQ:
            case PINGRESP:
            case DISCONNECT:
                return encodeMessageWithOnlySingleByteFixedHeader(byteBufAllocator, message);

            default:
                throw new IllegalArgumentException(
                        "Unknown message type: " + message.fixedHeader().messageType().value());
        }
    }