List of usage examples for io.netty.channel ChannelHandlerContext pipeline
ChannelPipeline pipeline();
From source file:io.vertx.core.net.NetTest.java
License:Open Source License
private void testNetClientInternal_(HttpServerOptions options, boolean expectSSL) throws Exception { waitFor(2);//from ww w.j a v a2 s. c o m HttpServer server = vertx.createHttpServer(options); server.requestHandler(req -> { req.response().end("Hello World"); }); CountDownLatch latch = new CountDownLatch(1); server.listen(onSuccess(v -> { latch.countDown(); })); awaitLatch(latch); client.connect(1234, "localhost", onSuccess(so -> { NetSocketInternal soInt = (NetSocketInternal) so; assertEquals(expectSSL, soInt.isSsl()); ChannelHandlerContext chctx = soInt.channelHandlerContext(); ChannelPipeline pipeline = chctx.pipeline(); pipeline.addBefore("handler", "http", new HttpClientCodec()); AtomicInteger status = new AtomicInteger(); soInt.handler(buff -> fail()); soInt.messageHandler(obj -> { switch (status.getAndIncrement()) { case 0: assertTrue(obj instanceof HttpResponse); HttpResponse resp = (HttpResponse) obj; assertEquals(200, resp.status().code()); break; case 1: assertTrue(obj instanceof LastHttpContent); ByteBuf content = ((LastHttpContent) obj).content(); assertEquals(!expectSSL, content.isDirect()); assertEquals(1, content.refCnt()); String val = content.toString(StandardCharsets.UTF_8); assertTrue(content.release()); assertEquals("Hello World", val); complete(); break; default: fail(); } }); soInt.writeMessage(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/somepath"), onSuccess(v -> complete())); })); await(); }
From source file:io.vertx.test.core.Http2ClientTest.java
License:Open Source License
private ServerBootstrap createH2Server( BiFunction<Http2ConnectionDecoder, Http2ConnectionEncoder, Http2FrameListener> handler) { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.channel(NioServerSocketChannel.class); NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(); eventLoopGroups.add(eventLoopGroup); bootstrap.group(eventLoopGroup);//from w ww . jav a 2 s.c o m bootstrap.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { SSLHelper sslHelper = new SSLHelper(serverOptions, Cert.SERVER_JKS.get(), null); SslHandler sslHandler = sslHelper .setApplicationProtocols(Arrays.asList(HttpVersion.HTTP_2, HttpVersion.HTTP_1_1)) .createSslHandler((VertxInternal) vertx, DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT); ch.pipeline().addLast(sslHandler); ch.pipeline().addLast(new ApplicationProtocolNegotiationHandler("whatever") { @Override protected void configurePipeline(ChannelHandlerContext ctx, String protocol) { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { ChannelPipeline p = ctx.pipeline(); Http2ConnectionHandler clientHandler = createHttpConnectionHandler(handler); p.addLast("handler", clientHandler); return; } ctx.close(); throw new IllegalStateException("unknown protocol: " + protocol); } }); } }); return bootstrap; }
From source file:io.werval.server.netty.SubProtocolSwitchHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext context, Object message) throws Exception { if (message instanceof HttpRequest) { HttpRequest request = (HttpRequest) message; LOG.trace("Switching to plain HTTP protocol"); ChannelPipeline pipeline = context.pipeline(); int maxBodySize = app.config().intNumber(WERVAL_HTTP_REQUESTS_BODY_MAX_SIZE); int diskThreshold = app.config().intNumber(WERVAL_HTTP_REQUESTS_BODY_DISK_THRESHOLD); pipeline.addLast("http-aggregator", new HttpRequestAggregator(helper, app.events(), maxBodySize, diskThreshold, app.tmpdir())); pipeline.addLast("werval-http", new WervalHttpHandler(app, devSpi)); pipeline.remove(this); context.fireChannelRead(request); } else if (message instanceof WebSocketFrame) { WebSocketFrame frame = (WebSocketFrame) message; LOG.trace("Switching to WebSocket protocol"); ChannelPipeline pipeline = context.pipeline(); pipeline.addLast("werval-websocket", new WervalSocketHandler(app, devSpi)); pipeline.remove(this); frame.retain(); // TODO Check this context.fireChannelRead(frame);/*from w w w. j a v a 2 s. c om*/ } else { LOG.warn("Received a message of an unknown type ({}), channel will be closed.", message.getClass()); context.channel().close(); } }
From source file:jj.http.server.HttpRequestListeningHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, HttpRequest request) throws Exception { this.request = request; if (request.getDecoderResult().isFailure()) { // respond with BAD_REQUEST and close the connection // (unless we are being proxied and the connection is keep-alive, that is) BAD_REQUEST.writeAndFlush(ctx).addListener(ChannelFutureListener.CLOSE); } else if (methodHandlers.containsKey(request.getMethod())) { HttpMethodHandler methodHandler = methodHandlers.get(request.getMethod()).get(); methodHandler.request(request);//ww w . j av a 2 s .co m ChannelPipeline p = ctx.pipeline(); p.addAfter(name, "method handler", methodHandler); ctx.fireChannelRead(request); } else { // respond with NOT_IMPLEMENTED // unless we are being proxied and the connection is keep-alive NOT_IMPLEMENTED.writeAndFlush(ctx).addListener(ChannelFutureListener.CLOSE); } }
From source file:jj.http.server.HttpRequestListeningHandler.java
License:Apache License
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { for (Entry<String, ChannelHandler> entry : ctx.pipeline()) { if (entry.getValue() == this) { name = entry.getKey();/* w w w.j av a 2 s.co m*/ } } assert name != null : "couldn't find myself in the pipeline!"; }
From source file:jj.http.server.websocket.WebSocketConnectionMaker.java
License:Apache License
private void doHandshake(final ChannelHandlerContext ctx, final FullHttpRequest request, final WebSocketServerHandshaker handshaker) { handshaker.handshake(ctx.channel(), request).addListener(new ChannelFutureListener() { private boolean isHandshakeFailure(ChannelFuture future) { return future.cause() != null && future.cause() instanceof WebSocketHandshakeException; }/* ww w . j av a 2 s .com*/ @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { URIMatch uriMatch = new URIMatch(request.getUri()); WebSocketConnectionHost host = null; for (Class<? extends WebSocketConnectionHost> hostClass : webSocketConnectionHostClasses) { host = resourceFinder.findResource(hostClass, AppLocation.Virtual, uriMatch.name); if (host != null) break; } if (host == null) { // 1011 indicates that a server is terminating the connection because // it encountered an unexpected condition that prevented it from // fulfilling the request. ctx.writeAndFlush(new CloseWebSocketFrame(1011, null)).addListener(CLOSE); // TODO: is closing here the right thing? or do we count on the client closing the connection // to avoid the time_wait state? } else if (!uriMatch.sha1.equals(host.sha1())) { ctx.writeAndFlush(new TextWebSocketFrame("jj-reload")) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { // 1001 indicates that an endpoint is "going away", such as a server // going down or a browser having navigated away from a page. ctx.writeAndFlush(new CloseWebSocketFrame(1001, null)).addListener(CLOSE); // TODO: is closing here the right thing? or do we count on the client closing the connection // to avoid the time_wait state? } }); } else { ctx.pipeline().replace(JJEngine.toString(), JJWebsocketHandler.toString(), handlerCreator.createHandler(handshaker, host)); } } else if (isHandshakeFailure(future)) { response.sendError(HttpResponseStatus.BAD_REQUEST); } else { ctx.close(); } } }); }
From source file:me.bigteddy98.animatedmotd.bungee.NettyDecoder.java
License:Open Source License
@Override protected void decode(final ChannelHandlerContext ctx, PacketWrapper packet, List<Object> out) throws Exception { this.previousTime = System.currentTimeMillis(); this.ctx = ctx; if (packet == null || packet.packet == null) { out.add(packet);/*from w w w.j a v a 2 s . c o m*/ return; } if (packet.packet instanceof Handshake) { Handshake packett = (Handshake) packet.packet; this.requestedProtocol = packett.getProtocolVersion(); } if (packet.packet instanceof PingPacket) { if (respondPing) { ctx.pipeline().writeAndFlush(new PingPacket(((PingPacket) packet.packet).getTime())); ctx.close(); return; } if ((System.currentTimeMillis() - startTime) > (PingManager.getStopAfter() * 1000)) { // respond with a response packet final ServerData data = this.statusListener.update(); JsonObject version = new JsonObject(); version.addProperty("name", "1.8"); version.addProperty("protocol", requestedProtocol); JsonArray playerArray = new JsonArray(); for (String playerName : data.getPlayers()) { JsonObject playerObject = new JsonObject(); playerObject.addProperty("name", playerName); playerObject.addProperty("id", UUID.randomUUID().toString()); playerArray.add(playerObject); } JsonObject countData = new JsonObject(); countData.addProperty("max", getMaxCount()); countData.addProperty("online", ProxyServer.getInstance().getOnlineCount()); countData.add("sample", playerArray); JsonObject jsonObject = new JsonObject(); jsonObject.add("version", version); jsonObject.add("players", countData); jsonObject.addProperty("description", data.getMotd()); if (data.getFavicon() != null) { jsonObject.addProperty("favicon", data.getFavicon()); } ctx.pipeline().writeAndFlush(new StatusResponse(jsonObject.toString())); respondPing = true; } else { final ServerData data = this.statusListener.update(); this.isPing = true; ProxyServer.getInstance().getScheduler().schedule(this.plugin, new Runnable() { @Override public void run() { // respond with a response packet ctx.pipeline().writeAndFlush((new StatusResponse(buildResponseJSON()))); } }, data.getSleepMillis(), TimeUnit.MILLISECONDS); } } else if (packet.packet instanceof StatusRequest) { ctx.pipeline().writeAndFlush(new StatusResponse(buildResponseJSON())); } else { out.add(packet); } }
From source file:me.bigteddy98.animatedmotd.bungee.PacketInterceptionDecoder.java
License:Open Source License
@Override protected void decode(final ChannelHandlerContext ctx, PacketWrapper packet, List<Object> out) throws Exception { this.previousTime = System.currentTimeMillis(); this.ctx = ctx; if (packet == null || packet.packet == null) { out.add(packet);/*from www . ja v a 2 s. c o m*/ return; } if (packet.packet instanceof PingPacket) { final ServerData data = this.statusListener.update(); this.isPing = true; ProxyServer.getInstance().getScheduler().schedule(this.plugin, new Runnable() { @Override public void run() { // respond with a response packet JsonObject version = new JsonObject(); version.addProperty("name", data.getFormat().replace("%COUNT%", ProxyServer.getInstance().getOnlineCount() + "") .replace("%MAX%", getMaxCount() + "")); version.addProperty("protocol", 10000); JsonObject countData = new JsonObject(); countData.addProperty("max", 0); countData.addProperty("online", 0); JsonObject jsonObject = new JsonObject(); jsonObject.add("version", version); jsonObject.add("players", countData); jsonObject.addProperty("description", data.getMotd()); if (data.getFavicon() != null) { jsonObject.addProperty("favicon", data.getFavicon()); } ctx.pipeline().writeAndFlush(new StatusResponse(jsonObject.toString())); } }, data.getSleepMillis(), TimeUnit.MILLISECONDS); } else if (packet.packet instanceof StatusRequest) { final ServerData data = this.statusListener.update(); // respond with a response packet JsonObject version = new JsonObject(); version.addProperty("name", data.getFormat().replace("%COUNT%", ProxyServer.getInstance().getOnlineCount() + "") .replace("%MAX%", getMaxCount() + "")); version.addProperty("protocol", 10000); JsonObject countData = new JsonObject(); countData.addProperty("max", 0); countData.addProperty("online", 0); JsonObject jsonObject = new JsonObject(); jsonObject.add("version", version); jsonObject.add("players", countData); jsonObject.addProperty("description", data.getMotd()); if (data.getFavicon() != null) { jsonObject.addProperty("favicon", data.getFavicon()); } ctx.pipeline().writeAndFlush(new StatusResponse(jsonObject.toString())); } else { out.add(packet); } }
From source file:me.bigteddy98.mcproxy.protocol.handlers.ClientSideHandler.java
License:Open Source License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { incomingChannel = ctx.channel();//from ww w . j a v a 2s .c o m networkManager.clientsidePipeline = ctx.pipeline(); Bootstrap bootstrab = new Bootstrap(); bootstrab.group(incomingChannel.eventLoop()); bootstrab.channel(ctx.channel().getClass()); bootstrab.handler(serverboundConnectionInitializer = new ServerboundConnectionInitializer(networkManager, incomingChannel)); bootstrab.option(ChannelOption.AUTO_READ, false); ChannelFuture f = bootstrab.connect(hostname, port); outgoingChannel = f.channel(); f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { incomingChannel.read(); } else { incomingChannel.close(); } } }); }
From source file:me.bigteddy98.mcproxy.protocol.handlers.ServerSideHandler.java
License:Open Source License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { networkManager.serversidePipeline = ctx.pipeline(); ctx.read();/*from ww w . j av a2 s .c om*/ ctx.write(Unpooled.EMPTY_BUFFER); }