List of usage examples for io.netty.channel ChannelHandlerContext pipeline
ChannelPipeline pipeline();
From source file:com.mapple.socksproxy.SocksServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, SocksMessage socksRequest) throws Exception { switch (socksRequest.version()) { case SOCKS4a: Socks4CommandRequest socksV4CmdRequest = (Socks4CommandRequest) socksRequest; if (socksV4CmdRequest.type() == Socks4CommandType.CONNECT) { ctx.pipeline().addLast(new SocksServerConnectHandler()); ctx.pipeline().remove(this); ctx.fireChannelRead(socksRequest); } else {//from w ww . j a v a 2s . co m ctx.close(); } break; case SOCKS5: if (socksRequest instanceof Socks5InitialRequest) { // auth support example //ctx.pipeline().addFirst(new Socks5PasswordAuthRequestDecoder()); //ctx.write(new DefaultSocks5AuthMethodResponse(Socks5AuthMethod.PASSWORD)); ctx.pipeline().addFirst(new Socks5CommandRequestDecoder()); ctx.write(new DefaultSocks5InitialResponse(Socks5AuthMethod.NO_AUTH)); } else if (socksRequest instanceof Socks5PasswordAuthRequest) { ctx.pipeline().addFirst(new Socks5CommandRequestDecoder()); ctx.write(new DefaultSocks5PasswordAuthResponse(Socks5PasswordAuthStatus.SUCCESS)); } else if (socksRequest instanceof Socks5CommandRequest) { /*Socks5InitialRequestDecoder handle = ctx.pipeline().get(Socks5InitialRequestDecoder.class); if(handle != null) { System.out.println("LWZ Remove" + handle); ctx.pipeline().remove(handle); }*/ Socks5CommandRequest socks5CmdRequest = (Socks5CommandRequest) socksRequest; if (socks5CmdRequest.type() == Socks5CommandType.CONNECT) { ctx.pipeline().addLast(new SocksServerConnectHandler()); ctx.pipeline().remove(this); ctx.fireChannelRead(socksRequest); } else { ctx.close(); } } else { ctx.close(); } break; case UNKNOWN: ctx.close(); break; } }
From source file:com.metasoft.empire.net.websocket.WebSocketIndexPageHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // Handle a bad request. if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;//from ww w . j a v a2s .co m } // Allow only GET methods. if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } if (websocketPath.equals(req.getUri())) { return; } // Send the index page if ("/".equals(req.getUri()) || "/index.html".equals(req.getUri())) { String webSocketLocation = getWebSocketLocation(ctx.pipeline(), req, websocketPath); ByteBuf content = WebSocketServerIndexPage.getContent(webSocketLocation); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8"); HttpHeaders.setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); } else { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND)); } }
From source file:com.netty.fileTest.http.download.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);// w ww .j a va 2 s . c o m return; } if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.getUri(); final String path = sanitizeUri(uri); if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { sendListing(ctx, file); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); // 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) { sendNotModified(ctx); return; } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpHeaders.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpHeaders.isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; if (ctx.pipeline().get(SslHandler.class) == null) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); // Write the end marker. lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); // HttpChunkedInput will write the end marker (LastHttpContent) for us. lastContentFuture = sendFileFuture; } 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."); } }); // 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.netty.game.server.handler.LoginHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ServerCustomMsg.CustomMsg req = (ServerCustomMsg.CustomMsg) msg; System.out.println("received msg: \n" + req); if (req.getCmd() != ServerConfigData.CMD_LOGIN) { ctx.writeAndFlush(resp(ServerConfigData.CMD_LOGIN, -1, "")); ctx.close();/*w ww.j a va 2s. c o m*/ throw new IllegalArgumentException("<LoginHandler>cmd error! must be login cmd!"); } String userName = req.getParamValueByKey(ServerConfigData.KEY_PARAM_USER_NAME); String pwd = req.getParamValueByKey(ServerConfigData.KEY_PARAM_PASSWORD); if (StringUtils.isBlank(userName) || StringUtils.isBlank(pwd)) { ctx.writeAndFlush(resp(ServerConfigData.CMD_LOGIN, -2, "?")); ctx.close(); throw new IllegalArgumentException("<LoginHandler>param empty!"); } if (!AccountValidate.INSTANCE.isValidate(userName, pwd)) { ctx.writeAndFlush(resp(ServerConfigData.CMD_LOGIN, -3, "??")); ctx.close(); throw new IllegalArgumentException( String.format("<LoginHandler>account validate error! user is %s", userName)); } ctx.pipeline().replace(ServerConfigData.LOGIN_HANDLER_NAME, ServerConfigData.EXT_HANDLER_NAME, new ExtHandler()); ctx.writeAndFlush(resp(ServerConfigData.CMD_LOGIN, 1, "?")); GameUser user = new GameUser(userName, ctx.channel()); ChannelManager.instance.addUser(user); }
From source file:com.ning.http.client.providers.netty_4.NettyAsyncHttpProvider.java
License:Apache License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception { Channel channel = ctx.channel(); Throwable cause = e.getCause(); NettyResponseFuture<?> future = null; /** Issue 81/* w w w .j a va 2 s . co m*/ if (e.getCause() != null && e.getCause().getClass().isAssignableFrom(PrematureChannelClosureException.class)) { return; } */ if (e.getCause() != null && e.getCause().getClass().getSimpleName().equals("PrematureChannelClosureException")) { return; } if (log.isDebugEnabled()) { log.debug("Unexpected I/O exception on channel {}", channel, cause); } try { if (cause != null && ClosedChannelException.class.isAssignableFrom(cause.getClass())) { return; } if (ctx.attr(DEFAULT_ATTRIBUTE).get() instanceof NettyResponseFuture<?>) { future = (NettyResponseFuture<?>) ctx.attr(DEFAULT_ATTRIBUTE).get(); future.attachChannel(null, false); future.touch(); if (IOException.class.isAssignableFrom(cause.getClass())) { if (config.getIOExceptionFilters().size() > 0) { FilterContext<?> fc = new FilterContext.FilterContextBuilder() .asyncHandler(future.getAsyncHandler()).request(future.getRequest()) .ioException(new IOException("Channel Closed")).build(); fc = handleIoException(fc, future); if (fc.replayRequest()) { replayRequest(future, fc, null, ctx); return; } } else { // Close the channel so the recovering can occurs. try { ctx.channel().close(); } catch (Throwable t) { ; // Swallow. } return; } } if (abortOnReadCloseException(cause) || abortOnWriteCloseException(cause)) { log.debug("Trying to recover from dead Channel: {}", channel); return; } } else if (ctx.attr(DEFAULT_ATTRIBUTE).get() instanceof AsyncCallable) { future = ((AsyncCallable) ctx.attr(DEFAULT_ATTRIBUTE).get()).future(); } } catch (Throwable t) { cause = t; } if (future != null) { try { log.debug("Was unable to recover Future: {}", future); abort(future, cause); } catch (Throwable t) { log.error(t.getMessage(), t); } } Protocol p = (ctx.pipeline().get(HttpClientCodec.class) != null ? httpProtocol : webSocketProtocol); p.onError(ctx, e); closeChannel(ctx); ctx.sendUpstream(e); }
From source file:com.ociweb.pronghorn.adapter.netty.impl.HttpStaticFileServerHandler.java
License:Apache License
public static void sendFile(ChannelHandlerContext ctx, FullHttpRequest request, File file) throws ParseException, IOException { long lastModified = file.lastModified(); String path = file.getPath(); // Cache Validation String ifModifiedSince = request.headers().get(HttpHeaderNames.IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); // 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 = lastModified / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { sendNotModified(ctx);//from ww w. j a v a2 s . com return; } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { sendError(ctx, NOT_FOUND); return; } long fileLength = file.length(); beginHTTPResponse(ctx, request, lastModified, path, fileLength); // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; if (ctx.pipeline().get(SslHandler.class) == null) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); // Write the end marker. lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { FileInputStream input = new FileInputStream(file); byte[] data = new byte[(int) fileLength]; //big hack to convert into byteBuf int pos = 0; int remaining = (int) fileLength; while (remaining > 0) { int len = input.read(data, pos, remaining); remaining -= len; pos += len; } sendFileFuture = ctx.write(Unpooled.wrappedBuffer(data), ctx.newProgressivePromise()); lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } progressAndClose(request, sendFileFuture, lastContentFuture); }
From source file:com.otcdlink.chiron.downend.Http11ProxyHandler.java
License:Apache License
@Override protected void addCodec(ChannelHandlerContext ctx) throws Exception { ChannelPipeline p = ctx.pipeline(); String name = ctx.name();// w ww. j a v a2s . com p.addBefore(name, null, codec); }
From source file:com.phei.netty.nio.http.file.HttpStaticFileServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.decoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);/*ww w. j a v a2 s. co m*/ return; } if (request.method() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.uri(); final String path = sanitizeUri(uri); if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { sendListing(ctx, file); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().getAndConvert(IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); // 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) { sendNotModified(ctx); return; } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpHeaderUtil.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpHeaderUtil.isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; if (ctx.pipeline().get(SslHandler.class) == null) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); // Write the end marker. lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); // HttpChunkedInput will write the end marker (LastHttpContent) for us. lastContentFuture = sendFileFuture; } 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."); } }); // Decide whether to close the connection or not. if (!HttpHeaderUtil.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.quavo.osrs.network.handler.listener.WorldLoginListener.java
License:Open Source License
@Override public void handleMessage(ChannelHandlerContext ctx, WorldLoginRequest msg) { ClientMessage message = evaluateLogin(msg); if (message != ClientMessage.SUCCESSFUL) { ctx.write(new WorldLoginResponse(message)); return;//from ww w .j av a 2 s . c o m } Player player = new Player(ctx.channel()); ctx.write(new WorldLoginResponse(player, message, msg.getIsaacPair())); ChannelPipeline pipeline = ctx.pipeline(); pipeline.remove("login.encoder"); // this isnt set automatically. pipeline.addAfter("world.decoder", "game.encoder", new GamePacketEncoder(msg.getIsaacPair().getEncoderRandom())); pipeline.replace("world.decoder", "game.decoder", new GamePacketDecoder(player, msg.getIsaacPair().getDecoderRandom())); player.init(msg.getDisplayInformation()); }
From source file:com.quavo.osrs.network.NetworkMessageHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, NetworkMessage msg) throws Exception { NetworkMessageListener<NetworkMessage> listener = NetworkMessageRepository.getNetworkListener(msg); listener.handleMessage(ctx, msg);/*from w w w . j a va2s. c om*/ ChannelPipeline pipeline = ctx.pipeline(); ChannelHandler handler = msg.getHandler(); if (pipeline.context(handler) != null) { // flush for specific handler. pipeline.context(handler).flush(); } }