List of usage examples for io.netty.handler.codec.http2 Http2Headers size
int size();
From source file:com.linecorp.armeria.internal.ArmeriaHttpUtil.java
License:Apache License
/** * Converts the specified Netty HTTP/2 into Armeria HTTP/2 headers. *//*from w w w. ja v a2 s .co m*/ public static HttpHeaders toArmeria(Http2Headers headers) { final HttpHeaders converted = new DefaultHttpHeaders(false, headers.size()); StringJoiner cookieJoiner = null; for (Entry<CharSequence, CharSequence> e : headers) { final AsciiString name = AsciiString.of(e.getKey()); final CharSequence value = e.getValue(); // Cookies must be concatenated into a single octet string. // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 if (name.equals(HttpHeaderNames.COOKIE)) { if (cookieJoiner == null) { cookieJoiner = new StringJoiner(COOKIE_SEPARATOR); } COOKIE_SPLITTER.split(value).forEach(cookieJoiner::add); } else { converted.add(name, convertHeaderValue(name, value)); } } if (cookieJoiner != null && cookieJoiner.length() != 0) { converted.add(HttpHeaderNames.COOKIE, cookieJoiner.toString()); } return converted; }
From source file:com.linecorp.armeria.internal.http.ArmeriaHttpUtil.java
License:Apache License
public static HttpHeaders toArmeria(Http2Headers headers) { final HttpHeaders converted = new DefaultHttpHeaders(false, headers.size()); for (Entry<CharSequence, CharSequence> e : headers) { converted.add(AsciiString.of(e.getKey()), e.getValue().toString()); }//from w w w. j av a 2 s. co m return converted; }
From source file:com.linkedin.r2.transport.http.client.Http2FrameListener.java
License:Apache License
@Override public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding, boolean endOfStream) throws Http2Exception { LOG.debug("Received HTTP/2 HEADERS frame, stream={}, end={}, headers={}, padding={}bytes", new Object[] { streamId, endOfStream, headers.size(), padding }); // Ignores response for the upgrade request if (streamId == Http2CodecUtil.HTTP_UPGRADE_STREAM_ID) { return;/*from ww w . j av a2s . c o m*/ } final StreamResponseBuilder builder = new StreamResponseBuilder(); // Process HTTP/2 pseudo headers if (headers.status() != null) { builder.setStatus(Integer.parseInt(headers.status().toString())); } if (headers.authority() != null) { builder.addHeaderValue(HttpHeaderNames.HOST.toString(), headers.authority().toString()); } // Process other HTTP headers for (Map.Entry<CharSequence, CharSequence> header : headers) { if (Http2Headers.PseudoHeaderName.isPseudoHeader(header.getKey())) { // Do no set HTTP/2 pseudo headers to response continue; } final String key = header.getKey().toString(); final String value = header.getValue().toString(); if (key.equalsIgnoreCase(HttpConstants.RESPONSE_COOKIE_HEADER_NAME)) { builder.addCookie(value); } else { builder.unsafeAddHeaderValue(key, value); } } // Gets async pool handle from stream properties Http2Connection.PropertyKey handleKey = ctx.channel() .attr(Http2ClientPipelineInitializer.CHANNEL_POOL_HANDLE_ATTR_KEY).get(); TimeoutAsyncPoolHandle<?> handle = _connection.stream(streamId).removeProperty(handleKey); if (handle == null) { _lifecycleManager.onError(ctx, Http2Exception.connectionError(Http2Error.PROTOCOL_ERROR, "No channel pool handle is associated with this stream", streamId)); return; } final StreamResponse response; if (endOfStream) { response = builder.build(EntityStreams.emptyStream()); ctx.fireChannelRead(handle); } else { // Associate an entity stream writer to the HTTP/2 stream final TimeoutBufferedWriter writer = new TimeoutBufferedWriter(ctx, streamId, _maxContentLength, handle); if (_connection.stream(streamId).setProperty(_writerKey, writer) != null) { _lifecycleManager.onError(ctx, Http2Exception.connectionError(Http2Error.PROTOCOL_ERROR, "Another writer has already been associated with current stream ID", streamId)); return; } // Prepares StreamResponse for the channel pipeline EntityStream entityStream = EntityStreams.newEntityStream(writer); response = builder.build(entityStream); } // Gets callback from stream properties Http2Connection.PropertyKey callbackKey = ctx.channel() .attr(Http2ClientPipelineInitializer.CALLBACK_ATTR_KEY).get(); TransportCallback<?> callback = _connection.stream(streamId).removeProperty(callbackKey); if (callback != null) { ctx.fireChannelRead(new ResponseWithCallback<Response, TransportCallback<?>>(response, callback)); } }
From source file:com.linkedin.r2.transport.http.client.Http2StreamCodec.java
License:Apache License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (!(msg instanceof RequestWithCallback)) { ctx.write(msg, promise);/* w w w. ja v a 2s.c o m*/ return; } Request request = ((RequestWithCallback) msg).request(); Http2ConnectionEncoder encoder = encoder(); int streamId = connection().local().incrementAndGetNextStreamId(); if (request instanceof StreamRequest) { LOG.debug("Writing StreamRequest..."); StreamRequest streamRequest = (StreamRequest) request; Http2Headers http2Headers = NettyRequestAdapter.toHttp2Headers(streamRequest); BufferedReader reader = new BufferedReader(ctx, encoder, streamId, ((RequestWithCallback) msg).handle()); streamRequest.getEntityStream().setReader(reader); encoder.writeHeaders(ctx, streamId, http2Headers, NO_PADDING, NOT_END_STREAM, promise) .addListener(future -> reader.request()); LOG.debug("Sent HTTP/2 HEADERS frame, stream={}, end={}, headers={}, padding={}bytes", new Object[] { streamId, NOT_END_STREAM, http2Headers.size(), NO_PADDING }); } else if (request instanceof RestRequest) { LOG.debug("Writing RestRequest..."); PromiseCombiner promiseCombiner = new PromiseCombiner(); ChannelPromise headersPromise = ctx.channel().newPromise(); ChannelPromise dataPromise = ctx.channel().newPromise(); promiseCombiner.add(headersPromise); promiseCombiner.add(dataPromise); promiseCombiner.finish(promise); RestRequest restRequest = (RestRequest) request; Http2Headers headers = NettyRequestAdapter.toHttp2Headers(restRequest); encoder.writeHeaders(ctx, streamId, headers, NO_PADDING, NOT_END_STREAM, headersPromise); LOG.debug("Sent HTTP/2 HEADERS frame, stream={}, end={}, headers={}, padding={}bytes", new Object[] { streamId, NOT_END_STREAM, headers.size(), NO_PADDING }); ByteBuf data = Unpooled.wrappedBuffer(restRequest.getEntity().asByteBuffer()); encoder.writeData(ctx, streamId, data, NO_PADDING, END_STREAM, dataPromise); LOG.debug("Sent HTTP/2 DATA frame, stream={}, end={}, data={}bytes, padding={}bytes", new Object[] { streamId, END_STREAM, data.readableBytes(), NO_PADDING }); } else { // Request type is not supported. Returns channel back to the pool and throws exception. ctx.fireChannelRead(((RequestWithCallback) msg).handle()); throw new IllegalArgumentException("Request is neither StreamRequest or RestRequest"); } // Sets TransportCallback as a stream property to be retrieved later TransportCallback<?> callback = ((RequestWithCallback) msg).callback(); Http2Connection.PropertyKey callbackKey = ctx.channel() .attr(Http2ClientPipelineInitializer.CALLBACK_ATTR_KEY).get(); connection().stream(streamId).setProperty(callbackKey, callback); // Sets AsyncPoolHandle as a stream property to be retrieved later AsyncPoolHandle<?> handle = ((RequestWithCallback) msg).handle(); Http2Connection.PropertyKey handleKey = ctx.channel() .attr(Http2ClientPipelineInitializer.CHANNEL_POOL_HANDLE_ATTR_KEY).get(); connection().stream(streamId).setProperty(handleKey, handle); }
From source file:io.grpc.netty.GrpcHttp2HeadersUtilsTest.java
License:Apache License
@Test public void decode_requestHeaders() throws Http2Exception { Http2HeadersDecoder decoder = new GrpcHttp2ServerHeadersDecoder(DEFAULT_MAX_HEADER_LIST_SIZE); Http2HeadersEncoder encoder = new DefaultHttp2HeadersEncoder(NEVER_SENSITIVE); Http2Headers headers = new DefaultHttp2Headers(false); headers.add(of(":scheme"), of("https")).add(of(":method"), of("GET")).add(of(":path"), of("index.html")) .add(of(":authority"), of("foo.grpc.io")).add(of("custom"), of("header")); encodedHeaders = Unpooled.buffer();/* ww w . ja v a2 s . c om*/ encoder.encodeHeaders(1 /* randomly chosen */, headers, encodedHeaders); Http2Headers decodedHeaders = decoder.decodeHeaders(3 /* randomly chosen */, encodedHeaders); assertEquals(headers.get(of(":scheme")), decodedHeaders.scheme()); assertEquals(headers.get(of(":method")), decodedHeaders.method()); assertEquals(headers.get(of(":path")), decodedHeaders.path()); assertEquals(headers.get(of(":authority")), decodedHeaders.authority()); assertEquals(headers.get(of("custom")), decodedHeaders.get(of("custom"))); assertEquals(headers.size(), decodedHeaders.size()); String toString = decodedHeaders.toString(); assertContainsKeyAndValue(toString, ":scheme", decodedHeaders.scheme()); assertContainsKeyAndValue(toString, ":method", decodedHeaders.method()); assertContainsKeyAndValue(toString, ":path", decodedHeaders.path()); assertContainsKeyAndValue(toString, ":authority", decodedHeaders.authority()); assertContainsKeyAndValue(toString, "custom", decodedHeaders.get(of("custom"))); }
From source file:io.grpc.netty.GrpcHttp2HeadersUtilsTest.java
License:Apache License
@Test public void decode_responseHeaders() throws Http2Exception { Http2HeadersDecoder decoder = new GrpcHttp2ClientHeadersDecoder(DEFAULT_MAX_HEADER_LIST_SIZE); Http2HeadersEncoder encoder = new DefaultHttp2HeadersEncoder(NEVER_SENSITIVE); Http2Headers headers = new DefaultHttp2Headers(false); headers.add(of(":status"), of("200")).add(of("custom"), of("header")); encodedHeaders = Unpooled.buffer();// w ww . jav a 2 s . com encoder.encodeHeaders(1 /* randomly chosen */, headers, encodedHeaders); Http2Headers decodedHeaders = decoder.decodeHeaders(3 /* randomly chosen */, encodedHeaders); assertEquals(headers.get(of(":status")), decodedHeaders.get(of(":status"))); assertEquals(headers.get(of("custom")), decodedHeaders.get(of("custom"))); assertEquals(headers.size(), decodedHeaders.size()); String toString = decodedHeaders.toString(); assertContainsKeyAndValue(toString, ":status", decodedHeaders.get(of(":status"))); assertContainsKeyAndValue(toString, "custom", decodedHeaders.get(of("custom"))); }
From source file:io.grpc.netty.GrpcHttp2HeadersUtilsTest.java
License:Apache License
@Test public void decode_emptyHeaders() throws Http2Exception { Http2HeadersDecoder decoder = new GrpcHttp2ClientHeadersDecoder(8192); Http2HeadersEncoder encoder = new DefaultHttp2HeadersEncoder(NEVER_SENSITIVE); ByteBuf encodedHeaders = Unpooled.buffer(); encoder.encodeHeaders(1 /* randomly chosen */, new DefaultHttp2Headers(false), encodedHeaders); Http2Headers decodedHeaders = decoder.decodeHeaders(3 /* randomly chosen */, encodedHeaders); assertEquals(0, decodedHeaders.size()); assertThat(decodedHeaders.toString(), containsString("[]")); }
From source file:io.grpc.netty.GrpcHttp2InboundHeadersTest.java
License:Apache License
@Test public void basicCorrectness() { Http2Headers headers = new GrpcHttp2RequestHeaders(1); headers.add(of(":method"), of("POST")); headers.add(of("content-type"), of("application/grpc+proto")); headers.add(of(":path"), of("/google.pubsub.v2.PublisherService/CreateTopic")); headers.add(of(":scheme"), of("https")); headers.add(of("te"), of("trailers")); headers.add(of(":authority"), of("pubsub.googleapis.com")); headers.add(of("foo"), of("bar")); assertEquals(7, headers.size()); // Number of headers without the pseudo headers and 'te' header. assertEquals(2, ((GrpcHttp2InboundHeaders) headers).numHeaders()); assertEquals(of("application/grpc+proto"), headers.get(of("content-type"))); assertEquals(of("/google.pubsub.v2.PublisherService/CreateTopic"), headers.path()); assertEquals(of("https"), headers.scheme()); assertEquals(of("POST"), headers.method()); assertEquals(of("pubsub.googleapis.com"), headers.authority()); assertEquals(of("trailers"), headers.get(of("te"))); assertEquals(of("bar"), headers.get(of("foo"))); }
From source file:io.grpc.netty.GrpcHttp2InboundHeadersTest.java
License:Apache License
@Test public void binaryHeadersShouldBeBase64Decoded() { Http2Headers headers = new GrpcHttp2RequestHeaders(1); byte[] data = new byte[100]; new Random().nextBytes(data); headers.add(of("foo-bin"), of(BASE64_ENCODING_OMIT_PADDING.encode(data))); assertEquals(1, headers.size()); byte[][] namesAndValues = ((GrpcHttp2InboundHeaders) headers).namesAndValues(); assertEquals(of("foo-bin"), new AsciiString(namesAndValues[0])); assertNotSame(data, namesAndValues[1]); assertArrayEquals(data, namesAndValues[1]); }
From source file:io.grpc.netty.Utils.java
License:Apache License
@CheckReturnValue private static byte[][] convertHeadersToArray(Http2Headers http2Headers) { // The Netty AsciiString class is really just a wrapper around a byte[] and supports // arbitrary binary data, not just ASCII. byte[][] headerValues = new byte[http2Headers.size() * 2][]; int i = 0;//from w ww. ja v a 2 s . c o m for (Map.Entry<CharSequence, CharSequence> entry : http2Headers) { headerValues[i++] = bytes(entry.getKey()); headerValues[i++] = bytes(entry.getValue()); } return toRawSerializedHeaders(headerValues); }