List of usage examples for io.netty.channel ChannelFuture addListener
@Override ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);
From source file:fileShare.MyHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpMessage msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; System.out.println("==================================HttpRequest=================================="); System.out.println(msg.toString()); URI uri = new URI(request.getUri()); if (uri.getPath().startsWith("/getFile")) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < 1000; i++) { sb.append(i + ","); }// w w w . j a va 2s . com //HttpContent httpContent = blockingFile.take(); //ByteBuf wrappedBufferA = Unpooled.wrappedBuffer(byteses); ByteBuf wrappedBufferA = copiedBuffer(sb.toString(), CharsetUtil.UTF_8); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, wrappedBufferA); response.headers().set(CONTENT_TYPE, "application/octet-stream"); if (isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, wrappedBufferA.readableBytes()); // Write the initial line and the header. //ctx.write(response); ChannelFuture lastContentFuture = ctx.channel().writeAndFlush(response); // 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); } } if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx); return; } // responseContent.setLength(0); // responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); // // // if GET Method: should not try to create a HttpPostRequestDecoder // try { // decoder = new HttpPostRequestDecoder(factory, request); // } catch (ErrorDataDecoderException e1) { // e1.printStackTrace(); // responseContent.append(e1.getMessage()); // writeResponse(ctx.channel()); // ctx.channel().close(); // return; // } catch (IncompatibleDataDecoderException e1) { // // GET Method: should not try to create a HttpPostRequestDecoder // // So OK but stop here // responseContent.append(e1.getMessage()); // responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); // writeResponse(ctx.channel()); // return; // } // // readingChunks = HttpHeaders.isTransferEncodingChunked(request); // responseContent.append("Is Chunked: " + readingChunks + "\r\n"); // responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n"); // if (readingChunks) { // // Chunk version // responseContent.append("Chunks: "); // readingChunks = true; // } } // check if the decoder was constructed before // if not it handles the form get // if (decoder != null) { // if (msg instanceof HttpContent) { // // New chunk is received // HttpContent chunk = (HttpContent) msg; // try { // System.out.println("==================================HttpContent=================================="); // //? // System.out.println(new String(((DefaultHttpContent) chunk).content().array())); // blockingFile.put(chunk.copy()); // decoder.offer(chunk); // } catch (ErrorDataDecoderException e1) { // e1.printStackTrace(); // responseContent.append(e1.getMessage()); // writeResponse(ctx.channel()); // ctx.channel().close(); // return; // } // responseContent.append('o'); // // example of reading chunk by chunk (minimize memory usage due to // // Factory) // readHttpDataChunkByChunk(); // // example of reading only if at the end // if (chunk instanceof LastHttpContent) { // writeResponse(ctx.channel()); // readingChunks = false; // send = false; // reset(); // } // } // } }
From source file:fileShare.ShareHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; System.out.println("==================================HttpRequest=================================="); System.out.println(msg.toString()); URI uri = new URI(request.getUri()); if (uri.getPath().startsWith("/getFile")) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < 1000; i++) { sb.append(i + ","); }//from w ww . j a v a2s.co m //HttpContent httpContent = blockingFile.take(); //ByteBuf wrappedBufferA = Unpooled.wrappedBuffer(byteses); ByteBuf wrappedBufferA = copiedBuffer(sb.toString(), CharsetUtil.UTF_8); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, wrappedBufferA); response.headers().set(CONTENT_TYPE, "application/octet-stream"); if (isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, wrappedBufferA.readableBytes()); // Write the initial line and the header. //ctx.write(response); ChannelFuture lastContentFuture = ctx.channel().writeAndFlush(response); // 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); } } if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx); return; } responseContent.setLength(0); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); // if GET Method: should not try to create a HttpPostRequestDecoder try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } catch (IncompatibleDataDecoderException e1) { // GET Method: should not try to create a HttpPostRequestDecoder // So OK but stop here responseContent.append(e1.getMessage()); responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); writeResponse(ctx.channel()); return; } readingChunks = HttpHeaders.isTransferEncodingChunked(request); responseContent.append("Is Chunked: " + readingChunks + "\r\n"); responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n"); if (readingChunks) { // Chunk version responseContent.append("Chunks: "); readingChunks = true; } } // check if the decoder was constructed before // if not it handles the form get if (decoder != null) { if (msg instanceof HttpContent) { // New chunk is received HttpContent chunk = (HttpContent) msg; try { System.out.println( "==================================HttpContent=================================="); //? System.out.println(new String(((DefaultHttpContent) chunk).content().array())); blockingFile.put(chunk.copy()); decoder.offer(chunk); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } responseContent.append('o'); // example of reading chunk by chunk (minimize memory usage due to // Factory) readHttpDataChunkByChunk(); // example of reading only if at the end if (chunk instanceof LastHttpContent) { writeResponse(ctx.channel()); readingChunks = false; send = false; reset(); } } } }
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 . ja v a 2 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.letroll.ttorrentandroid.client.io.PeerClient.java
License:Apache License
@Nonnull public ChannelFuture connect(@Nonnull final PeerConnectionListener listener, @Nonnull final byte[] infoHash, @Nonnull final SocketAddress remoteAddress) { final ChannelFuture future; synchronized (lock) { // connect -> initAndRegister grabs this, so we can safely synchronize here. bootstrap.handler(new PeerClientHandshakeHandler(listener, infoHash, client.getLocalPeerId())); future = bootstrap.connect(remoteAddress); }//from w ww . java 2 s . c o m future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { try { LOG.trace("Succeeded: {}", future.get()); } catch (Exception e) { LOG.error("Connection to " + remoteAddress + " failed.", e); listener.handlePeerConnectionFailed(remoteAddress, e); } } }); return future; }
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:gribbit.http.request.decoder.HttpRequestDecoder.java
License:Open Source License
/** * Send non-OK response. Used by Netty pipeline for uncaught exceptions (e.g. connecion reset by peer, malformed * HTTP message, etc.), and also called manually for caught exceptions. *///from ww w .j a v a 2s .co m @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { try { if (e instanceof NotSslRecordException) { // Malformed SSL ctx.channel().flush(); ctx.channel().close(); } else if ("Connection reset by peer".equals(e.getMessage())) { // TODO: should connection be closed in this case? Does a response need to be sent? // Log.info(cause.getMessage()); } else { if (request != null) { ResponseException exception = e instanceof ResponseException ? (ResponseException) e : new InternalServerErrorException(e); // Override default error response page if there is a custom handler for this error type Response response = generateErrorResponse(exception); if (exception instanceof InternalServerErrorException) { // Log backtrace for Internal Server Errors Log.request(request, response, exception); } else { Log.request(request, response); } // Send response if (request != null && ctx.channel().isOpen()) { try { response.send(ctx); return; } catch (Exception e2) { } } } // If couldn't send response in normal way (either there is no request object generated yet, or // there was an exception calling response.send()), then send a plain text response as a fallback if (ctx.channel().isOpen()) { Log.exception("Unexpected un-sendable exception", e); FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR); res.content().writeBytes("Internal Server Error".getBytes("UTF-8")); HttpHeaders headers = res.headers(); headers.set(CONTENT_TYPE, "text/plain;charset=utf-8"); HttpUtil.setContentLength(res, res.content().readableBytes()); // Disable caching headers.add(CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // HTTP 1.1 headers.add(PRAGMA, "no-cache"); // HTTP 1.0 headers.add(EXPIRES, "0"); // Proxies ChannelFuture f = ctx.writeAndFlush(res); f.addListener(ChannelFutureListener.CLOSE); } } } catch (Exception e2) { Log.exception("Exception thrown while calling toplevel exception handler", e2); try { ctx.channel().flush(); ctx.channel().close(); } catch (Exception e3) { } } finally { freeResources(); } }
From source file:gwlpr.protocol.handshake.HandshakeHandler.java
License:Open Source License
@Override protected void decode(final ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { ByteBuf buf = in.order(ByteOrder.LITTLE_ENDIAN); switch (server) { case LoginServer: // client version: {/*from w w w . j a v a 2s . co m*/ // lengthcheck if (buf.readableBytes() < (P000_ClientVersion.getLength() + P000_ClientSeed.getLength())) { return; } // get the header P000_ClientVersion.Header header = P000_ClientVersion.serializeHeader(buf); // check the header if (header == null || !P000_ClientVersion.check(header)) { return; } // get the data P000_ClientVersion.Payload payload = P000_ClientVersion.serializePayload(buf); LOGGER.debug(String.format("Got the client version: %d", payload.ClientVersion)); } break; case GameServer: // verify client: { // lengthcheck if (buf.readableBytes() < (P000_VerifyClient.getLength() + P000_ClientSeed.getLength())) { return; } // get the header P000_VerifyClient.Header header = P000_VerifyClient.serializeHeader(buf); // check the header if (header == null || !P000_VerifyClient.check(header)) { return; } // get the data verifyClient = P000_VerifyClient.serializePayload(buf); LOGGER.debug(String.format("Got the verify client packet.")); } break; } // client seed: // get the header P000_ClientSeed.Header header = P000_ClientSeed.serializeHeader(buf); // check the header if (header == null || !P000_ClientSeed.check(header)) { return; } // get the data P000_ClientSeed.Payload payload = P000_ClientSeed.serializePayload(buf); LOGGER.debug("Got the client seed packet."); // INITIALIZE ENCRYPTION WITH THE CLIENT SEED PAYLOAD // generate the shared key byte[] sharedKeyBytes = EncryptionUtils.generateSharedKey(payload.ClientPublicKey); // start RC4 key generation byte[] randomBytes = new byte[20]; new SecureRandom().nextBytes(randomBytes); final byte[] rc4Key = EncryptionUtils.hash(randomBytes); // encrypt the RC4 key before sending it to the client byte[] xoredRandomBytes = EncryptionUtils.XOR(randomBytes, sharedKeyBytes); // INITIALIZATION OF ENCRYPTION DONE // we can set the RC4 decoder now... if encryption is enabled if (encryption == EncryptionOptions.Enable) { RC4Codec.Decoder decoder = new RC4Codec.Decoder(rc4Key); ctx.pipeline().addFirst(decoder); LOGGER.debug("RC4Decoder added to pipeline."); } // now send the server seed packet P001_ServerSeed serverSeed = new P001_ServerSeed(); serverSeed.setEncryptedRC4Key(xoredRandomBytes); buf = ctx.alloc().buffer(70).order(ByteOrder.LITTLE_ENDIAN); serverSeed.serializeInto(buf); ChannelFuture cf = ctx.writeAndFlush(buf); // also remove this handler ctx.pipeline().remove(this); // set the RC4 encoder only after the serverseed packet has been send! cf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (encryption == EncryptionOptions.Enable) { // add the rc4 codec if encryption is enabled RC4Codec.Encoder encoder = new RC4Codec.Encoder(rc4Key); ctx.pipeline().addFirst(encoder); LOGGER.debug("RC4Encoder added to pipeline."); } // tell the channel's context that handshake has been done ctx.channel().attr(GameAppContextKey.KEY).get() .trigger(new HandShakeDoneEvent(ctx.channel(), verifyClient)); } }); }
From source file:http.HttpFileServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);/* ww w .j a v a 2s. com*/ 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; } RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile(file, "r");// ?? } catch (FileNotFoundException fnfe) { sendError(ctx, NOT_FOUND); return; } long fileLength = randomAccessFile.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); setContentLength(response, fileLength); setContentTypeHeader(response, file); if (isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } ctx.write(response); ChannelFuture sendFileFuture; sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 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.out.println("Transfer complete."); } }); //0?NIO ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if (!isKeepAlive(request)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:io.advantageous.conekt.datagram.impl.DatagramSocketImpl.java
License:Open Source License
@SuppressWarnings("unchecked") final void addListener(ChannelFuture future, Handler<AsyncResult<DatagramSocket>> handler) { if (handler != null) { future.addListener(new DatagramChannelFutureListener<>(this, handler, context)); }//from w w w.j av a 2 s . c o m }
From source file:io.advantageous.conekt.datagram.impl.DatagramSocketImpl.java
License:Open Source License
@Override public void close(final Handler<AsyncResult<Void>> handler) { // make sure everything is flushed out on close endReadAndFlush();//from ww w. jav a 2s .co m metrics.close(); ChannelFuture future = channel.close(); if (handler != null) { future.addListener(new DatagramChannelFutureListener<>(null, handler, context)); } }