List of usage examples for io.netty.channel ChannelFuture addListener
@Override ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);
From source file:com.king.platform.net.http.netty.request.InputStreamHttpBody.java
License:Apache License
@Override public ChannelFuture writeContent(ChannelHandlerContext ctx) throws IOException { final InputStream is = inputStream; Channel channel = ctx.channel(); ChannelFuture channelFuture = channel.write(new ChunkedStream(inputStream), channel.newProgressivePromise()); channelFuture.addListener(new ChannelFutureListener() { @Override//from w w w. j a va 2 s .com public void operationComplete(ChannelFuture future) throws Exception { is.close(); } }); return channelFuture; }
From source file:com.king.platform.net.http.netty.request.InputStreamHttpBodyTest.java
License:Apache License
@Test public void operationCompletedShouldCloseInputStream() throws Exception { ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); Channel channel = mock(Channel.class); when(ctx.channel()).thenReturn(channel); ChannelFuture channelFuture = mock(ChannelFuture.class); when(channel.write(any(ChunkedStream.class), any(ChannelPromise.class))).thenReturn(channelFuture); when(channelFuture.addListener(any(ChannelFutureListener.class))).thenAnswer(new CallHandler() { @Override// ww w . j a v a 2 s . c om public Object invoke(Object obj, MethodCall call) throws Throwable { ChannelFutureListener channelFutureListener = (ChannelFutureListener) call.getArguments()[0]; channelFutureListener.operationComplete(mock(ChannelFuture.class)); return null; } }); inputStreamHttpBody.writeContent(ctx, false); verifyOnce().on(inputStream).close(); }
From source file:com.l2jmobius.gameserver.network.telnet.TelnetServerHandler.java
License:Open Source License
@Override public void channelActive(ChannelHandlerContext ctx) { String ip = ctx.channel().remoteAddress().toString(); ip = ip.substring(1, ip.lastIndexOf(':')); // Trim out /127.0.0.1:14013 if (!Config.TELNET_HOSTS.contains(ip)) { final ChannelFuture future = ctx.write("Your ip: " + ip + " is not allowed to connect." + Config.EOL); future.addListener(ChannelFutureListener.CLOSE); ctx.flush();//from ww w.j a v a 2 s. com return; } // Send greeting for a new connection. ctx.write("Welcome to the telnet session." + Config.EOL); ctx.write("It is " + new Date() + " now." + Config.EOL); ctx.write("Please enter your password:" + Config.EOL); if (!Config.TELNET_PASSWORD.isEmpty()) { // Ask password ctx.write("Password:"); ctx.attr(AUTHORIZED).set(Boolean.FALSE); } else { ctx.write("Type 'help' to see all available commands." + Config.EOL); ctx.attr(AUTHORIZED).set(Boolean.TRUE); } ctx.flush(); }
From source file:com.l2jmobius.gameserver.network.telnet.TelnetServerHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { // Cast to a String first. // We know it is a String because we put some codec in TelnetPipelineFactory. String request = (String) msg; // Generate and write a response. String response = null;//from w ww . j av a 2 s .c o m boolean close = false; if (Boolean.FALSE.equals(ctx.attr(AUTHORIZED).get())) { if (Config.TELNET_PASSWORD.equals(request)) { ctx.attr(AUTHORIZED).set(Boolean.TRUE); request = ""; } else { response = "Wrong password!" + Config.EOL; close = true; } } if (Boolean.TRUE.equals(ctx.attr(AUTHORIZED).get())) { if (request.isEmpty()) { response = "Type 'help' to see all available commands." + Config.EOL; } else if (request.toLowerCase().equals("exit")) { response = "Have a good day!" + Config.EOL; close = true; } else { final Matcher m = COMMAND_ARGS_PATTERN.matcher(request); if (m.find()) { final String command = m.group(); final List<String> args = new ArrayList<>(); String arg; while (m.find()) { arg = m.group(1); if (arg == null) { arg = m.group(0); } args.add(arg); } response = tryHandleCommand(ctx, command, args.toArray(new String[args.size()])); if (!response.endsWith(Config.EOL)) { response += Config.EOL; } } } } // We do not need to write a ChannelBuffer here. // We know the encoder inserted at TelnetPipelineFactory will do the conversion. final ChannelFuture future = ctx.write(response); // Close the connection after sending 'Have a good day!' // if the client has sent 'exit'. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.lambdaworks.redis.AbstractRedisClient.java
License:Apache License
/** * Connect and initialize a channel from {@link ConnectionBuilder}. * * @param connectionBuilder must not be {@literal null}. * @return the {@link ConnectionFuture} to synchronize the connection process. * @since 4.4// www . jav a 2s . co m */ @SuppressWarnings("unchecked") protected <K, V, T extends RedisChannelHandler<K, V>> ConnectionFuture<T> initializeChannelAsync( ConnectionBuilder connectionBuilder) { SocketAddress redisAddress = connectionBuilder.socketAddress(); if (clientResources.eventExecutorGroup().isShuttingDown()) { throw new IllegalStateException("Cannot connect, Event executor group is terminated."); } logger.debug("Connecting to Redis at {}", redisAddress); CompletableFuture<Channel> channelReadyFuture = new CompletableFuture<>(); Bootstrap redisBootstrap = connectionBuilder.bootstrap(); RedisChannelInitializer initializer = connectionBuilder.build(); redisBootstrap.handler(initializer); ChannelFuture connectFuture = redisBootstrap.connect(redisAddress); connectFuture.addListener(future -> { if (!future.isSuccess()) { logger.debug("Connecting to Redis at {}: {}", redisAddress, future.cause()); connectionBuilder.commandHandler().initialState(); channelReadyFuture.completeExceptionally(future.cause()); return; } CompletableFuture<Boolean> initFuture = (CompletableFuture<Boolean>) initializer.channelInitialized(); initFuture.whenComplete((success, throwable) -> { if (throwable == null) { logger.debug("Connecting to Redis at {}: Success", redisAddress); RedisChannelHandler<?, ?> connection = connectionBuilder.connection(); connection.registerCloseables(closeableResources, connection); channelReadyFuture.complete(connectFuture.channel()); return; } logger.debug("Connecting to Redis at {}, initialization: {}", redisAddress, throwable); connectionBuilder.commandHandler().initialState(); Throwable failure; if (throwable instanceof RedisConnectionException) { failure = throwable; } else if (throwable instanceof TimeoutException) { failure = new RedisConnectionException("Could not initialize channel within " + connectionBuilder.getTimeout() + " " + connectionBuilder.getTimeUnit(), throwable); } else { failure = throwable; } channelReadyFuture.completeExceptionally(failure); CompletableFuture<Boolean> response = new CompletableFuture<>(); response.completeExceptionally(failure); }); }); return new DefaultConnectionFuture<>(redisAddress, channelReadyFuture.thenApply(channel -> (T) connectionBuilder.connection())); }
From source file:com.leadtone.riders.server.RidersWebSocketServerHandler.java
License:Apache License
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != 200) { res.content().writeBytes(Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8)); setContentLength(res, res.content().readableBytes()); }/*from w w w. j a va2 s . c o m*/ // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().write(res); if (!isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.liferay.sync.engine.lan.server.file.LanFileServerHandler.java
License:Open Source License
protected void sendFile(final ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest, SyncFile syncFile) throws Exception { Path path = Paths.get(syncFile.getFilePathName()); if (Files.notExists(path)) { _syncTrafficShapingHandler.decrementConnectionsCount(); if (_logger.isTraceEnabled()) { Channel channel = channelHandlerContext.channel(); _logger.trace("Client {}: file not found {}", channel.remoteAddress(), path); }/* w ww . j a v a2s. c om*/ _sendError(channelHandlerContext, NOT_FOUND); return; } if (_logger.isDebugEnabled()) { Channel channel = channelHandlerContext.channel(); _logger.debug("Client {}: sending file {}", channel.remoteAddress(), path); } long modifiedTime = syncFile.getModifiedTime(); long previousModifiedTime = syncFile.getPreviousModifiedTime(); if (OSDetector.isApple()) { modifiedTime = modifiedTime / 1000 * 1000; previousModifiedTime = previousModifiedTime / 1000 * 1000; } FileTime currentFileTime = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS); long currentTime = currentFileTime.toMillis(); if ((currentTime != modifiedTime) && (currentTime != previousModifiedTime)) { _syncTrafficShapingHandler.decrementConnectionsCount(); Channel channel = channelHandlerContext.channel(); _logger.error( "Client {}: file modified {}, currentTime {}, modifiedTime " + "{}, previousModifiedTime {}", channel.remoteAddress(), path, currentTime, modifiedTime, previousModifiedTime); _sendError(channelHandlerContext, NOT_FOUND); return; } HttpResponse httpResponse = new DefaultHttpResponse(HTTP_1_1, OK); long size = Files.size(path); HttpUtil.setContentLength(httpResponse, size); HttpHeaders httpHeaders = httpResponse.headers(); MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap(); httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, mimetypesFileTypeMap.getContentType(syncFile.getName())); if (HttpUtil.isKeepAlive(fullHttpRequest)) { httpHeaders.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } channelHandlerContext.write(httpResponse); SyncChunkedFile syncChunkedFile = new SyncChunkedFile(path, size, 4 * 1024 * 1024, currentTime); ChannelFuture channelFuture = channelHandlerContext.writeAndFlush(new HttpChunkedInput(syncChunkedFile), channelHandlerContext.newProgressivePromise()); channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { _syncTrafficShapingHandler.decrementConnectionsCount(); if (channelFuture.isSuccess()) { return; } Throwable exception = channelFuture.cause(); Channel channel = channelHandlerContext.channel(); _logger.error("Client {}: {}", channel.remoteAddress(), exception.getMessage(), exception); channelHandlerContext.close(); } }); if (!HttpUtil.isKeepAlive(fullHttpRequest)) { channelFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.liferay.sync.engine.lan.server.file.LanFileServerHandler.java
License:Open Source License
private void _sendError(ChannelHandlerContext channelHandlerContext, HttpResponseStatus httpResponseStatus) { ChannelFuture channelFuture = channelHandlerContext .writeAndFlush(new DefaultFullHttpResponse(HTTP_1_1, httpResponseStatus)); channelFuture.addListener(ChannelFutureListener.CLOSE); }
From source file:com.linecorp.armeria.client.http.HttpRequestSubscriber.java
License:Apache License
private void write0(HttpObject o, boolean endOfStream, boolean flush) { final ChannelFuture future; if (o instanceof HttpData) { final HttpData data = (HttpData) o; future = encoder.writeData(ctx, id, streamId(), data, endOfStream); logBuilder.increaseContentLength(data.length()); } else if (o instanceof HttpHeaders) { future = encoder.writeHeaders(ctx, id, streamId(), (HttpHeaders) o, endOfStream); } else {// ww w . j a v a 2s. c om // Should never reach here because we did validation in onNext(). throw new Error(); } if (endOfStream) { logBuilder.end(); } future.addListener(this); if (flush) { ctx.flush(); } }
From source file:com.linecorp.armeria.client.http.HttpSessionChannelFactory.java
License:Apache License
void connect(SocketAddress remoteAddress, SessionProtocol protocol, Promise<Channel> sessionPromise) { final Bootstrap bootstrap = bootstrap(protocol); final ChannelFuture connectFuture = bootstrap.connect(remoteAddress); connectFuture.addListener((ChannelFuture future) -> { if (future.isSuccess()) { initSession(protocol, future, sessionPromise); } else {//ww w . j av a 2 s . c o m sessionPromise.setFailure(future.cause()); } }); }