Example usage for io.netty.util.concurrent GenericFutureListener GenericFutureListener

List of usage examples for io.netty.util.concurrent GenericFutureListener GenericFutureListener

Introduction

In this page you can find the example usage for io.netty.util.concurrent GenericFutureListener GenericFutureListener.

Prototype

GenericFutureListener

Source Link

Usage

From source file:com.couchbase.client.core.endpoint.binary.BinaryAuthHandler.java

License:Open Source License

@Override
public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
        ChannelPromise promise) throws Exception {
    originalPromise = promise;//from   www  .j a  v  a2  s.co  m
    ChannelPromise downPromise = ctx.newPromise();
    downPromise.addListener(new GenericFutureListener<Future<Void>>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            if (!future.isSuccess() && !originalPromise.isDone()) {
                originalPromise.setFailure(future.cause());
            }
        }
    });
    ctx.connect(remoteAddress, localAddress, downPromise);
}

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  ww  w  .j  av  a  2  s  .  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  w  w  w.  j a  va  2s  .co  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 w ww.java2  s.c  o m*/
 * @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.core.env.resources.IoPoolShutdownHook.java

License:Apache License

public Observable<Boolean> shutdown() {
    return Observable.create(new Observable.OnSubscribe<Boolean>() {
        @Override/*from  ww  w  . j  av  a2 s  . c  om*/
        public void call(final Subscriber<? super Boolean> subscriber) {
            ioPool.shutdownGracefully(0, 10, TimeUnit.MILLISECONDS).addListener(new GenericFutureListener() {
                @Override
                public void operationComplete(final Future future) throws Exception {
                    if (!subscriber.isUnsubscribed()) {
                        try {
                            if (future.isSuccess()) {
                                subscriber.onNext(true);
                                shutdown = true;
                                subscriber.onCompleted();
                            } else {
                                subscriber.onError(future.cause());
                            }
                        } catch (Exception ex) {
                            subscriber.onError(ex);
                        }
                    }
                }
            });
        }
    });
}

From source file:com.couchbase.client.core.io.endpoint.AbstractEndpoint.java

License:Open Source License

/**
 * Adds a listener to retry if the underlying channel gets closed.
 *//*  w  ww  . ja v  a 2 s .  co  m*/
private void addRetryListener() {
    if (state == EndpointState.CONNECTED) {
        channel.closeFuture().addListener(new GenericFutureListener<Future<Void>>() {
            @Override
            public void operationComplete(Future<Void> future) throws Exception {
                if (shouldRetry) {
                    connect();
                }
            }
        });
    }
}

From source file:com.dinstone.jrpc.transport.netty4.NettyConnection.java

License:Apache License

@Override
public ResultFuture call(Call call) {
    final int id = ID_GENERATOR.incrementAndGet();
    Map<Integer, ResultFuture> futureMap = SessionUtil.getResultFutureMap(ioSession);
    final ResultFuture resultFuture = new ResultFuture();
    futureMap.put(id, resultFuture);/*from   w  w  w  .  jav  a 2 s  .  c  o m*/

    ChannelFuture wf = ioSession.writeAndFlush(new Request(id, serializeType, call));
    wf.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                resultFuture.setResult(new Result(500, "can't write request"));
            }
        }

    });

    return resultFuture;
}

From source file:com.eucalyptus.util.async.AsyncRequestHandler.java

License:Open Source License

/**
 *
 *//*from   w w  w  .  j  av  a 2s .  c o  m*/
@Override
public boolean fire(final ServiceConfiguration config, final Q request) {
    if (!this.request.compareAndSet(null, request)) {
        LOG.warn("Duplicate write attempt for request: " + this.request.get().getClass().getSimpleName());
        return false;
    } else {
        try {
            final InetSocketAddress serviceSocketAddress = config.getSocketAddress();
            final Bootstrap clientBootstrap = config.getComponentId().getClientBootstrap();
            final ChannelInitializer<?> initializer = config.getComponentId().getClientChannelInitializer();
            final int poolSizeLimit = initializer instanceof AsyncRequestPoolable
                    ? ((AsyncRequestPoolable) initializer).fixedSize()
                    : -1;
            final IoMessage<FullHttpRequest> ioMessage = IoMessage.httpRequest(ServiceUris.internal(config),
                    this.request.get());
            final ChannelPoolKey poolKey = new ChannelPoolKey(clientBootstrap, initializer,
                    serviceSocketAddress, poolSizeLimit);
            final long before = System.currentTimeMillis();
            this.channelPool = POOL_MAP.get(poolKey);
            this.acquireFuture = channelPool.acquire();
            this.acquireFuture.addListener(new GenericFutureListener<Future<Channel>>() {
                @Override
                public void operationComplete(final Future<Channel> future) throws Exception {
                    try {
                        if (future.isSuccess()) {
                            final Channel channel = future.get();
                            logAcquired(channel, before);
                            channel.pipeline().addLast("request-handler", AsyncRequestHandler.this);

                            if (!initializer.getClass().getSimpleName().startsWith("GatherLog")) {
                                Topology.populateServices(config, AsyncRequestHandler.this.request.get());
                            }

                            logMessage(ioMessage);

                            channel.writeAndFlush(ioMessage).addListener(new ChannelFutureListener() {
                                @Override
                                public void operationComplete(final ChannelFuture future) throws Exception {
                                    AsyncRequestHandler.this.writeComplete.set(true);

                                    Logs.extreme()
                                            .debug(EventRecord.here(request.getClass(),
                                                    EventClass.SYSTEM_REQUEST, EventType.CHANNEL_WRITE,
                                                    request.getClass().getSimpleName(),
                                                    request.getCorrelationId(), serviceSocketAddress.toString(),
                                                    "" + future.channel().localAddress(),
                                                    "" + future.channel().remoteAddress()));
                                }
                            });
                        } else {
                            AsyncRequestHandler.this.teardown(future.cause());
                        }
                    } catch (final Exception ex) {
                        LOG.error(ex, ex);
                        AsyncRequestHandler.this.teardown(ex);
                    }
                }
            });
            return true;
        } catch (final Exception t) {
            LOG.error(t, t);
            this.teardown(t);
            return false;
        }
    }
}

From source file:com.farsunset.cim.sdk.android.CIMConnectorManager.java

License:Apache License

public void connect(final String host, final int port) {

    if (!isNetworkConnected(context)) {

        Intent intent = new Intent();
        intent.setAction(CIMConstant.IntentAction.ACTION_CONNECTION_FAILED);
        intent.putExtra(Exception.class.getName(), NetworkDisabledException.class.getSimpleName());
        context.sendBroadcast(intent);//from  ww  w . ja  va 2 s  .co  m

        return;
    }

    if (isConnected() || !semaphore.tryAcquire()) {
        return;
    }

    executor.execute(new Runnable() {
        @Override
        public void run() {

            final InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
            bootstrap.connect(remoteAddress).addListener(new GenericFutureListener<ChannelFuture>() {

                @Override
                public void operationComplete(ChannelFuture future) {
                    semaphore.release();
                    future.removeListener(this);
                    if (!future.isSuccess() && future.cause() != null) {
                        handleConnectFailure(future.cause(), remoteAddress);
                    }

                    if (future.isSuccess()) {
                        channel = future.channel();
                    }

                }
            });
        }
    });

}

From source file:com.farsunset.cim.sdk.client.CIMConnectorManager.java

License:Apache License

public void connect(final String host, final int port) {

    if (isConnected() || !semaphore.tryAcquire()) {
        return;//from w  w w .j a  va2 s  .c  o  m
    }

    executor.execute(new Runnable() {
        @Override
        public void run() {

            logger.info("****************CIM?  " + host + ":" + port + "......");
            final InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
            bootstrap.connect(remoteAddress).addListener(new GenericFutureListener<ChannelFuture>() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    semaphore.release();
                    future.removeListener(this);
                    if (!future.isSuccess() && future.cause() != null) {
                        handleConnectFailure(future.cause(), remoteAddress);
                    }

                    if (future.isSuccess()) {
                        channel = future.channel();
                    }
                }
            });
        }
    });

}