Captures the last received metadata on a channel. Useful for testing.

@param headersCapture to record the last received headers
@param trailersCapture to record the last received trailers
@return an implementation of the channel with captures installed.
491638
public static ClientInterceptor newCaptureMetadataInterceptor(
      AtomicReference<Metadata> headersCapture, AtomicReference<Metadata> trailersCapture) {
    return new MetadataCapturingClientInterceptor(headersCapture, trailersCapture);
  }
21437
public IoBuffer encodeHeader(Header header, Header lastHeader) {
        final IoBuffer result = IoBuffer.allocate(calculateHeaderSize(header, lastHeader));
        encodeHeader(header, lastHeader, result);
        return result;
    }
115783
public Content getSummaryTableHeader(String[] header, String scope) {
        Content tr = new HtmlTree(HtmlTag.TR);
        int size = header.length;
        Content tableHeader;
        if (size == 1) {
            tableHeader = new StringContent(header[0]);
            tr.addContent(HtmlTree.TH(HtmlStyle.colOne, scope, tableHeader));
            return tr;
        }
        for (int i = 0; i < size; i++) {
            tableHeader = new StringContent(header[i]);
            if(i == 0)
                tr.addContent(HtmlTree.TH(HtmlStyle.colFirst, scope, tableHeader));
            else if(i == (size - 1))
                tr.addContent(HtmlTree.TH(HtmlStyle.colLast, scope, tableHeader));
            else
                tr.addContent(HtmlTree.TH(scope, tableHeader));
        }
        return tr;
    }
1165294
@Override
    public List<String> getTrailerNames() {
        HttpTrailers trailers = message.getTrailers();
        if (trailers != null)
            return trailers.getAllHeaderNames();
        else
            return null;

    }
925175
public static void addMementoDatetimeHeader(HttpServletResponse response,
			CaptureSearchResult result) {
		response.setHeader(MEMENTO_DATETIME, formatLinkDate(result.getCaptureDate()));
	}
548231
public Content getSerializedSummariesHeader() {
        HtmlTree ul = new HtmlTree(HtmlTag.UL);
        ul.addStyle(HtmlStyle.blockList);
        return ul;
    }
418345
private SnapshotCodec getCurrentCodec() {
    if (codecs.isEmpty()) {
      throw new IllegalStateException(String.format("No codecs are registered."));
    }
    return codecs.get(codecs.lastKey());
  }
162603
function getLiveStream(options) {
    return raspivid(Object.assign({
        width: 960,
        height: 540,
        framerate: 20,
        profile: 'baseline',
        timeout: 0
    }, options))
    .pipe(new Splitter(NALseparator))
    .pipe(new stream.Transform({ transform: function (chunk, encoding, callback) {
        const chunkWithSeparator = Buffer.concat([NALseparator, chunk]);

        const chunkType = chunk[0] & 0b11111;

        // Capture the first SPS & PPS frames, so we can send stream parameters on connect.
        if (chunkType === 7 || chunkType === 8) {
            headerData.addParameterFrame(chunkWithSeparator);
        } else {
            // The live stream only includes the non-parameter chunks
            this.push(chunkWithSeparator);

            // Keep track of the latest IDR chunk, so we can start clients off with a near-current image
            if (chunkType === 5) {
                headerData.idrFrame = chunkWithSeparator;
            }
        }

        callback();
    }}));
}
372263
void read_header(Bitstream stream, Crc16[] crcp) throws BitstreamException
	{
		int headerstring;
		int channel_bitrate;
		boolean sync = false;
		do
		{
			headerstring = stream.syncHeader(syncmode);
			_headerstring = headerstring; // E.B
			if (syncmode == Bitstream.INITIAL_SYNC)
			{
				h_version = ((headerstring >>> 19) & 1);
				if (((headerstring >>> 20) & 1) == 0) // SZD: MPEG2.5 detection
					if (h_version == MPEG2_LSF)
						h_version = MPEG25_LSF;
					else
						throw stream.newBitstreamException(Bitstream.UNKNOWN_ERROR);
				if ((h_sample_frequency = ((headerstring >>> 10) & 3)) == 3)
				{
					throw stream.newBitstreamException(Bitstream.UNKNOWN_ERROR);
				}
			}
			h_layer = 4 - (headerstring >>> 17) & 3;
			h_protection_bit = (headerstring >>> 16) & 1;
			h_bitrate_index = (headerstring >>> 12) & 0xF;
			h_padding_bit = (headerstring >>> 9) & 1;
			h_mode = ((headerstring >>> 6) & 3);
			h_mode_extension = (headerstring >>> 4) & 3;
			if (h_mode == JOINT_STEREO)
				h_intensity_stereo_bound = (h_mode_extension << 2) + 4;
			else
				h_intensity_stereo_bound = 0; // should never be used
			if (((headerstring >>> 3) & 1) == 1)
				h_copyright = true;
			if (((headerstring >>> 2) & 1) == 1)
				h_original = true;
			// calculate number of subbands:
			if (h_layer == 1)
				h_number_of_subbands = 32;
			else
			{
				channel_bitrate = h_bitrate_index;
				// calculate bitrate per channel:
				if (h_mode != SINGLE_CHANNEL)
					if (channel_bitrate == 4)
						channel_bitrate = 1;
					else
						channel_bitrate -= 4;
				if ((channel_bitrate == 1) || (channel_bitrate == 2))
					if (h_sample_frequency == THIRTYTWO)
						h_number_of_subbands = 12;
					else
						h_number_of_subbands = 8;
				else if ((h_sample_frequency == FOURTYEIGHT) || ((channel_bitrate >= 3) && (channel_bitrate <= 5)))
					h_number_of_subbands = 27;
				else
					h_number_of_subbands = 30;
			}
			if (h_intensity_stereo_bound > h_number_of_subbands)
				h_intensity_stereo_bound = h_number_of_subbands;
			// calculate framesize and nSlots
			calculate_framesize();
			// read framedata:
			int framesizeloaded = stream.read_frame_data(framesize);
			if ((framesize >=0) && (framesizeloaded != framesize))
			{
				// Data loaded does not match to expected framesize,
				// it might be an ID3v1 TAG. (Fix 11/17/04).
				throw stream.newBitstreamException(Bitstream.INVALIDFRAME);
			}
			if (stream.isSyncCurrentPosition(syncmode))
			{
				if (syncmode == Bitstream.INITIAL_SYNC)
				{
					syncmode = Bitstream.STRICT_SYNC;
					stream.set_syncword(headerstring & 0xFFF80CC0);
				}
				sync = true;
			}
			else
			{
				stream.unreadFrame();
			}
		}
		while (!sync);
		stream.parse_frame();
		if (h_protection_bit == 0)
		{
			// frame contains a crc checksum
			checksum = (short) stream.get_bits(16);
			if (crc == null)
				crc = new Crc16();
			crc.add_bits(headerstring, 16);
			crcp[0] = crc;
		}
		else
			crcp[0] = null;
		
//		if (h_sample_frequency == FOURTYFOUR_POINT_ONE)
//		{
//			if (offset == null)
//			{
//				int max = max_number_of_frames(stream);
//				offset = new int[max];
//				for (int i = 0; i < max; i++)
//					offset[i] = 0;
//			}
//			// E.B : Investigate more
//			int cf = stream.current_frame();
//			int lf = stream.last_frame();
//			if ((cf > 0) && (cf == lf))
//			{
//				offset[cf] = offset[cf - 1] + h_padding_bit;
//			}
//			else
//			{
//				offset[0] = h_padding_bit;
//			}
//		}
	}
521777
public Header decodeHeader(ChunkHeader chh, RTMPDecodeState state, IoBuffer in, RTMP rtmp) {
        //if (log.isTraceEnabled()) {
            //log.trace("decodeHeader - chh: {} input: {}", chh, Hex.encodeHexString(Arrays.copyOfRange(in.array(), in.position(), in.limit())));
            //log.trace("decodeHeader - chh: {}", chh);
        //}
        final int channelId = chh.getChannelId();
        // identifies the header type of the four types
        final byte headerSize = chh.getFormat();
        Header lastHeader = rtmp.getLastReadHeader(channelId);
        if (log.isTraceEnabled()) {
            log.trace("{} lastHeader: {}", Header.HeaderType.values()[headerSize], lastHeader);
        }
        // got a non-new header for a channel which has no last-read header
        if (headerSize != HEADER_NEW && lastHeader == null) {
            String detail = String.format("Last header null: %s, channelId %s", Header.HeaderType.values()[headerSize], channelId);
            log.debug("{}", detail);
            // if the op prefers to exit or kill the connection, we should allow based on configuration param
            if (closeOnHeaderError) {
                // this will trigger an error status, which in turn will disconnect the "offending" flash player
                // preventing a memory leak and bringing the whole server to its knees
                throw new ProtocolException(detail);
            } else {
                // we need to skip the current channel data and continue until a new header is sent
                return null;
            }
        }
        int headerLength = RTMPUtils.getHeaderLength(headerSize);
        headerLength += chh.getSize() - 1;
//        if (log.isTraceEnabled()) {
//            log.trace("headerLength: {}", headerLength);
//        }
        if (in.remaining() < headerLength) {
            //log.trace("Header too small (hlen: {}), buffering. remaining: {}", headerLength, remaining);
            state.bufferDecoding(headerLength);
            return null;
        }
        int timeBase = 0, timeDelta = 0;
        Header header = new Header();
        header.setChannelId(channelId);
        switch (headerSize) {
            case HEADER_NEW: // type 0
                // an absolute time value
                timeBase = RTMPUtils.readUnsignedMediumInt(in);
                header.setSize(RTMPUtils.readUnsignedMediumInt(in));
                header.setDataType(in.get());
                header.setStreamId(RTMPUtils.readReverseInt(in));
                // read the extended timestamp if we have the indication that it exists
                if (timeBase >= MEDIUM_INT_MAX) {
                    long ext = in.getUnsignedInt();
                    timeBase = (int) (ext ^ (ext >>> 32));
                    if (log.isTraceEnabled()) {
                        log.trace("Extended time read: {}", timeBase);
                    }
                    header.setExtended(true);
                }
                header.setTimerBase(timeBase);
                header.setTimerDelta(timeDelta);
                break;
            case HEADER_SAME_SOURCE: // type 1
                // time base from last header
                timeBase = lastHeader.getTimerBase();
                // a delta time value
                timeDelta = RTMPUtils.readUnsignedMediumInt(in);
                header.setSize(RTMPUtils.readUnsignedMediumInt(in));
                header.setDataType(in.get());
                header.setStreamId(lastHeader.getStreamId());
                // read the extended timestamp if we have the indication that it exists
                if (timeDelta >= MEDIUM_INT_MAX) {
                    long ext = in.getUnsignedInt();
                    timeDelta = (int) (ext ^ (ext >>> 32));
                    header.setExtended(true);
                }
                header.setTimerBase(timeBase);
                header.setTimerDelta(timeDelta);
                break;
            case HEADER_TIMER_CHANGE: // type 2
                // time base from last header
                timeBase = lastHeader.getTimerBase();
                // a delta time value
                timeDelta = RTMPUtils.readUnsignedMediumInt(in);
                header.setSize(lastHeader.getSize());
                header.setDataType(lastHeader.getDataType());
                header.setStreamId(lastHeader.getStreamId());
                // read the extended timestamp if we have the indication that it exists
                if (timeDelta >= MEDIUM_INT_MAX) {
                    long ext = in.getUnsignedInt();
                    timeDelta = (int) (ext ^ (ext >>> 32));
                    header.setExtended(true);
                }
                header.setTimerBase(timeBase);
                header.setTimerDelta(timeDelta);
                break;
            case HEADER_CONTINUE: // type 3
                // time base from last header
                timeBase = lastHeader.getTimerBase();
                timeDelta = lastHeader.getTimerDelta();
                header.setSize(lastHeader.getSize());
                header.setDataType(lastHeader.getDataType());
                header.setStreamId(lastHeader.getStreamId());
                // read the extended timestamp if we have the indication that it exists
                // This field is present in Type 3 chunks when the most recent Type 0, 1, or 2 chunk for the same chunk stream ID
                // indicated the presence of an extended timestamp field
                if (lastHeader.isExtended()) {
                    long ext = in.getUnsignedInt();
                    int timeExt = (int) (ext ^ (ext >>> 32));
                    if (log.isTraceEnabled()) {
                        log.trace("Extended time read: {} {}", ext, timeExt);
                    }
                    timeBase = timeExt;
                    header.setExtended(true);
                }
                header.setTimerBase(timeBase);
                header.setTimerDelta(timeDelta);
                break;
            default:
                throw new ProtocolException(String.format("Unexpected header: %s", headerSize));
        }
        log.trace("Decoded chunk {} {}", Header.HeaderType.values()[headerSize], header);
        return header;
    }
1362708
protected void transportTrailersReceived(Metadata trailers) {
    Preconditions.checkNotNull(trailers, "trailers");
    if (transportError == null && !headersReceived) {
      transportError = validateInitialMetadata(trailers);
      if (transportError != null) {
        transportErrorMetadata = trailers;
      }
    }
    if (transportError != null) {
      transportError = transportError.augmentDescription("trailers: " + trailers);
      http2ProcessingFailed(transportError, false, transportErrorMetadata);
    } else {
      Status status = statusFromTrailers(trailers);
      stripTransportDetails(trailers);
      inboundTrailersReceived(trailers, status);
    }
  }
1151831
@GetMapping(path = WSFederationConstants.ENDPOINT_FEDERATION_METADATA)
    public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        try {
            response.setContentType(MediaType.TEXT_HTML_VALUE);
            val out = response.getWriter();
            val metadata = WSFederationMetadataWriter.produceMetadataDocument(casProperties);
            out.write(DOM2Writer.nodeToString(metadata));
        } catch (final Exception ex) {
            LOGGER.error("Failed to get metadata document", ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
793555
protected B codec(Http2ConnectionDecoder decoder, Http2ConnectionEncoder encoder) {
        enforceConstraint("codec", "server", isServer);
        enforceConstraint("codec", "maxReservedStreams", maxReservedStreams);
        enforceConstraint("codec", "connection", connection);
        enforceConstraint("codec", "frameLogger", frameLogger);
        enforceConstraint("codec", "validateHeaders", validateHeaders);
        enforceConstraint("codec", "headerSensitivityDetector", headerSensitivityDetector);
        enforceConstraint("codec", "encoderEnforceMaxConcurrentStreams", encoderEnforceMaxConcurrentStreams);

        checkNotNull(decoder, "decoder");
        checkNotNull(encoder, "encoder");

        if (decoder.connection() != encoder.connection()) {
            throw new IllegalArgumentException("The specified encoder and decoder have different connections.");
        }

        this.decoder = decoder;
        this.encoder = encoder;

        return self();
    }
192505
private ChannelFuture writeContinuationFrames(ChannelHandlerContext ctx, int streamId,
            ByteBuf headerBlock, int padding, SimpleChannelPromiseAggregator promiseAggregator) {
        Http2Flags flags = new Http2Flags().paddingPresent(padding > 0);
        int maxFragmentLength = maxFrameSize - padding;
        // TODO: same padding is applied to all frames, is this desired?
        if (maxFragmentLength <= 0) {
            return promiseAggregator.setFailure(new IllegalArgumentException(
                    "Padding [" + padding + "] is too large for max frame size [" + maxFrameSize + "]"));
        }

        if (headerBlock.isReadable()) {
            // The frame header (and padding) only changes on the last frame, so allocate it once and re-use
            int fragmentReadableBytes = min(headerBlock.readableBytes(), maxFragmentLength);
            int payloadLength = fragmentReadableBytes + padding;
            ByteBuf buf = ctx.alloc().buffer(CONTINUATION_FRAME_HEADER_LENGTH);
            writeFrameHeaderInternal(buf, payloadLength, CONTINUATION, flags, streamId);
            writePaddingLength(buf, padding);

            do {
                fragmentReadableBytes = min(headerBlock.readableBytes(), maxFragmentLength);
                ByteBuf fragment = headerBlock.readRetainedSlice(fragmentReadableBytes);

                payloadLength = fragmentReadableBytes + padding;
                if (headerBlock.isReadable()) {
                    ctx.write(buf.retain(), promiseAggregator.newPromise());
                } else {
                    // The frame header is different for the last frame, so re-allocate and release the old buffer
                    flags = flags.endOfHeaders(true);
                    buf.release();
                    buf = ctx.alloc().buffer(CONTINUATION_FRAME_HEADER_LENGTH);
                    writeFrameHeaderInternal(buf, payloadLength, CONTINUATION, flags, streamId);
                    writePaddingLength(buf, padding);
                    ctx.write(buf, promiseAggregator.newPromise());
                }

                ctx.write(fragment, promiseAggregator.newPromise());

                // Write out the padding, if any.
                if (paddingBytes(padding) > 0) {
                    ctx.write(ZERO_BUFFER.slice(0, paddingBytes(padding)), promiseAggregator.newPromise());
                }
            } while (headerBlock.isReadable());
        }
        return promiseAggregator;
    }
1340267
void receiveHeaders(Headers headers, boolean inFinished) {
    assert (!Thread.holdsLock(Http2Stream.this));
    boolean open;
    synchronized (this) {
      if (!hasResponseHeaders || !inFinished) {
        hasResponseHeaders = true;
        headersQueue.add(headers);
      } else {
        this.source.trailers = headers;
      }
      if (inFinished) {
        this.source.finished = true;
      }
      open = isOpen();
      notifyAll();
    }
    if (!open) {
      connection.removeStream(id);
    }
  }
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;	
	}
1282874
@Override
    public RequestContent getRequestContent(HttpServletRequest request,
                                            HttpHeaders headers)
        throws Exception {
        RequestContent rContent = null;

        // See if the request is a multi-part file upload request
        if (ServletFileUpload.isMultipartContent(request)) {

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload();

            // Parse the request, use the first available File item
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                if (!item.isFormField()) {
                    rContent = new RequestContent();
                    rContent.contentStream = item.openStream();
                    rContent.mimeType = item.getContentType();

                    FileItemHeaders itemHeaders = item.getHeaders();
                    if (itemHeaders != null) {
                        String contentLength =
                            itemHeaders.getHeader("Content-Length");
                        if (contentLength != null) {
                            rContent.size = Long.parseLong(contentLength);
                        }
                    }

                    break;
                }
            }
        } else {
            // If the content stream was not found as a multipart,
            // try to use the stream from the request directly
            rContent = new RequestContent();
            rContent.contentStream = request.getInputStream();
            if (request.getContentLength() >= 0) {
                rContent.size = request.getContentLength();
            }
        }

        // Attempt to set the mime type and size if not already set
        if (rContent != null) {
            if (rContent.mimeType == null) {
                MediaType mediaType = headers.getMediaType();
                if (mediaType != null) {
                    rContent.mimeType = mediaType.toString();
                }
            }

            if (rContent.size == 0) {
                List<String> lengthHeaders =
                    headers.getRequestHeader("Content-Length");
                if (lengthHeaders != null && lengthHeaders.size() > 0) {
                    rContent.size = Long.parseLong(lengthHeaders.get(0));
                }
            }
        }

        return rContent;
    }