List of usage examples for io.netty.handler.codec.http2 Http2Headers method
CharSequence method();
From source file:com.linecorp.armeria.server.Http2RequestDecoder.java
License:Apache License
@Override public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding, boolean endOfStream) throws Http2Exception { DecodedHttpRequest req = requests.get(streamId); if (req == null) { // Validate the method. final CharSequence method = headers.method(); if (method == null) { writeErrorResponse(ctx, streamId, HttpResponseStatus.BAD_REQUEST); return; }// w ww .j a va 2 s .co m if (!HttpMethod.isSupported(method.toString())) { writeErrorResponse(ctx, streamId, HttpResponseStatus.METHOD_NOT_ALLOWED); return; } // Validate the 'content-length' header if exists. final boolean contentEmpty; if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) { final long contentLength = headers.getLong(HttpHeaderNames.CONTENT_LENGTH, -1L); if (contentLength < 0) { writeErrorResponse(ctx, streamId, HttpResponseStatus.BAD_REQUEST); return; } contentEmpty = contentLength == 0; } else { contentEmpty = true; } req = new DecodedHttpRequest(ctx.channel().eventLoop(), ++nextId, streamId, ArmeriaHttpUtil.toArmeria(headers), true, inboundTrafficController, cfg.defaultMaxRequestLength()); // Close the request early when it is sure that there will be // neither content nor trailing headers. if (contentEmpty && endOfStream) { req.close(); } requests.put(streamId, req); ctx.fireChannelRead(req); } else { try { req.write(ArmeriaHttpUtil.toArmeria(headers)); } catch (Throwable t) { req.close(t); throw connectionError(INTERNAL_ERROR, t, "failed to consume a HEADERS frame"); } } if (endOfStream) { req.close(); } }
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 w w . ja va2s. 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 w w . j a va2s .co 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());// ww w .j a v a2s . co m // 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.InboundHeadersBenchmark.java
License:Apache License
@CompilerControl(CompilerControl.Mode.INLINE) private static void serverHandler(Blackhole bh, Http2Headers headers) { for (int i = 0; i < requestHeaders.length; i += 2) { bh.consume(headers.add(requestHeaders[i], requestHeaders[i + 1])); }//from ww w. j a v a2 s . com // Sequence of headers accessed in NettyServerHandler bh.consume(headers.get(TE_TRAILERS)); bh.consume(headers.get(CONTENT_TYPE_HEADER)); bh.consume(headers.method()); bh.consume(headers.get(CONTENT_TYPE_HEADER)); bh.consume(headers.path()); bh.consume(Utils.convertHeaders(headers)); }
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 ww w . j a v a 2 s . c om*/ } 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)); }//ww w .j a v a2s . c om 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; }//from w w w .j av a 2 s . c om 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; }
From source file:org.jboss.aerogear.webpush.netty.WebPushFrameListener.java
License:Apache License
@Override public void onHeadersRead(final ChannelHandlerContext ctx, final int streamId, final Http2Headers headers, final int streamDependency, final short weight, final boolean exclusive, final int padding, final boolean endStream) throws Http2Exception { final String path = headers.path().toString(); final String method = headers.method().toString(); LOGGER.info("onHeadersRead. streamId={}, method={}, path={}, endstream={}", streamId, method, path, endStream);//w w w.java 2 s .c o m final Resource resource = getResource(path); final Http2Stream stream = encoder.connection().stream(streamId); stream.setProperty(pathPropertyKey, path); stream.setProperty(resourcePropertyKey, resource); switch (method) { case GET: switch (resource) { case SUBSCRIPTION: handleReceivingPushMessages(ctx, streamId, headers, path); return; case RECEIPT: handleReceivingPushMessageReceipts(ctx, streamId, path); return; } break; case POST: switch (resource) { case SUBSCRIBE: handleSubscribe(ctx, streamId); return; case RECEIPTS: handleReceipts(ctx, streamId, path); return; case PUSH: final Optional<String> pushReceiptToken = getPushReceiptToken(headers); stream.setProperty(pushReceiptPropertyKey, pushReceiptToken); final Optional<Integer> ttl = getTtl(headers); stream.setProperty(ttlPropertyKey, ttl); //see onDataRead(...) method return; } break; case DELETE: switch (resource) { case PUSH_MESSAGE: handleAcknowledgement(ctx, streamId, path); return; case SUBSCRIPTION: handlePushMessageSubscriptionRemoval(ctx, streamId, path); return; case RECEIPT: handleReceiptSubscriptionRemoval(ctx, streamId, path); return; } break; } }
From source file:org.wso2.carbon.transport.http.netty.listener.http2.HTTP2SourceHandler.java
License:Open Source License
/** * Setup carbon message for HTTP2 request. * * @param streamId Stream id of HTTP2 request received * @param headers HTTP2 Headers// ww w .j a va 2 s.co m * @return HTTPCarbonMessage */ protected HTTPCarbonMessage setupCarbonMessage(int streamId, Http2Headers headers) { // Construct new HTTP carbon message and put into stream id request map // TODO: This fix is temporary and we need to revisit this and the entire http2 implementation. HTTPCarbonMessage cMsg = new HTTPCarbonMessage( new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "")); cMsg.setProperty(Constants.PORT, ((InetSocketAddress) ctx.channel().remoteAddress()).getPort()); cMsg.setProperty(Constants.HOST, ((InetSocketAddress) ctx.channel().remoteAddress()).getHostName()); cMsg.setProperty(Constants.SCHEME, listenerConfiguration.getScheme()); cMsg.setProperty(Constants.HTTP_VERSION, Constants.HTTP2_VERSION); cMsg.setProperty(org.wso2.carbon.messaging.Constants.LISTENER_PORT, ((InetSocketAddress) ctx.channel().localAddress()).getPort()); cMsg.setProperty(org.wso2.carbon.messaging.Constants.LISTENER_INTERFACE_ID, listenerConfiguration.getId()); cMsg.setProperty(org.wso2.carbon.messaging.Constants.PROTOCOL, Constants.HTTP_SCHEME); if (listenerConfiguration.getSslConfig() != null) { cMsg.setProperty(Constants.IS_SECURED_CONNECTION, true); } else { cMsg.setProperty(Constants.IS_SECURED_CONNECTION, false); } cMsg.setProperty(Constants.LOCAL_ADDRESS, ctx.channel().localAddress()); cMsg.setProperty(Constants.LOCAL_NAME, ((InetSocketAddress) ctx.channel().localAddress()).getHostName()); cMsg.setProperty(Constants.REMOTE_ADDRESS, ctx.channel().remoteAddress()); cMsg.setProperty(Constants.REMOTE_HOST, ((InetSocketAddress) ctx.channel().remoteAddress()).getHostName()); cMsg.setProperty(Constants.REMOTE_PORT, ((InetSocketAddress) ctx.channel().remoteAddress()).getPort()); ChannelHandler handler = ctx.handler(); cMsg.setProperty(Constants.CHANNEL_ID, ((HTTP2SourceHandler) handler).getListenerConfiguration().getId()); cMsg.setProperty(Constants.STREAM_ID, streamId); if (headers.path() != null) { String path = headers.getAndRemove(Constants.HTTP2_PATH).toString(); cMsg.setProperty(Constants.TO, path); cMsg.setProperty(Constants.REQUEST_URL, path); } if (headers.method() != null) { String method = headers.getAndRemove(Constants.HTTP2_METHOD).toString(); cMsg.setProperty(Constants.HTTP_METHOD, method); } // Remove PseudoHeaderNames from headers headers.getAndRemove(Constants.HTTP2_AUTHORITY); headers.getAndRemove(Constants.HTTP2_SCHEME); // Copy Http2 headers to carbon message headers.forEach(k -> cMsg.setHeader(k.getKey().toString(), k.getValue().toString())); streamIdRequestMap.put(streamId, cMsg); return cMsg; }