List of usage examples for io.netty.channel ChannelHandlerContext pipeline
ChannelPipeline pipeline();
From source file:eu.jangos.realm.network.handler.CharacterHandler.java
License:Apache License
@Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { if (ctx.pipeline().get(RealmAuthHandler.class).getAccount() != null) { worldService.removeSession(ctx.pipeline().get(RealmAuthHandler.class).getAccount().getId()); }//from ww w .j a va 2s . c om }
From source file:eu.smartenit.unada.tpm.TeamCymruWhoisClientHandler.java
License:Apache License
/** * Handles response from IP to ASN Mapping service. * * @param ctx the {@link ChannelHandlerContext} which this * {@link SimpleChannelInboundHandler} belongs to * @param msg the message to handle//from ww w. ja v a 2 s. co m * @throws Exception is thrown if an error occurred */ @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { logger.debug("Reading from channel " + ctx.pipeline().channel() + ": \"" + msg + "\""); if (msg.startsWith("Bulk mode;")) { return; } Matcher m = responseLine.matcher(msg); if (m.matches()) { asMap.put((Inet4Address) InetAddress.getByName(m.group(2)), Integer.parseInt(m.group(1))); } else { throw new UnsupportedOperationException("Could not parse \"" + msg + "\""); } }
From source file:example.http2.helloworld.frame.server.Http2OrHttpHandler.java
License:Apache License
@Override protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { ctx.pipeline().addLast(Http2FrameCodecBuilder.forServer().build(), new HelloWorldHttp2Handler()); return;//w ww . j a va 2s.c om } if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) { ctx.pipeline().addLast(new HttpServerCodec(), new HttpObjectAggregator(MAX_CONTENT_LENGTH), new HelloWorldHttp1Handler("ALPN Negotiation")); return; } throw new IllegalStateException("unknown protocol: " + protocol); }
From source file:example.http2.helloworld.multiplex.server.Http2OrHttpHandler.java
License:Apache License
@Override protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception { if (ApplicationProtocolNames.HTTP_2.equals(protocol)) { ctx.pipeline().addLast(Http2MultiplexCodecBuilder.forServer(new HelloWorldHttp2Handler()).build()); return;//from w w w .ja v a2 s. c o m } if (ApplicationProtocolNames.HTTP_1_1.equals(protocol)) { ctx.pipeline().addLast(new HttpServerCodec(), new HttpObjectAggregator(MAX_CONTENT_LENGTH), new HelloWorldHttp1Handler("ALPN Negotiation")); return; } throw new IllegalStateException("unknown protocol: " + protocol); }
From source file:example.http2.helloworld.server.Http2ServerInitializer.java
License:Apache License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0 *//* w ww. j av a2 s . c o m*/ private void configureClearText(SocketChannel ch) { final ChannelPipeline p = ch.pipeline(); final HttpServerCodec sourceCodec = new HttpServerCodec(); final HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory); final CleartextHttp2ServerUpgradeHandler cleartextHttp2ServerUpgradeHandler = new CleartextHttp2ServerUpgradeHandler( sourceCodec, upgradeHandler, new HelloWorldHttp2HandlerBuilder().build()); p.addLast(cleartextHttp2ServerUpgradeHandler); p.addLast(new SimpleChannelInboundHandler<HttpMessage>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception { // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP. System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)"); ChannelPipeline pipeline = ctx.pipeline(); ChannelHandlerContext thisCtx = pipeline.context(this); pipeline.addAfter(thisCtx.name(), null, new HelloWorldHttp1Handler("Direct. No Upgrade Attempted.")); pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength)); ctx.fireChannelRead(ReferenceCountUtil.retain(msg)); } }); p.addLast(new UserEventLogger()); }
From source file:fr.kissy.zergling_push.infrastructure.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 va2 s . c o m return; } if (request.method() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.uri(); final String path = sanitizeUri(uri); File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); 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 lastContentFuture; if (ctx.pipeline().get(SslHandler.class) == null) { ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); } // 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:fr.meuret.web.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);/*w w w .ja va2 s. c om*/ return; } if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.getUri(); final String relativePath = sanitizeUri(uri); if (relativePath == null) { sendError(ctx, FORBIDDEN); return; } Path fileAbsolutePath = rootPath.resolve(relativePath); if (Files.isHidden(fileAbsolutePath) || Files.notExists(fileAbsolutePath)) { sendError(ctx, NOT_FOUND); return; } if (Files.isDirectory(fileAbsolutePath)) { if (uri.endsWith("/")) { sendListing(ctx, rootPath, fileAbsolutePath); } else { sendRedirect(ctx, uri + '/'); } return; } if (!Files.isRegularFile(fileAbsolutePath)) { 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 = Files.getLastModifiedTime(fileAbsolutePath).to(TimeUnit.SECONDS); if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { sendNotModified(ctx); return; } } RandomAccessFile raf; File file = fileAbsolutePath.toFile(); 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); setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (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; //Zero-copy transfer is SSL is not enabled if (ctx.pipeline().get(SslHandler.class) == null) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); } else { sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); } sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) { // total unknown logger.info("{} Transfer progress: {}", future.channel(), progress); } else { logger.info("{} Transfer progress: {} / {}", future.channel(), progress, total); } } @Override public void operationComplete(ChannelProgressiveFuture future) { logger.info("{} Transfer complete.", future.channel()); } }); // Write the end marker ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // Decide whether to close the connection or not. if (!isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:fslib.net.FSChannelHandler.java
License:Open Source License
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { ctx.pipeline().addLast("fslib:FMLToPacketCodec", new FMLToPacketCodec()); }
From source file:gedi.remote.RemoteConnections.java
License:Apache License
/** * Connects to the given server; the mechanics is as follows: * <br/>/*from www .ja v a 2s . c om*/ * The initChannel consumer is supposed to register channel handlers (called upon channel.registered) * <br/> * Depending on the outcome of the Bootrap.connect method, either the errorHandler or the connectedHandler is called. * <br/> * If the connection is lost, the closedHandler is called. * <br/> * If you want to cancel the connection attempt, invoke cancel on the returned ChannelFuture. If you want to terminate the connection, use the * channel object from the connectedHandler. * <br /> * If the channel is unregistered, the added flag is reset for all handlers bound to the channel pipeline (important if you want to reuse * the handlers added by the initChannel consumer). * * @param uri * @param initChannel * @param errorHandler * @param connectedHandler * @param closedHandler * @return */ public ChannelFuture connect(URI uri, Consumer<SocketChannel> initChannel, Consumer<Throwable> errorHandler, Consumer<SocketChannel> connectedHandler, Runnable closedHandler) { final Protocol protocol = ProtocolExtensionPoint.getInstance().get(ExtensionContext.emptyContext(), uri.getScheme()); if (protocol == null) throw new RuntimeException("Protocol " + uri.getScheme() + " unknown!"); EventLoopGroup group = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); protocol.setCodecs(pipeline); initChannel.accept(ch); pipeline.addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { pipeline.addLast(new ConfigLoggingHandler(ConfigLoggingHandler.LogLevel.INFO)); connectedHandler.accept(ch); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); closedHandler.run(); } @Override public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { ctx.pipeline().iterator().forEachRemaining((e) -> Workarounds.removeAdded(e.getValue())); super.channelUnregistered(ctx); } }); } }); // Make a new connection and wait until closed. ChannelFuture f = b.connect(uri.getHost(), uri.getPort() == -1 ? protocol.getDefaultPort() : uri.getPort()) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { Throwable cause = future.cause(); if (cause != null) { log.log(Level.INFO, "Connection failed to server " + uri + ": " + cause.getMessage()); try { errorHandler.accept(cause); } finally { group.shutdownGracefully(); } } else { log.log(Level.INFO, "Client connected to server " + uri); future.channel().closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { log.log(Level.INFO, "Connection closed to server " + uri); group.shutdownGracefully(); } }); } } }); return f; }
From source file:gribbit.http.request.Request.java
License:Open Source License
public Request(ChannelHandlerContext ctx, HttpRequest httpReq) throws ResponseException { this.reqReceivedTimeEpochMillis = System.currentTimeMillis(); this.httpRequest = httpReq; HttpHeaders headers = httpReq.headers(); // Netty changes the URI of the request to "/bad-request" if the HTTP request was malformed this.rawURL = httpReq.uri(); if (rawURL.equals("/bad-request")) { throw new BadRequestException(); } else if (rawURL.isEmpty()) { rawURL = "/"; }/*from w ww . java 2s . c o m*/ // Decode the URL RequestURL requestURL = new RequestURL(rawURL); this.normalizedURL = requestURL.getNormalizedPath(); this.queryParamToVals = requestURL.getQueryParams(); // TODO: figure out how to detect HTTP/2 connections this.httpVersion = httpReq.protocolVersion().toString(); // Get HTTP2 stream ID this.streamId = headers.getAsString(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text()); this.isSecure = ctx.pipeline().get(SslHandler.class) != null; // TODO: is this correct for HTTP2? // Decode cookies try { for (CharSequence cookieHeader : headers.getAll(COOKIE)) { for (Cookie cookie : ServerCookieDecoder.STRICT.decode(cookieHeader.toString())) { // Log.fine("Cookie in request: " + nettyCookie); if (cookieNameToCookies == null) { cookieNameToCookies = new HashMap<>(); } String cookieName = cookie.name(); // Multiple cookies may be present in the request with the same name but with different paths ArrayList<Cookie> cookiesWithThisName = cookieNameToCookies.get(cookieName); if (cookiesWithThisName == null) { cookieNameToCookies.put(cookieName, cookiesWithThisName = new ArrayList<>()); } cookiesWithThisName.add(cookie); } } } catch (IllegalArgumentException e) { // Malformed cookies cause ServerCookieDecoder to throw IllegalArgumentException // Log.info("Malformed cookie in request"); throw new BadRequestException(); } // Sort cookies into decreasing order of path length, in case client doesn't conform to RFC6295, // delivering the cookies in this order itself. This allows us to get the most likely single // cookie for a given cookie name by reading the first cookie in a list for a given name. if (cookieNameToCookies != null) { for (Entry<String, ArrayList<Cookie>> ent : cookieNameToCookies.entrySet()) { Collections.sort(ent.getValue(), COOKIE_COMPARATOR); } } this.method = httpReq.method(); // Force the GET method if HEAD is requested this.isHEADRequest = this.method == HttpMethod.HEAD; if (this.isHEADRequest) { this.method = HttpMethod.GET; } this.isKeepAlive = HttpUtil.isKeepAlive(httpReq) && httpReq.protocolVersion().equals(HttpVersion.HTTP_1_0); CharSequence host = headers.get(HOST); this.host = host == null ? null : host.toString(); this.xRequestedWith = headers.get("X-Requested-With"); this.accept = headers.get(ACCEPT); this.acceptCharset = headers.get(ACCEPT_CHARSET); this.acceptLanguage = headers.get(ACCEPT_LANGUAGE); this.origin = headers.get(ORIGIN); this.referer = headers.get(REFERER); this.userAgent = headers.get(USER_AGENT); InetSocketAddress requestorSocketAddr = (InetSocketAddress) ctx.channel().remoteAddress(); if (requestorSocketAddr != null) { InetAddress address = requestorSocketAddr.getAddress(); if (address != null) { this.requestor = address.getHostAddress(); } } CharSequence acceptEncoding = headers.get(ACCEPT_ENCODING); this.acceptEncodingGzip = acceptEncoding != null && acceptEncoding.toString().toLowerCase().contains("gzip"); this.ifModifiedSince = headers.get(IF_MODIFIED_SINCE); if (this.ifModifiedSince != null && this.ifModifiedSince.length() > 0) { this.ifModifiedSinceEpochSecond = ZonedDateTime .parse(this.ifModifiedSince, DateTimeFormatter.RFC_1123_DATE_TIME).toEpochSecond(); } // // If this is a hash URL, look up original URL whose served resource was hashed to give this hash URL. // // We only need to serve the resource at a hash URL once per resource per client, since resources served // // from hash URLs are indefinitely cached in the browser. // // TODO: Move cache-busting out of http package // this.urlHashKey = CacheExtension.getHashKey(this.urlPath); // this.urlPathUnhashed = this.urlHashKey != null ? CacheExtension.getOrigURL(this.urlPath) : this.urlPath; // // Get flash messages from cookie, if any // this.flashMessages = FlashMessage.fromCookieString(getCookieValue(Cookie.FLASH_COOKIE_NAME)); }