List of usage examples for io.netty.channel ChannelHandlerContext pipeline
ChannelPipeline pipeline();
From source file:com.chuck.netty4.websocket.WebSocketIndexPageHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { // Handle a bad request. if (!req.decoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;//from www .ja va 2 s . c o m } // Allow only GET methods. if (req.method() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Send the index page if ("/".equals(req.uri()) || "/index.html".equals(req.uri())) { String webSocketLocation = getWebSocketLocation(ctx.pipeline(), req, websocketPath); ByteBuf content = WebSocketServerIndexPage.getContent(webSocketLocation); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8"); HttpUtil.setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); } else { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND)); } }
From source file:com.cmz.http.file.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.decoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);// w w w . j a v a 2s . c om 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, uri); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } // 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 = 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); HttpUtil.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpUtil.isKeepAlive(request)) { response.headers().set(HttpHeaderNames.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.writeAndFlush(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 (!HttpUtil.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.corundumstudio.socketio.handler.ResourceHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); URL resUrl = resources.get(queryDecoder.path()); if (resUrl != null) { URLConnection fileUrl = resUrl.openConnection(); long lastModified = fileUrl.getLastModified(); // check if file has been modified since last request if (isNotModified(req, lastModified)) { sendNotModified(ctx);//from w ww .j a v a2 s . co m req.release(); return; } // create resource input-stream and check existence final InputStream is = fileUrl.getInputStream(); if (is == null) { sendError(ctx, NOT_FOUND); return; } // create ok response HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); // set Content-Length header setContentLength(res, fileUrl.getContentLength()); // set Content-Type header setContentTypeHeader(res, fileUrl); // set Date, Expires, Cache-Control and Last-Modified headers setDateAndCacheHeaders(res, lastModified); // write initial response header ctx.write(res); // write the content stream ctx.pipeline().addBefore(SocketIOChannelInitializer.RESOURCE_HANDLER, "chunkedWriter", new ChunkedWriteHandler()); ChannelFuture writeFuture = ctx.channel().write(new ChunkedStream(is, fileUrl.getContentLength())); // add operation complete listener so we can close the channel and the input stream writeFuture.addListener(ChannelFutureListener.CLOSE); return; } } ctx.fireChannelRead(msg); }
From source file:com.corundumstudio.socketio.transport.FlashPolicyHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof ByteBuf) { ByteBuf message = (ByteBuf) msg; ByteBuf data = message.slice(0, requestBuffer.readableBytes()); if (data.equals(requestBuffer)) { message.release();/*from w ww. ja va 2 s.co m*/ ChannelFuture f = ctx.writeAndFlush(Unpooled.copiedBuffer(responseBuffer)); f.addListener(ChannelFutureListener.CLOSE); return; } ctx.pipeline().remove(this); } ctx.fireChannelRead(msg); }
From source file:com.corundumstudio.socketio.transport.FlashUrlLoaderPolicyHandler.java
License:Apache License
/** * Channel read callback//w w w . ja v a2 s . com * * @param ctx * @param msg * @throws Exception */ @Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { if (msg instanceof HttpRequest) { final FullHttpRequest request = (FullHttpRequest) msg; if (request.getUri().contains("crossdomain.xml")) { writeCrossdomainDotXml(ctx, request); request.release(); ctx.pipeline().remove(this); return; } ctx.pipeline().remove(this); } ctx.fireChannelRead(msg); }
From source file:com.corundumstudio.socketio.transport.PollingTransport.java
License:Apache License
private void onPost(UUID sessionId, ChannelHandlerContext ctx, String origin, ByteBuf content) throws IOException { ClientHead client = clientsBox.get(sessionId); if (client == null) { log.error("{} is not registered. Closing connection", sessionId); sendError(ctx);//from w ww.j av a 2s.c o m return; } // release POST response before message processing ctx.channel().writeAndFlush(new XHRPostMessage(origin, sessionId)); Boolean b64 = ctx.channel().attr(EncoderHandler.B64).get(); if (b64 != null && b64) { Integer jsonIndex = ctx.channel().attr(EncoderHandler.JSONP_INDEX).get(); content = decoder.preprocessJson(jsonIndex, content); } ctx.pipeline().fireChannelRead(new PacketsMessage(client, content, Transport.POLLING)); }
From source file:com.corundumstudio.socketio.transport.WebSocketTransport.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof CloseWebSocketFrame) { ctx.channel().close();/* w w w . ja v a2 s . c om*/ ReferenceCountUtil.release(msg); } else if (msg instanceof BinaryWebSocketFrame || msg instanceof TextWebSocketFrame) { ByteBufHolder frame = (ByteBufHolder) msg; ClientHead client = clientsBox.get(ctx.channel()); if (client == null) { log.debug("Client with was already disconnected. Channel closed!"); ctx.channel().close(); frame.release(); return; } ctx.pipeline().fireChannelRead(new PacketsMessage(client, frame.content(), Transport.WEBSOCKET)); frame.release(); } else if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); String path = queryDecoder.path(); List<String> transport = queryDecoder.parameters().get("transport"); List<String> sid = queryDecoder.parameters().get("sid"); if (transport != null && NAME.equals(transport.get(0))) { try { if (!configuration.getTransports().contains(Transport.WEBSOCKET)) { log.debug("{} transport not supported by configuration.", Transport.WEBSOCKET); ctx.channel().close(); return; } if (sid != null && sid.get(0) != null) { final UUID sessionId = UUID.fromString(sid.get(0)); handshake(ctx, sessionId, path, req); } else { ClientHead client = ctx.channel().attr(ClientHead.CLIENT).get(); // first connection handshake(ctx, client.getSessionId(), path, req); } } finally { req.release(); } } else { ctx.fireChannelRead(msg); } } else { ctx.fireChannelRead(msg); } }
From source file:com.corundumstudio.socketio.transport.XHRPollingTransport.java
License:Apache License
private void onPost(UUID sessionId, ChannelHandlerContext ctx, String origin, ByteBuf content) throws IOException { XHRPollingClient client = sessionId2Client.get(sessionId); if (client == null) { log.debug("Client with sessionId: {} was already disconnected. Channel closed!", sessionId); ctx.channel().close();//w ww . j a va 2 s .com return; } // release POST response before message processing ctx.channel().writeAndFlush(new XHROutMessage(origin, sessionId)); ctx.pipeline().fireChannelRead(new PacketsMessage(client, content)); }
From source file:com.couchbase.client.core.endpoint.AbstractGenericHandler.java
License:Apache License
@Override public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { CouchbaseRequest keepAlive = createKeepAliveRequest(); if (keepAlive != null) { keepAlive.observable().subscribe(new KeepAliveResponseAction(ctx)); onKeepAliveFired(ctx, keepAlive); Channel channel = ctx.channel(); if (channel.isActive() && channel.isWritable()) { ctx.pipeline().writeAndFlush(keepAlive); }//www. ja v a 2 s . co m } } else { super.userEventTriggered(ctx, evt); } }
From source file:com.couchbase.client.core.endpoint.dcp.DCPConnectionHandler.java
License:Apache License
/** * Dispatches incoming OPEN_CONNECTION responses and also initialize flow control. * * @param ctx the handler context.// w ww . j av a 2 s .co m * @param msg the incoming message to investigate. * @throws Exception if something goes wrong during negotiation. */ @Override protected void channelRead0(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception { if (msg.getOpcode() == DCPHandler.OP_OPEN_CONNECTION) { if (msg.getStatus() == KeyValueStatus.SUCCESS.code()) { if (env.dcpConnectionBufferSize() > 0) { FullBinaryMemcacheRequest request = controlRequest(ctx, ControlParameter.CONNECTION_BUFFER_SIZE, env.dcpConnectionBufferSize()); ChannelFuture future = ctx.writeAndFlush(request); future.addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(Future<Void> future) throws Exception { if (!future.isSuccess()) { LOGGER.warn("Error during setting CONNECTION_BUFFER_SIZE for DCP connection: {}.", future); } } }); } else { originalPromise.setSuccess(); ctx.pipeline().remove(this); ctx.fireChannelActive(); } } else { originalPromise.setFailure( new IllegalStateException("Bad status for DCP Open Connection: " + msg.getStatus())); } } else if (msg.getOpcode() == DCPHandler.OP_CONTROL) { if (msg.getStatus() == KeyValueStatus.SUCCESS.code()) { originalPromise.setSuccess(); ctx.pipeline().remove(this); ctx.fireChannelActive(); } else { originalPromise.setFailure(new IllegalStateException( "Bad status for setting CONNECTION_BUFFER_SIZE DCP Open Connection: " + msg.getStatus())); } } }