Java org.jboss.netty.channel.ChannelFuture 代码实例

・10 分钟阅读

以下是展示如何使用org.jboss.netty.channel.ChannelFuture的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


@Test
public void shouldPropagateDownstreamCloseOnBarrierFutureSuccess() throws Exception {
    context.checking(new Expectations() {
        {
            oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class)));
            oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(channelState(OPEN, TRUE)));
            oneOf(downstream).handleDownstream(with(any(ChannelHandlerContext.class)), with(channelState(OPEN, FALSE)));
            oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(channelState(OPEN, FALSE)));
        }
    });
    Channel channel = channelFactory.newChannel(pipeline);
    close(channel);
    ChannelFuture barrierFuture = barrier.getFuture();
    barrierFuture.setSuccess();
    ChannelFuture handlerFuture = handler.getHandlerFuture();
    assertTrue(handlerFuture.isSuccess());
    assertFalse(handler.hasQueuedChannelEvents());
    context.assertIsSatisfied();
}
 

实例 2


@Test
public void shouldNotPropagateDownstreamConnectOnPipelineFutureFailure() throws Exception {
    context.checking(new Expectations() {
        {
            oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class)));
            oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(channelState(OPEN, TRUE)));
        }
    });
    channelFactory.newChannel(pipeline);
    ChannelFuture executionFuture = execution.getHandlerFuture();
    executionFuture.setFailure(new ChannelException("pipeline already failed"));
    ChannelFuture handlerFuture = handler.getHandlerFuture();
    assertFalse(handlerFuture.isDone());
    context.assertIsSatisfied();
}
 

实例 3


@Test
public void shouldDecodePrepareMessage() throws Exception {
    String path = "org/kaazing/robot/driver/control/handler/testScript.rpt";
    final PrepareMessage expected = new PrepareMessage();
    expected.setNames(singletonList(path));
    context.checking(new Expectations() {
        {
            oneOf(handler).handleUpstream(with(any(ChannelHandlerContext.class)), with(message(expected)));
        }
    });
    // @formatter:off
    ChannelBuffer buffer = copiedBuffer("PREPAREn" +
                                        "name:" + path
                                        + "n" + "n", UTF_8);
    // @formatter:on
    ChannelFuture future = client.connect(new LocalAddress("test")).sync();
    Channel channel = future.getChannel();
    channel.write(buffer).sync();
    channel.close().sync();
    assertEquals(0, buffer.readableBytes());
    context.assertIsSatisfied();
}
 

实例 4


/**
 * Creates a new channel which is bound to the specified local address.
 *
 * @return a new bound channel which accepts incoming connections
 *
 * @throws ChannelException
 *         if failed to create a new channel and
 *                      bind it to the local address
 */
public Channel bind(final SocketAddress localAddress) {
    if (localAddress == null) {
        throw new NullPointerException("localAddress");
    }
    ChannelPipeline pipeline;
    try {
        pipeline = getPipelineFactory().getPipeline();
    } catch (Exception e) {
        throw new ChannelPipelineException("Failed to initialize a pipeline.", e);
    }
    Channel ch = getFactory().newChannel(pipeline);
    // Apply options.
    boolean success = false;
    try {
        ch.getConfig().setOptions(getOptions());
        success = true;
    } finally {
        if (!success) {
            ch.close();
        }
    }
    // Bind
    ChannelFuture future = ch.bind(localAddress);
    // Wait for the future.
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        future.getChannel().close().awaitUninterruptibly();
        throw new ChannelException("Failed to bind to: " + localAddress, future.getCause());
    }
    return ch;
}
 

实例 5


private void handleSession(ChannelHandlerContext ctx, Session session, MixinPipeline pipeline)
{
        _hasSession = true;
        session.setClosed(false);
        // if we have a session timeout set, cancel it.
        Timeout timeOut = session.removeTimeout();
        if (timeOut != null)
                timeOut.cancel();
        // check if the session is already connected to a channel
        Channel c = pipeline.getChannel();
        if (c != null && c.isOpen())
        {
                Constants.ahessianLogger.warn(ctx.getChannel()+" session already attached -> close connection");
                c.close();
        }
        // now that we have a session extend the pipeline
        ChannelPipeline currentPipeline = ctx.getPipeline();
        pipeline.mixin(currentPipeline);
        ctx.setAttachment(session);
        _channel = ctx.getChannel();
        // first send session and wait until it has been transmitted
        ChannelFuture future = Channels.future(ctx.getChannel());
        Channels.write(ctx, future, ChannelBuffers.wrappedBuffer(session.getId().getBytes()));
        try
        {
                future.await();
        }
        catch (InterruptedException e)
        {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
        // only then inform the mixin pipeline
        ctx.sendUpstream(_connectedEvent);
}
 

实例 6


@Test(expected = ChannelException.class)
public void shouldPropagateDownstreamConnectOnPipelineFutureSuccess() throws Exception {
    context.checking(new Expectations() {
        {
            oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(any(PreparationEvent.class)));
            oneOf(upstream).handleUpstream(with(any(ChannelHandlerContext.class)), with(channelState(OPEN, TRUE)));
            oneOf(downstream).handleDownstream(with(any(ChannelHandlerContext.class)),
                    with(channelState(CONNECTED, new LocalAddress("test"))));
        }
    });
    channelFactory.newChannel(pipeline);
    ChannelFuture executionFuture = execution.getHandlerFuture();
    executionFuture.setSuccess();
    ChannelFuture handlerFuture = handler.getHandlerFuture();
    handlerFuture.sync();
    context.assertIsSatisfied();
}
 

实例 7


@Override
public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent evt) throws Exception {
    ChannelFuture pipelineFuture = getPipelineFuture();
    ChannelFuture handlerFuture = getHandlerFuture();
    // while handler future not complete, queue channel events
    if (queue != null && pipelineFuture.isDone() && !handlerFuture.isDone()) {
        queue.add(evt);
    }
    else {
        // TODO: review need for synchronized
        synchronized (ctx) {
            ctx.sendDownstream(evt);
        }
    }
}
 

实例 8


private ChannelFutureListener createConnectCompleteListener(final RegionInfo regionInfo) {
    return new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture connectFuture) throws Exception {
            if (connectFuture.isCancelled()) {
                // This is more that the connect never really fired, as in the case of a barrier, or the the connect
                // is still in process here, so an empty line annotates that it did not do a connect, an actual connect
                // failure should fail the future
                progress.addScriptFailure(regionInfo, "");
            }
            else if (!connectFuture.isSuccess()) {
                Throwable cause = connectFuture.getCause();
                String message = format("connect failed: %s", cause.getMessage());
                progress.addScriptFailure(regionInfo, message);
            }
        }
    };
}
 
讨论
淘淘あ西西 profile image