List of usage examples for io.netty.channel ChannelFuture addListener
@Override ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);
From source file:divconq.web.Response.java
License:Open Source License
public void write(Channel ch) { if ((this.status != HttpResponseStatus.OK) && (this.body.getLength() == 0)) this.body.write(this.status.toString()); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, this.status); int clen = 0; this.body.setPosition(0); try {//from w w w.j a v a 2 s . c o m clen = response.content().writeBytes(new InputWrapper(this.body), this.body.getLength()); } catch (IOException e) { } response.headers().set(Names.CONTENT_TYPE, "text/plain; charset=UTF-8"); if (this.keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. response.headers().set(Names.CONTENT_LENGTH, clen); // Add keep alive header as per: // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection response.headers().set(Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } // Encode the cookies for (Cookie c : this.cookies.values()) response.headers().add(Names.SET_COOKIE, ServerCookieEncoder.encode(c)); for (Entry<CharSequence, String> h : this.headers.entrySet()) response.headers().set(h.getKey(), h.getValue()); Hub.instance.getSecurityPolicy().hardenHttpResponse(response); // Write the response. ChannelFuture future = ch.writeAndFlush(response); // Close the non-keep-alive connection after the write operation is done. if (!this.keepAlive) future.addListener(ChannelFutureListener.CLOSE); /* we do not need to sync - HTTP is one request, one response. we would not pile messages on this channel * * furthermore, when doing an upload stream we can actually get locked up here because the "write" from our stream * is locked on the write process of the data bus and the response to the session is locked on the write of the response * here - but all the HTTP threads are busy with their respective uploads. If they all use the same data bus session * then all HTTP threads can get blocked trying to stream upload if even one of those has called an "OK" to upload and * is stuck here. so be sure not to use sync with HTTP responses. this won't be a problem under normal use. * try { future.sync(); } catch (InterruptedException x) { // TODO should we close channel? } */ }
From source file:divconq.web.Response.java
License:Open Source License
public void writeEnd(Channel ch) { // Write the response. ChannelFuture future = ch.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // Close the non-keep-alive connection after the write operation is done. if (!this.keepAlive) future.addListener(ChannelFutureListener.CLOSE); /* we do not need to sync - HTTP is one request, one response. we would not pile messages on this channel * /* www.j a va 2s . c o m*/ * furthermore, when doing an upload stream we can actually get locked up here because the "write" from our stream * is locked on the write process of the data bus and the response to the session is locked on the write of the response * here - but all the HTTP threads are busy with their respective uploads. If they all use the same data bus session * then all HTTP threads can get blocked trying to stream upload if even one of those has called an "OK" to upload and * is stuck here. so be sure not to use sync with HTTP responses. this won't be a problem under normal use. * try { future.sync(); } catch (InterruptedException x) { // TODO should we close channel? } */ }
From source file:divconq.web.Response.java
License:Open Source License
public void writeChunked(Channel ch) { // Build the response object. HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, this.status); response.headers().set(Names.CONTENT_TYPE, "text/plain; charset=UTF-8"); if (this.keepAlive) { // Add keep alive header as per: // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection response.headers().set(Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); }//from w ww. j a v a 2 s . c o m // TODO add a customer header telling how many messages are in the session adaptor's queue - if > 0 // Encode the cookies for (Cookie c : this.cookies.values()) response.headers().add(Names.SET_COOKIE, ServerCookieEncoder.encode(c)); for (Entry<CharSequence, String> h : this.headers.entrySet()) response.headers().set(h.getKey(), h.getValue()); response.headers().set(Names.TRANSFER_ENCODING, Values.CHUNKED); // Write the response. ChannelFuture future = ch.writeAndFlush(response); // Close the non-keep-alive connection after the write operation is done. if (!this.keepAlive) future.addListener(ChannelFutureListener.CLOSE); /* we do not need to sync - HTTP is one request, one response. we would not pile messages on this channel try { future.sync(); } catch (InterruptedException x) { // TODO should we close channel? } */ }
From source file:dorkbox.network.connection.registration.remote.RegistrationRemoteHandler.java
License:Apache License
private void cleanupPipeline0(final int idleTimeout, final ChannelHandler connection, final Channel channel, final ChannelPromise channelPromise, final boolean isTcp) { final ChannelPipeline pipeline = channel.pipeline(); // have to explicitly remove handlers based on the input type. Cannot use this.getClass().... boolean isClient = registrationWrapper.isClient(); if (isClient) { if (isTcp) { pipeline.remove(RegistrationRemoteHandlerClientTCP.class); } else {// ww w . j a va 2s .co m pipeline.remove(RegistrationRemoteHandlerClientUDP.class); } } else { if (isTcp) { pipeline.remove(RegistrationRemoteHandlerServerTCP.class); } else { pipeline.remove(RegistrationRemoteHandlerServerUDP.class); } } pipeline.remove(ConnectionRegistrationImpl.class); if (idleTimeout > 0) { pipeline.replace(IDLE_HANDLER, IDLE_HANDLER_FULL, new IdleStateHandler(0, 0, idleTimeout, TimeUnit.MILLISECONDS)); } else { pipeline.remove(IDLE_HANDLER); } pipeline.addLast(CONNECTION_HANDLER, connection); // we also DEREGISTER from the HANDSHAKE event-loop and run on the worker event-loop! ChannelFuture future = channel.deregister(); future.addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(final Future<? super Void> f) throws Exception { if (f.isSuccess()) { // TCP and UDP register on DIFFERENT event loops. The channel promise ONLY runs on 1 of them... if (channelPromise.channel() == channel) { workerEventLoop.register(channelPromise); } else { workerEventLoop.register(channel); } } } }); }
From source file:dpfmanager.shell.modules.server.get.HttpGetHandler.java
License:Open Source License
/** * Main functions//from ww w. j a v a2 s . c o m */ private void tractReadGet(ChannelHandlerContext ctx, String zipPath) { // Parse params String path = DPFManagerProperties.getReportsDir() + zipPath; if (!zipPath.endsWith(".zip")) { String hash = zipPath.substring(1, zipPath.length()); StatusMessage sm = (StatusMessage) context.sendAndWaitResponse(BasicConfig.MODULE_DATABASE, new PostMessage(PostMessage.Type.ASK, hash)); path = sm.getFolder().substring(0, sm.getFolder().length() - 1) + ".zip"; } // Send the zip report File file = new File(path); if (file.exists()) { try { RandomAccessFile raf = new RandomAccessFile(file, "r"); long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpUtil.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); response.headers().remove(HttpHeaderNames.CONNECTION); // 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()); // Write the end marker. lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { lastContentFuture = ctx.writeAndFlush( new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); } // Delete the zip after download? lastContentFuture.addListener(new GenericFutureListener() { @Override public void operationComplete(Future future) throws Exception { // file.delete(); } }); // Decide whether to close the connection or not. if (!HttpUtil.isKeepAlive(request)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } } catch (Exception ignore) { sendError(ctx, NOT_FOUND); } } else { // No exists sendError(ctx, NOT_FOUND); } }
From source file:dpfmanager.shell.modules.server.post.HttpPostHandler.java
License:Open Source License
/** * Util functions//from ww w . j a v a 2 s . com */ private void writeResponse(Channel channel) { // Convert the response content to a ChannelBuffer. ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8); responseContent.setLength(0); // Decide whether to close the connection or not. boolean close = request.headers().contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE, true) || request.protocolVersion().equals(HttpVersion.HTTP_1_0) && !request.headers() .contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE, true); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); if (!close) { response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes()); } // Extra headers response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); // Write the response. ChannelFuture future = channel.writeAndFlush(response); // Close the connection after the write operation is done if necessary. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }
From source file:eastwind.webpush.WebPushHandler.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.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf);// w ww .ja v a2 s .c o m buf.release(); } // Send the response and close the connection if necessary. res.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/json; charset=UTF-8"); res.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); HttpUtil.setContentLength(res, res.content().readableBytes()); ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:etcd.client.HttpClient.java
License:Open Source License
private void send(Iterator<ServerList.Server> serverIterator, FullHttpRequest request, Consumer<Response> completionHandler) { final ServerList.Server server = serverIterator.next(); final URI address = server.getAddress(); final ChannelFuture connectFuture = bootstrap.connect(address.getHost(), address.getPort()); final FullHttpRequest requestCopy = request.copy(); requestCopy.retain();/* www . j a v a2 s. com*/ final Channel channel = connectFuture.channel(); channel.attr(REQUEST_KEY).set(requestCopy); channel.attr(ATTRIBUTE_KEY).set(completionHandler); connectFuture.addListener((future) -> { if (future.isSuccess()) { channel.writeAndFlush(request); } else { server.connectionFailed(); if (autoReconnect && serverIterator.hasNext()) { send(serverIterator, request, completionHandler); } else { invokeCompletionHandler(completionHandler, new Response(null, new EtcdException(future.cause()))); } } }); }
From source file:eu.heronnet.module.kad.net.ClientImpl.java
License:Open Source License
private void sendAllNodes(List<Node> nodes, Messages.Request.Builder requestBuilder) { try {//from www. j av a2 s . c o m Node self = selfNodeProvider.getSelf(); Builder selfNodeBuilder = Messages.NetworkNode.newBuilder(); self.getAddresses().forEach(address -> { Address.Builder addressBuilder = Address.newBuilder().setPort(self.getPort()) .setIpAddress(ByteString.copyFrom(address)); selfNodeBuilder.addAddresses(addressBuilder); }); selfNodeBuilder.setId(ByteString.copyFrom(self.getId())); requestBuilder.setOrigin(selfNodeBuilder); for (Node node : nodes) { List<byte[]> addresses = node.getAddresses(); addresses.forEach(address -> { try { ByteString messageId = requestBuilder.getMessageId(); tcpBoostrap.handler(new ResponseHandler(messageId.toByteArray())); ChannelFuture connectFuture = tcpBoostrap .connect(InetAddress.getByAddress(address), node.getPort()).sync(); connectFuture.addListener(future -> { Messages.Request request = requestBuilder.build(); connectFuture.channel().writeAndFlush(request); }); } catch (InterruptedException e) { logger.error(e.getMessage()); } catch (RuntimeException e) { logger.error("Unresolved address {}", address); } catch (UnknownHostException e) { logger.error("Unkown host={}", e); } }); } } catch (SocketException e) { logger.error("Socket exception while building list of self nodes={}", e.getMessage()); } }
From source file:fileShare.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);// ww w. j a v a2s . co 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 fnfe) { 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, Values.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture sendFileFuture; if (useSendFile) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); } else { sendFileFuture = ctx.write(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 System.err.println("Transfer progress: " + progress); } else { System.err.println("Transfer progress: " + progress + " / " + total); } } @Override public void operationComplete(ChannelProgressiveFuture future) throws Exception { System.err.println("Transfer complete."); } }); // 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); } }