List of usage examples for io.netty.channel ChannelFuture addListener
@Override ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);
From source file:com.corundumstudio.socketio.transport.WebSocketTransport.java
License:Apache License
private void handshake(ChannelHandlerContext ctx, final UUID sessionId, String path, FullHttpRequest req) { final Channel channel = ctx.channel(); WebSocketServerHandshakerFactory factory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, false, configuration.getMaxFramePayloadLength()); WebSocketServerHandshaker handshaker = factory.newHandshaker(req); if (handshaker != null) { ChannelFuture f = handshaker.handshake(channel, req); f.addListener(new ChannelFutureListener() { @Override/*from w w w. j a v a 2 s .c om*/ public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { log.error("Can't handshake " + sessionId, future.cause()); return; } channel.pipeline().addBefore(SocketIOChannelInitializer.WEB_SOCKET_TRANSPORT, SocketIOChannelInitializer.WEB_SOCKET_AGGREGATOR, new WebSocketFrameAggregator(configuration.getMaxFramePayloadLength())); connectClient(channel, sessionId); } }); } else { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } }
From source file:com.corundumstudio.socketio.transport.XHRPollingTransport.java
License:Apache License
private void scheduleDisconnect(Channel channel, final UUID sessionId) { final SchedulerKey key = new SchedulerKey(Type.CLOSE_TIMEOUT, sessionId); scheduler.cancel(key);/*from w w w. j av a2 s .c o m*/ ChannelFuture future = channel.closeFuture(); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { scheduler.scheduleCallback(key, new Runnable() { @Override public void run() { XHRPollingClient client = sessionId2Client.get(sessionId); if (client != null) { client.onChannelDisconnect(); log.debug("Client: {} disconnected due to connection timeout", sessionId); } } }, configuration.getCloseTimeout(), TimeUnit.SECONDS); } }); }
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 a va 2s . c o 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())); } } }
From source file:com.couchbase.client.core.endpoint.kv.KeyValueAuthHandler.java
License:Apache License
/** * Handles an incoming SASL list mechanisms response and dispatches the next SASL AUTH step. * * @param ctx the handler context.//from www .ja v a2s . c o m * @param msg the incoming message to investigate. * @throws Exception if something goes wrong during negotiation. */ private void handleListMechsResponse(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception { String remote = ctx.channel().remoteAddress().toString(); String[] supportedMechanisms = msg.content().toString(CharsetUtil.UTF_8).split(" "); if (supportedMechanisms.length == 0) { throw new AuthenticationException("Received empty SASL mechanisms list from server: " + remote); } saslClient = Sasl.createSaslClient(supportedMechanisms, null, "couchbase", remote, null, this); selectedMechanism = saslClient.getMechanismName(); int mechanismLength = selectedMechanism.length(); byte[] bytePayload = saslClient.hasInitialResponse() ? saslClient.evaluateChallenge(new byte[] {}) : null; ByteBuf payload = bytePayload != null ? ctx.alloc().buffer().writeBytes(bytePayload) : Unpooled.EMPTY_BUFFER; FullBinaryMemcacheRequest initialRequest = new DefaultFullBinaryMemcacheRequest( selectedMechanism.getBytes(CharsetUtil.UTF_8), Unpooled.EMPTY_BUFFER, payload); initialRequest.setOpcode(SASL_AUTH_OPCODE).setKeyLength((short) mechanismLength) .setTotalBodyLength(mechanismLength + payload.readableBytes()); ChannelFuture future = ctx.writeAndFlush(initialRequest); future.addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(Future<Void> future) throws Exception { if (!future.isSuccess()) { LOGGER.warn("Error during SASL Auth negotiation phase.", future); } } }); }
From source file:com.couchbase.client.core.endpoint.kv.KeyValueAuthHandler.java
License:Apache License
/** * Handles an incoming SASL AUTH response and - if needed - dispatches the SASL STEPs. * * @param ctx the handler context./*from ww w . j av a2 s .c om*/ * @param msg the incoming message to investigate. * @throws Exception if something goes wrong during negotiation. */ private void handleAuthResponse(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception { if (saslClient.isComplete()) { checkIsAuthed(msg); return; } byte[] response = new byte[msg.content().readableBytes()]; msg.content().readBytes(response); byte[] evaluatedBytes = saslClient.evaluateChallenge(response); if (evaluatedBytes != null) { ByteBuf content; // This is needed against older server versions where the protocol does not // align on cram and plain, the else block is used for all the newer cram-sha* // mechanisms. // // Note that most likely this is only executed in the CRAM-MD5 case only, but // just to play it safe keep it for both mechanisms. if (selectedMechanism.equals("CRAM-MD5") || selectedMechanism.equals("PLAIN")) { String[] evaluated = new String(evaluatedBytes).split(" "); content = Unpooled.copiedBuffer(username + "\0" + evaluated[1], CharsetUtil.UTF_8); } else { content = Unpooled.wrappedBuffer(evaluatedBytes); } FullBinaryMemcacheRequest stepRequest = new DefaultFullBinaryMemcacheRequest( selectedMechanism.getBytes(CharsetUtil.UTF_8), Unpooled.EMPTY_BUFFER, content); stepRequest.setOpcode(SASL_STEP_OPCODE).setKeyLength((short) selectedMechanism.length()) .setTotalBodyLength(content.readableBytes() + selectedMechanism.length()); ChannelFuture future = ctx.writeAndFlush(stepRequest); future.addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(Future<Void> future) throws Exception { if (!future.isSuccess()) { LOGGER.warn("Error during SASL Auth negotiation phase.", future); } } }); } else { throw new AuthenticationException("SASL Challenge evaluation returned null."); } }
From source file:com.couchbase.client.QueryConnection.java
License:Open Source License
public HttpFuture<QueryResult> execute(String query) { Channel chan = connectedChannels.get(0); // always use first channel for now CountDownLatch futureLatch = new CountDownLatch(1); HttpFuture<QueryResult> future = new HttpFuture<QueryResult>(futureLatch, 10000, connectionFactory.getListenerExecutorService()); ChannelFuture channelFuture = chan.writeAndFlush(new QueryEvent<QueryResult>(query, future, futureLatch)); final CountDownLatch latch = new CountDownLatch(1); channelFuture.addListener(new ChannelFutureListener() { @Override//from w w w.j a va 2 s.c o m public void operationComplete(ChannelFuture channelFuture) throws Exception { latch.countDown(); } }); try { latch.await(); } catch (InterruptedException e) { getLogger().warn("Got interrupted while writing Query, cancelling operation."); future.cancel(true); } return future; }
From source file:com.creamsugardonut.HttpStaticFileServerHandler2.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);//from w w w.j a v a2 s . c o m 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.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); setContentTypeHeader(response, file); if (HttpHeaders.isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; // Tell clients that Partial Requests are available. response.headers().add(HttpHeaders.Names.ACCEPT_RANGES, HttpHeaders.Values.BYTES); String rangeHeader = request.headers().get(HttpHeaders.Names.RANGE); System.out.println(HttpHeaders.Names.RANGE + " = " + rangeHeader); if (rangeHeader != null && rangeHeader.length() > 0) { // Partial Request PartialRequestInfo partialRequestInfo = getPartialRequestInfo(rangeHeader, fileLength); // Set Response Header response.headers().add(HttpHeaders.Names.CONTENT_RANGE, HttpHeaders.Values.BYTES + " " + partialRequestInfo.startOffset + "-" + partialRequestInfo.endOffset + "/" + fileLength); System.out.println(HttpHeaders.Names.CONTENT_RANGE + " : " + response.headers().get(HttpHeaders.Names.CONTENT_RANGE)); HttpHeaders.setContentLength(response, partialRequestInfo.getChunkSize()); System.out.println(HttpHeaders.Names.CONTENT_LENGTH + " : " + partialRequestInfo.getChunkSize()); response.setStatus(HttpResponseStatus.PARTIAL_CONTENT); // Write Response ctx.write(response); sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), partialRequestInfo.getStartOffset(), partialRequestInfo.getChunkSize()), ctx.newProgressivePromise()); } else { // Set Response Header HttpHeaders.setContentLength(response, fileLength); // Write Response ctx.write(response); sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); } lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); 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 (!HttpHeaders.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.cssweb.network.NettyClientHandler.java
License:Apache License
public void sendRequest(byte msgType, byte[] body) { MsgHeader msgHeader = new MsgHeader(); msgHeader.encodeMsgHeader(body.length, msgType, (byte) 0, (byte) 0, (byte) 0, (byte) 0); CustomMessage req = new CustomMessage(); req.setMsgContent(body);// w ww. j a v a 2 s.c o m req.setMsgHeader(msgHeader); ChannelFuture future = null; future = ctx.write(req); future.addListener(numberSender); ctx.flush(); }
From source file:com.cssweb.payment.posp.client.NettyClientHandler.java
License:Apache License
/** * ???/*from w w w . ja v a 2 s . c om*/ * @param customMessage */ public void sendResponse(CustomMessage customMessage) { ChannelFuture future = null; future = ctx.write(customMessage); future.addListener(numberSender); ctx.flush(); }
From source file:com.cssweb.payment.posp.client.NettyClientHandler.java
License:Apache License
public void sendRequest(CustomMessage customMessage) { ChannelFuture future = null; future = ctx.write(customMessage);//from w w w .j av a 2s . c o m future.addListener(numberSender); ctx.flush(); }