List of usage examples for io.netty.channel ChannelHandlerContext pipeline
ChannelPipeline pipeline();
From source file:com.quavo.osrs.network.protocol.codec.connection.ConnectionEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext ctx, ConnectionResponse msg, ByteBuf out) throws Exception { ChannelPipeline pipeline = ctx.pipeline(); switch (msg.getType()) { case HANDSHAKE_CONNECTION: pipeline.addAfter("decoder", "handshake.encoder", new HandshakeEncoder()); pipeline.replace("decoder", "handshake.decoder", new HandshakeDecoder()); break;//from www . java 2s . c o m case LOGIN_CONNECTION: out.writeByte(ClientMessage.SUCCESSFUL_CONNECTION.getId()); pipeline.addAfter("decoder", "login.encoder", new LoginEncoder()); pipeline.replace("decoder", "login.decoder", new LoginDecoder()); break; } pipeline.remove(this); }
From source file:com.quavo.osrs.network.protocol.codec.handshake.HandshakeEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext ctx, HandshakeResponse msg, ByteBuf out) throws Exception { ChannelPipeline pipeline = ctx.pipeline(); ClientMessage message = msg.getMessage(); out.writeByte(message.getId());/*from w w w . ja va 2 s.c om*/ if (message == ClientMessage.SUCCESSFUL_CONNECTION) { pipeline.addAfter("handshake.decoder", "xor.encrypt", new XOREncryptionEncoder()); pipeline.addAfter("xor.encrypt", "update.encoder", new UpdateEncoder()); pipeline.replace("handshake.decoder", "update.decoder", new UpdateDecoder()); } pipeline.remove(this); }
From source file:com.quavo.osrs.network.protocol.codec.login.LoginEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext ctx, LoginResponse msg, ByteBuf out) throws Exception { ClientMessage message = msg.getMessage(); ChannelPipeline pipeline = ctx.pipeline(); if (message != ClientMessage.SUCCESSFUL) { // dont write the id for successful. out.writeByte(message.getId());/*from w w w .java2 s .co m*/ } else { pipeline.addAfter("login.decoder", "world.encoder", new WorldLoginEncoder()); pipeline.replace("login.decoder", "world.decoder", new WorldLoginDecoder(msg.getType())); } pipeline.remove(this); }
From source file:com.quavo.osrs.network.protocol.codec.login.world.WorldLoginEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext ctx, WorldLoginResponse msg, ByteBuf out) throws Exception { ClientMessage message = msg.getMessage(); out.writeByte(message.getId());/*from w ww.j a v a2 s .c om*/ if (message == ClientMessage.SUCCESSFUL) { out.writeByte(0); out.writeByte(0); out.writeByte(0); out.writeByte(0); out.writeByte(0); out.writeByte(2);// rights out.writeByte(0); out.writeShort(1);// index out.writeByte(1); } ctx.pipeline().remove(this); }
From source file:com.quavo.osrs.network.protocol.codec.update.encrypt.XOREncryptionEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext ctx, XOREncryptionResponse msg, ByteBuf out) throws Exception { if (msg.getKey() != 0) { for (int i = 0; i < out.writerIndex(); i++) { out.setByte(i, out.getByte(i) ^ msg.getKey()); }//from ww w . ja v a 2 s . c o m } ctx.pipeline().remove(this); }
From source file:com.relayrides.pushy.apns.ApnsClient.java
License:Open Source License
protected ApnsClient(final SslContext sslContext, final EventLoopGroup eventLoopGroup) { this.bootstrap = new Bootstrap(); if (eventLoopGroup != null) { this.bootstrap.group(eventLoopGroup); this.shouldShutDownEventLoopGroup = false; } else {//w w w. j av a2 s .c om this.bootstrap.group(new NioEventLoopGroup(1)); this.shouldShutDownEventLoopGroup = true; } this.bootstrap.channel(SocketChannelClassUtil.getSocketChannelClass(this.bootstrap.config().group())); this.bootstrap.option(ChannelOption.TCP_NODELAY, true); this.bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel channel) throws Exception { final ChannelPipeline pipeline = channel.pipeline(); final ProxyHandlerFactory proxyHandlerFactory = ApnsClient.this.proxyHandlerFactory; if (proxyHandlerFactory != null) { pipeline.addFirst(proxyHandlerFactory.createProxyHandler()); } if (ApnsClient.this.writeTimeoutMillis > 0) { pipeline.addLast( new WriteTimeoutHandler(ApnsClient.this.writeTimeoutMillis, TimeUnit.MILLISECONDS)); } pipeline.addLast(sslContext.newHandler(channel.alloc())); pipeline.addLast(new ApplicationProtocolNegotiationHandler("") { @Override protected void configurePipeline(final ChannelHandlerContext context, final String protocol) { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { final ApnsClientHandler apnsClientHandler = new ApnsClientHandler.ApnsClientHandlerBuilder() .server(false).apnsClient(ApnsClient.this) .authority( ((InetSocketAddress) context.channel().remoteAddress()).getHostName()) .encoderEnforceMaxConcurrentStreams(true).build(); synchronized (ApnsClient.this.bootstrap) { if (ApnsClient.this.gracefulShutdownTimeoutMillis != null) { apnsClientHandler.gracefulShutdownTimeoutMillis( ApnsClient.this.gracefulShutdownTimeoutMillis); } } context.pipeline().addLast( new IdleStateHandler(0, 0, PING_IDLE_TIME_MILLIS, TimeUnit.MILLISECONDS)); context.pipeline().addLast(apnsClientHandler); final ChannelPromise connectionReadyPromise = ApnsClient.this.connectionReadyPromise; if (connectionReadyPromise != null) { connectionReadyPromise.trySuccess(); } } else { throw new IllegalArgumentException("Unexpected protocol: " + protocol); } } }); } }); }
From source file:com.replaymod.sponge.recording.spongecommon.SpongeConnectionEventListener.java
License:MIT License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.pipeline().remove(this).addBefore("packet_handler", "connection_events", this); super.channelActive(ctx); }
From source file:com.rs3e.network.protocol.codec.handshake.HandshakeDecoder.java
License:Open Source License
@Override public void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in) throws Exception { if (!in.readable()) return;/*from w w w . ja v a 2 s . c o m*/ ctx.pipeline().remove(HandshakeDecoder.class); int incomingOpcode = in.readByte() & 0xFF; HandshakeState handshakeState = HandshakeState.forId(incomingOpcode); if (handshakeState == null) { return; } switch (handshakeState) { case HANDSHAKE_UPDATE: ctx.pipeline().addFirst(new UpdateEncoder(), new UpdateStatusEncoder(), new XorEncoder(), new UpdateDecoder()); break; case HANDSHAKE_WORLD_LIST: ctx.pipeline().addFirst(new WorldListEncoder(), new WorldListDecoder()); break; case HANDSHAKE_LOGIN: ctx.pipeline().addFirst(new LoginEncoder(), new LoginDecoder()); ctx.write(new LoginResponse(0)); break; default: break; } ctx.nextInboundMessageBuffer().add(new HandshakeMessage(handshakeState)); ctx.fireInboundBufferUpdated(); if (in.readable()) { ChannelHandlerContext head = ctx.pipeline().firstContext(); head.nextInboundByteBuffer().writeBytes(in.readBytes(in.readableBytes())); head.fireInboundBufferUpdated(); } }
From source file:com.sangupta.swift.netty.http.HttpStaticFileServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext context, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { NettyUtils.sendError(context, HttpResponseStatus.BAD_REQUEST); return;//w w w. java 2 s .c om } if (request.getMethod() != HttpMethod.GET) { NettyUtils.sendError(context, HttpResponseStatus.METHOD_NOT_ALLOWED); return; } final String uri = request.getUri(); final String path = NettyUtils.sanitizeUri(uri); if (path == null) { NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN); return; } File file = new File(documentRoot, path); if (file.isHidden() || !file.exists()) { NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { NettyUtils.sendListing(context, file); } else { NettyUtils.sendRedirect(context, uri + '/'); } return; } if (!file.isFile()) { NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().get(HttpHeaders.Names.IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { Date ifModifiedSinceDate = NettyUtils.parseDateHeader(ifModifiedSince); if (ifModifiedSinceDate != null) { // Only compare up to the second because the datetime format we send to the client // does not have milliseconds long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000; long fileLastModifiedSeconds = file.lastModified() / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { NettyUtils.sendNotModified(context); return; } } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND); return; } final long fileLength = file.length(); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpHeaders.setContentLength(response, fileLength); NettyUtils.setContentTypeHeader(response, file); NettyUtils.setDateAndCacheHeaders(response, file, 3600); // cache for an hour // check for keep alive if (HttpHeaders.isKeepAlive(request)) { response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } // Write the initial line and the header. context.write(response); // Write the content. ChannelFuture sendFileFuture; if (context.pipeline().get(SslHandler.class) == null) { sendFileFuture = context.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), context.newProgressivePromise()); } else { sendFileFuture = context.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), context.newProgressivePromise()); } // sendFileFuture.addListener(new ChannelProgressiveFutureListener() { // // @Override // public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { // if (total < 0) { // total unknown // System.err.println(future.channel() + " Transfer progress: " + progress); // } else { // System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total); // } // } // // @Override // public void operationComplete(ChannelProgressiveFuture future) { // System.err.println(future.channel() + " Transfer complete."); // } // // }); // Write the end marker ChannelFuture lastContentFuture = context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // Decide whether to close the connection or not. if (!HttpHeaders.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.sangupta.swift.netty.spdy.SpdyStaticFileServerHandler.java
License:Apache License
@Override protected void channelRead0(final ChannelHandlerContext context, final FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { NettyUtils.sendError(context, HttpResponseStatus.BAD_REQUEST); return;// w ww .j a va 2 s. c o m } // check for server name if (this.checkServerName) { String host = request.headers().get(HttpHeaders.Names.HOST); if (!host.startsWith(this.swiftServer.getServerName())) { NettyUtils.sendError(context, HttpResponseStatus.BAD_REQUEST); return; } } // check method if (request.getMethod() != HttpMethod.GET) { NettyUtils.sendError(context, HttpResponseStatus.METHOD_NOT_ALLOWED); return; } // check for SPDY support final boolean spdyRequest = request.headers().contains(NettyUtils.SPDY_STREAM_ID); // check for URI path to be proper final String uri = request.getUri(); final String path = NettyUtils.sanitizeUri(uri); if (path == null) { NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN); return; } File file = new File(documentRoot, path); if (file.isHidden() || !file.exists()) { NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { NettyUtils.sendListing(context, file, request.headers().get(NettyUtils.SPDY_STREAM_ID)); return; } // redirect to the listing page NettyUtils.sendRedirect(context, uri + '/'); return; } if (!file.isFile()) { NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().get(HttpHeaders.Names.IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { Date ifModifiedSinceDate = NettyUtils.parseDateHeader(ifModifiedSince); if (ifModifiedSinceDate != null) { // Only compare up to the second because the datetime format we send to the client // does not have milliseconds long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000; long fileLastModifiedSeconds = file.lastModified() / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { NettyUtils.sendNotModified(context); return; } } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND); return; } final long fileLength = file.length(); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpHeaders.setContentLength(response, fileLength); NettyUtils.setContentTypeHeader(response, file); NettyUtils.setDateAndCacheHeaders(response, file, 3600); // cache for an hour // check for keep alive if (HttpHeaders.isKeepAlive(request)) { response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } else { context.write(response).addListener(ChannelFutureListener.CLOSE); } // Write the initial line and the header. context.write(response); // Write the content. ChannelFuture sendFileFuture; if (context.pipeline().get(SslHandler.class) == null) { sendFileFuture = context.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), context.newProgressivePromise()); } else { sendFileFuture = context.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), context.newProgressivePromise()); } // sendFileFuture.addListener(new ChannelProgressiveFutureListener() { // // @Override // public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { // if (total < 0) { // total unknown // System.err.println(future.channel() + " Transfer progress: " + progress); // } else { // System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total); // } // } // // @Override // public void operationComplete(ChannelProgressiveFuture future) { // System.err.println(future.channel() + " Transfer complete."); // } // // }); // Write the end marker ChannelFuture lastContentFuture = context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // Decide whether to close the connection or not. if (!HttpHeaders.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }