List of usage examples for io.netty.channel ChannelFuture isSuccess
boolean isSuccess();
From source file:com.cloudhopper.smpp.impl.UnboundSmppSession.java
License:Apache License
public void sendResponsePdu(PduResponse pdu) { try {/* w w w . jav a 2s. com*/ // encode the pdu into a buffer ByteBuf buffer = server.getTranscoder().encode(pdu); // always log the PDU logger.info("send PDU: {}", pdu); // write the pdu out & wait till its written ChannelFuture channelFuture = this.channel.writeAndFlush(buffer).await(); // check if the write was a success if (!channelFuture.isSuccess()) { // the write failed, make sure to throw an exception throw new SmppChannelException(channelFuture.cause().getMessage(), channelFuture.cause()); } } catch (Exception e) { logger.error("Fatal exception thrown while attempting to send response PDU: {}", e); } }
From source file:com.codebullets.external.party.simulator.connections.websocket.inbound.NettyWebSocketServerHandler.java
License:Apache License
private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) { if (!req.getDecoderResult().isSuccess()) { // Handle a bad request. sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); } else if (req.getMethod() != GET) { // Allow only GET methods. sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); } else if ("/".equals(req.getUri())) { ByteBuf content = WebSocketServerIndexPage.getContent(endpoint.toString()); FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content); res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); setContentLength(res, content.readableBytes()); sendHttpResponse(ctx, req, res); } else if ("/favicon.ico".equals(req.getUri())) { // Send the demo page and favicon.ico FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); sendHttpResponse(ctx, req, res); } else {/* w w w. j av a 2 s . c o m*/ // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(endpoint.toString(), null, false); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req).addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { connectedChannels.add(ctx.channel()); connectionMonitor.connectionEstablished(getContext(ctx)); } } }); } } }
From source file:com.codebullets.external.party.simulator.connections.websocket.outbound.OutboundWebSocketConnection.java
License:Apache License
/** * Open the connection to the target web socket endpoint. */// w ww . j av a 2s. c om public void openConnection() { LOG.info("Connecting to web socket server at {}", targetEndpoint); Bootstrap bootstrap = new Bootstrap(); bootstrap.group(eventGroup).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MILLIS) .handler(new WebSocketClientInitializer(monitor, connectionConfig, this)); bootstrap.connect(targetEndpoint.getHost(), targetEndpoint.getPort()) .addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { connectionEstablished(future.channel()); } else { LOG.warn("Connection to {} failed: {}", targetEndpoint, future.cause().getMessage()); eventGroup.schedule(new Runnable() { @Override public void run() { openConnection(); } }, CONNECT_RETRY_DELAY_MILLIS, TimeUnit.MILLISECONDS); } } }); }
From source file:com.codnos.dbgp.internal.handlers.DBGpRegularCommandHandler.java
License:Apache License
private void sendBackResponse(ChannelHandlerContext ctx, String responseString) { ChannelFuture channelFuture = ctx.writeAndFlush(responseString); try {/*w w w . j ava2s . c o m*/ ChannelFuture sync = channelFuture.sync(); LOGGER.fine("isdone sending = " + sync.isDone()); LOGGER.fine("was success= " + sync.isSuccess()); } catch (InterruptedException e) { LOGGER.fine("got interrupted"); e.printStackTrace(); } }
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. ja v a 2 s . c o m 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.couchbase.client.core.endpoint.AbstractEndpoint.java
License:Apache License
/** * Helper method to perform the actual connect and reconnect. * * @param observable the {@link Subject} which is eventually notified if the connect process * succeeded or failed. * @param bootstrapping true if connection attempt is for bootstrapping phase and therefore be less forgiving of * some errors (like socket connect timeout). */// w w w . j a v a 2 s. co m protected void doConnect(final Subject<LifecycleState, LifecycleState> observable, final boolean bootstrapping) { bootstrap.connect().addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (state() == LifecycleState.DISCONNECTING || state() == LifecycleState.DISCONNECTED) { LOGGER.debug(logIdent(channel, AbstractEndpoint.this) + "Endpoint connect completed, " + "but got instructed to disconnect in the meantime."); transitionState(LifecycleState.DISCONNECTED); channel = null; } else { if (future.isSuccess()) { channel = future.channel(); LOGGER.debug(logIdent(channel, AbstractEndpoint.this) + "Connected Endpoint."); transitionState(LifecycleState.CONNECTED); } else { if (future.cause() instanceof AuthenticationException) { LOGGER.warn(logIdent(channel, AbstractEndpoint.this) + "Authentication Failure."); transitionState(LifecycleState.DISCONNECTED); observable.onError(future.cause()); } else if (future.cause() instanceof SSLHandshakeException) { LOGGER.warn(logIdent(channel, AbstractEndpoint.this) + "SSL Handshake Failure during connect."); transitionState(LifecycleState.DISCONNECTED); observable.onError(future.cause()); } else if (future.cause() instanceof ClosedChannelException) { LOGGER.warn(logIdent(channel, AbstractEndpoint.this) + "Generic Failure."); transitionState(LifecycleState.DISCONNECTED); LOGGER.warn(future.cause().getMessage()); observable.onError(future.cause()); } else if (future.cause() instanceof ConnectTimeoutException) { LOGGER.warn(logIdent(channel, AbstractEndpoint.this) + "Socket connect took longer than specified timeout."); transitionState(LifecycleState.DISCONNECTED); observable.onError(future.cause()); } else if (isTransient) { transitionState(LifecycleState.DISCONNECTED); LOGGER.warn(future.cause().getMessage()); observable.onError(future.cause()); } if (!disconnected && !bootstrapping && !isTransient) { long delay = env.reconnectDelay().calculate(reconnectAttempt++); TimeUnit delayUnit = env.reconnectDelay().unit(); LOGGER.warn(logIdent(channel, AbstractEndpoint.this) + "Could not connect to endpoint, retrying with delay " + delay + " " + delayUnit + ": ", future.cause()); if (responseBuffer != null) { responseBuffer.publishEvent(ResponseHandler.RESPONSE_TRANSLATOR, SignalConfigReload.INSTANCE, null); } transitionState(LifecycleState.CONNECTING); future.channel().eventLoop().schedule(new Runnable() { @Override public void run() { // Make sure to avoid a race condition where the reconnect could override // the disconnect phase. If this happens, explicitly break the retry loop // and re-run the disconnect phase to make sure all is properly freed. if (!disconnected) { doConnect(observable, bootstrapping); } else { LOGGER.debug( "{}Explicitly breaking retry loop because already disconnected.", logIdent(channel, AbstractEndpoint.this)); disconnect(); } } }, delay, delayUnit); } else { LOGGER.debug("{}Not retrying because already disconnected.", logIdent(channel, AbstractEndpoint.this)); } } } observable.onNext(state()); observable.onCompleted(); } }); }
From source file:com.couchbase.client.core.endpoint.AbstractEndpoint.java
License:Apache License
@Override public Observable<LifecycleState> disconnect() { disconnected = true;//from w ww. ja v a2s .com if (state() == LifecycleState.DISCONNECTED || state() == LifecycleState.DISCONNECTING) { return Observable.just(state()); } if (state() == LifecycleState.CONNECTING) { transitionState(LifecycleState.DISCONNECTED); return Observable.just(state()); } transitionState(LifecycleState.DISCONNECTING); final AsyncSubject<LifecycleState> observable = AsyncSubject.create(); channel.disconnect().addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { LOGGER.debug(logIdent(channel, AbstractEndpoint.this) + "Disconnected Endpoint."); } else { LOGGER.warn( logIdent(channel, AbstractEndpoint.this) + "Received an error " + "during disconnect.", future.cause()); } transitionState(LifecycleState.DISCONNECTED); observable.onNext(state()); observable.onCompleted(); channel = null; } }); return observable; }
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./*from www . j ava 2 s.c om*/ * @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 w ww .j a v a 2 s .c om * @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.// w ww .j a v a 2s .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."); } }