List of usage examples for io.netty.handler.codec.http2 Http2Headers authority
CharSequence authority();
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;// w ww .j ava 2 s. 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.TestNettyRequestAdapter.java
License:Apache License
@Test public void testStreamToHttp2HeadersPseudoHeaders() throws Exception { StreamRequestBuilder streamRequestBuilder = new StreamRequestBuilder(new URI(ANY_URI)); StreamRequest request = streamRequestBuilder .build(EntityStreams.newEntityStream(new ByteStringWriter(ByteString.copy(ANY_ENTITY.getBytes())))); Http2Headers headers = NettyRequestAdapter.toHttp2Headers(request); Assert.assertNotNull(headers);/*from w ww . j av a 2 s .c o m*/ Assert.assertEquals(headers.authority(), "localhost:8080"); Assert.assertEquals(headers.method(), "GET"); Assert.assertEquals(headers.path(), "/foo/bar?q=baz"); Assert.assertEquals(headers.scheme(), "http"); }
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();/* w ww .j a v a 2s . c o m*/ 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.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());/*from ww w . j ava 2s. com*/ // 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.NettyServerHandler.java
License:Apache License
private void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers) throws Http2Exception { if (!teWarningLogged && !TE_TRAILERS.contentEquals(headers.get(TE_HEADER))) { logger.warning(String.format( "Expected header TE: %s, but %s is received. This means " + "some intermediate proxy may not support trailers", TE_TRAILERS, headers.get(TE_HEADER))); teWarningLogged = true;//from w w w . j a va 2 s . c o m } try { // Remove the leading slash of the path and get the fully qualified method name CharSequence path = headers.path(); if (path == null) { respondWithHttpError(ctx, streamId, 404, Status.Code.UNIMPLEMENTED, "Expected path but is missing"); return; } if (path.charAt(0) != '/') { respondWithHttpError(ctx, streamId, 404, Status.Code.UNIMPLEMENTED, String.format("Expected path to start with /: %s", path)); return; } String method = path.subSequence(1, path.length()).toString(); // Verify that the Content-Type is correct in the request. CharSequence contentType = headers.get(CONTENT_TYPE_HEADER); if (contentType == null) { respondWithHttpError(ctx, streamId, 415, Status.Code.INTERNAL, "Content-Type is missing from the request"); return; } String contentTypeString = contentType.toString(); if (!GrpcUtil.isGrpcContentType(contentTypeString)) { respondWithHttpError(ctx, streamId, 415, Status.Code.INTERNAL, String.format("Content-Type '%s' is not supported", contentTypeString)); return; } if (!HTTP_METHOD.contentEquals(headers.method())) { respondWithHttpError(ctx, streamId, 405, Status.Code.INTERNAL, String.format("Method '%s' is not supported", headers.method())); return; } // The Http2Stream object was put by AbstractHttp2ConnectionHandler before calling this // method. Http2Stream http2Stream = requireHttp2Stream(streamId); Metadata metadata = Utils.convertHeaders(headers); StatsTraceContext statsTraceCtx = StatsTraceContext.newServerContext(streamTracerFactories, method, metadata); NettyServerStream.TransportState state = new NettyServerStream.TransportState(this, ctx.channel().eventLoop(), http2Stream, maxMessageSize, statsTraceCtx, transportTracer, method); PerfMark.startTask("NettyServerHandler.onHeadersRead", state.tag()); try { String authority = getOrUpdateAuthority((AsciiString) headers.authority()); NettyServerStream stream = new NettyServerStream(ctx.channel(), state, attributes, authority, statsTraceCtx, transportTracer); transportListener.streamCreated(stream, method, metadata); state.onStreamAllocated(); http2Stream.setProperty(streamKey, state); } finally { PerfMark.stopTask("NettyServerHandler.onHeadersRead", state.tag()); } } catch (Exception e) { logger.log(Level.WARNING, "Exception in onHeadersRead()", e); // Throw an exception that will get handled by onStreamError. throw newStreamException(streamId, e); } }
From source file:io.vertx.core.http.impl.Http2ClientConnection.java
License:Open Source License
@Override public synchronized void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId, Http2Headers headers, int padding) throws Http2Exception { Http2ClientStream stream = (Http2ClientStream) streams.get(streamId); if (stream != null) { Handler<HttpClientRequest> pushHandler = stream.pushHandler(); if (pushHandler != null) { context.executeFromIO(() -> { String rawMethod = headers.method().toString(); HttpMethod method = HttpUtils.toVertxMethod(rawMethod); String uri = headers.path().toString(); String host = headers.authority() != null ? headers.authority().toString() : null; MultiMap headersMap = new Http2HeadersAdaptor(headers); Http2Stream promisedStream = handler.connection().stream(promisedStreamId); int port = remoteAddress().port(); HttpClientRequestPushPromise pushReq = new HttpClientRequestPushPromise(this, promisedStream, http2Pool.client, isSsl(), method, rawMethod, uri, host, port, headersMap); if (metrics.isEnabled()) { pushReq.metric(metrics.responsePushed(queueMetric, metric(), localAddress(), remoteAddress(), pushReq)); }/*www. j a v a 2 s .co m*/ streams.put(promisedStreamId, pushReq.getStream()); pushHandler.handle(pushReq); }); return; } } handler.writeReset(promisedStreamId, Http2Error.CANCEL.code()); }
From source file:io.vertx.core.http.impl.Http2ServerConnection.java
License:Open Source License
private static boolean isMalformedRequest(Http2Headers headers) { if (headers.method() == null) { return true; }// ww w . j a va2s. c o m String method = headers.method().toString(); if (method.equals("CONNECT")) { if (headers.scheme() != null || headers.path() != null || headers.authority() == null) { return true; } } else { if (headers.method() == null || headers.scheme() == null || headers.path() == null) { return true; } } if (headers.authority() != null) { URI uri; try { uri = new URI(null, headers.authority().toString(), null, null, null); } catch (URISyntaxException e) { return true; } if (uri.getRawUserInfo() != null) { return true; } } return false; }