List of usage examples for io.netty.channel ChannelHandlerContext channel
Channel channel();
From source file:com.aerofs.baseline.http.Channels.java
License:Apache License
static String getHexText(ChannelHandlerContext ctx) { return getHexText(ctx.channel()); }
From source file:com.aerofs.baseline.http.HttpRequestHandler.java
License:Apache License
@Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { LOGGER.trace("{}: set http cleanup handler", Channels.getHexText(ctx)); ctx.channel().closeFuture().addListener(future -> cleanup(ctx, future.cause())); super.channelRegistered(ctx); ctx.read();/* w ww. j a v a 2s . c o m*/ }
From source file:com.aerofs.baseline.http.HttpRequestHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (ctx.channel().closeFuture().isDone()) { LOGGER.warn("{}: drop http message - channel closed", Channels.getHexText(ctx)); return;// w ww . j a v a2 s . c om } if (!(msg instanceof HttpObject)) { super.channelRead(ctx, msg); } // // netty http decoding: // // 1. normal case: HttpRequest (headers), HttpContent (0+), LastHttpContent (trailing headers) // NOTE: with chunked transfer encoding or content-length non-zero you get an arbitrary number of HttpContent objects // 2. error case (failed to decode an HTTP message): HttpRequest with NETTY_HTTP_DECODING_FAILED_URI // if (msg instanceof HttpRequest) { // this is the first object netty generates: // an HttpRequest containing a number of headers // we should not have another request pending Preconditions.checkState(pendingRequest == null, "previous request pending:%s", pendingRequest); // cast it HttpRequest nettyRequest = (HttpRequest) msg; // get the request id String requestId = nettyRequest.headers().get(Headers.REQUEST_TRACING_HEADER); Preconditions.checkState(requestId != null, "http request on %s has no request id", Channels.getHexText(ctx)); // check if http decoding failed and if so, abort early if (nettyRequest.uri().equals(NETTY_HTTP_DECODING_FAILED_URI)) { LOGGER.warn("{}: [{}] fail http decoding", Channels.getHexText(ctx), requestId); ctx.read(); return; } // get a few headers we really care about HttpVersion httpVersion = nettyRequest.protocolVersion(); boolean keepAlive = HttpHeaders.isKeepAlive(nettyRequest); boolean transferEncodingChunked = HttpHeaders.isTransferEncodingChunked(nettyRequest); boolean continueExpected = HttpHeaders.is100ContinueExpected(nettyRequest); long contentLength = HttpHeaders.getContentLength(nettyRequest, ZERO_CONTENT_LENGTH); boolean hasContent = transferEncodingChunked || contentLength > ZERO_CONTENT_LENGTH; LOGGER.trace("{}: [{}] rq:{} ka:{} ck:{} ce:{} cl:{}", Channels.getHexText(ctx), requestId, nettyRequest, keepAlive, transferEncodingChunked, continueExpected, contentLength); // create the input stream used to read content ContentInputStream entityInputStream; if (hasContent) { entityInputStream = new EntityInputStream(httpVersion, continueExpected, ctx); } else { entityInputStream = EmptyEntityInputStream.EMPTY_ENTITY_INPUT_STREAM; } // create the object with which to write the response body PendingRequest pendingRequest = new PendingRequest(requestId, httpVersion, keepAlive, entityInputStream, ctx); // create the jersey request object final ContainerRequest jerseyRequest = new ContainerRequest(baseUri, URI.create(nettyRequest.uri()), nettyRequest.method().name(), DEFAULT_SECURITY_CONTEXT, PROPERTIES_DELEGATE); jerseyRequest.setProperty(RequestProperties.REQUEST_CONTEXT_CHANNEL_ID_PROPERTY, new ChannelId(Channels.getHexText(ctx))); jerseyRequest.setProperty(RequestProperties.REQUEST_CONTEXT_REQUEST_ID_PROPERTY, new RequestId(requestId)); jerseyRequest.header(Headers.REQUEST_TRACING_HEADER, requestId); // add request id to headers copyHeaders(nettyRequest.headers(), jerseyRequest); // copy headers from message jerseyRequest.setEntityStream(entityInputStream); jerseyRequest.setWriter(pendingRequest); // now we've got all the initial headers and are waiting for the entity this.pendingRequest = pendingRequest; // store the runnable that we want jersey to execute saveRequestRunnable(() -> { // all throwables caught by jersey internally - // handled by the ResponseWriter below // if, for some reason there's some weird error it'll be handled // by the default exception handler, which kills the process applicationHandler.handle(jerseyRequest); }); // IMPORTANT: // we pass this request up to be processed by // jersey before we've read any content. This allows // the resource to read from the InputStream // directly, OR, to use an @Consumes annotation with an // input objectType to invoke the appropriate parser // // since the request is consumed *before* the content // has been received readers may block. to prevent the // IO thread from blocking we have to execute all // request processing in an application threadpool if (hasContent) { submitPendingRunnable(); } // indicate that we want to keep reading // this is always the case when we receive headers // because we want to receive everything until // LastHttpContent ctx.read(); } else { // after receiving the http headers we get // a series of HttpContent objects that represent // the entity or a set of chunks // we should have received the headers already Preconditions.checkState(pendingRequest != null, "no pending request"); // we're not expecting anything other than content objects right now Preconditions.checkArgument(msg instanceof HttpContent, "HttpContent expected, not %s", msg.getClass().getSimpleName()); // handle the content HttpContent content = (HttpContent) msg; boolean last = msg instanceof LastHttpContent; LOGGER.trace("{}: [{}] handling content:{} last:{}", Channels.getHexText(ctx), pendingRequest.requestId, content.content().readableBytes(), last); pendingRequest.entityInputStream.addBuffer(content.content(), last); // transfers ownership to the HttpContentInputStream // FIXME (AG): support trailing headers // if it's the last piece of content, then we're done if (last) { // submit the request to jersey if we haven't yet if (savedRequestRunnable != null) { submitPendingRunnable(); } } } }
From source file:com.ahanda.techops.noty.clientTest.ClientHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { assert msg instanceof FullHttpResponse; l.info(" Got a message from server !!! {}", msg); ++state;/* www . ja v a 2 s . c o m*/ if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; System.out.println("STATUS: " + response.getStatus()); System.out.println("VERSION: " + response.getProtocolVersion()); System.out.println(); if (!response.headers().isEmpty()) { for (String name : response.headers().names()) { for (String value : response.headers().getAll(name)) { System.out.println("HEADER: " + name + " = " + value); } } System.out.println(); } if (HttpHeaders.isTransferEncodingChunked(response)) { System.out.println("CHUNKED CONTENT {"); } else { System.out.println("CONTENT {"); } } if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; System.out.print(content.content().toString(CharsetUtil.UTF_8)); System.out.flush(); if (content instanceof LastHttpContent) { System.out.println("} END OF CONTENT"); } } switch (state) { case 1: FullHttpResponse resp = (FullHttpResponse) msg; for (String cookiestr : resp.headers().getAll(HttpHeaders.Names.SET_COOKIE)) { Set<Cookie> tmp = CookieDecoder.decode(cookiestr); sessCookies = tmp; } //login( ctx.channel(), credential ); pubEvent(ctx.channel(), event, (FullHttpResponse) msg); break; case 2: getEvents(ctx.channel(), (FullHttpResponse) msg); break; case 3: logout(ctx.channel()); break; default: ctx.close(); break; } }
From source file:com.alibaba.dubbo.qos.server.handler.HttpProcessHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception { CommandContext commandContext = HttpCommandDecoder.decode(msg); // return 404 when fail to construct command context if (commandContext == null) { log.warn("can not found commandContext url: " + msg.getUri()); FullHttpResponse response = http_404(); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else {/*from ww w .j av a 2s . c o m*/ commandContext.setRemote(ctx.channel()); try { String result = commandExecutor.execute(commandContext); FullHttpResponse response = http_200(result); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (NoSuchCommandException ex) { log.error("can not find commandContext: " + commandContext, ex); FullHttpResponse response = http_404(); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (Exception qosEx) { log.error("execute commandContext: " + commandContext + " got exception", qosEx); FullHttpResponse response = http_500(qosEx.getMessage()); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } } }
From source file:com.alibaba.dubbo.qos.server.handler.LocalHostPermitHandler.java
License:Apache License
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { if (!acceptForeignIp) { if (!((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().isLoopbackAddress()) { ByteBuf cb = Unpooled.wrappedBuffer( (QosConstants.BR_STR + "Foreign Ip Not Permitted." + QosConstants.BR_STR).getBytes()); ctx.writeAndFlush(cb).addListener(ChannelFutureListener.CLOSE); }//w w w . j av a 2s . c o m } }
From source file:com.alibaba.dubbo.qos.server.handler.TelnetProcessHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { if (StringUtils.isBlank(msg)) { ctx.writeAndFlush(QosProcessHandler.prompt); } else {/*from www.j a v a 2 s.com*/ CommandContext commandContext = TelnetCommandDecoder.decode(msg); commandContext.setRemote(ctx.channel()); try { String result = commandExecutor.execute(commandContext); if (StringUtils.equals(QosConstants.CLOSE, result)) { ctx.writeAndFlush(getByeLabel()).addListener(ChannelFutureListener.CLOSE); } else { ctx.writeAndFlush(result + QosConstants.BR_STR + QosProcessHandler.prompt); } } catch (NoSuchCommandException ex) { ctx.writeAndFlush(msg + " :no such command"); ctx.writeAndFlush(QosConstants.BR_STR + QosProcessHandler.prompt); log.error("can not found command " + commandContext, ex); } catch (Exception ex) { ctx.writeAndFlush(msg + " :fail to execute commandContext by " + ex.getMessage()); ctx.writeAndFlush(QosConstants.BR_STR + QosProcessHandler.prompt); log.error("execute commandContext got exception " + commandContext, ex); } } }
From source file:com.alibaba.dubbo.remoting.transport.netty.NettyClientHandler.java
License:Apache License
@Override public void disconnect(ChannelHandlerContext ctx, ChannelPromise future) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try {//ww w. j a va2 s. co m handler.disconnected(channel); } finally { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } }
From source file:com.alibaba.dubbo.remoting.transport.netty.NettyClientHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try {// w ww . j a va 2 s . c o m handler.received(channel, msg); } finally { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } }
From source file:com.alibaba.dubbo.remoting.transport.netty.NettyClientHandler.java
License:Apache License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { super.write(ctx, msg, promise); NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); try {/*w w w . j av a 2s . c o m*/ handler.sent(channel, msg); } finally { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } }