Example usage for io.netty.channel.embedded EmbeddedChannel runPendingTasks

List of usage examples for io.netty.channel.embedded EmbeddedChannel runPendingTasks

Introduction

In this page you can find the example usage for io.netty.channel.embedded EmbeddedChannel runPendingTasks.

Prototype

public void runPendingTasks() 

Source Link

Document

Run all tasks (which also includes scheduled tasks) that are pending in the EventLoop for this Channel

Usage

From source file:com.vela.iot.active.netty.http2.server.LastInboundHandler.java

License:Apache License

public void writeOutbound(Object... msgs) throws Exception {
    for (Object msg : msgs) {
        ctx.write(msg);//from  w w w . j ava2  s.  c  o m
    }
    ctx.flush();
    EmbeddedChannel ch = (EmbeddedChannel) ctx.channel();
    ch.runPendingTasks();
    ch.checkException();
    checkException();
}

From source file:eu.stratosphere.runtime.io.network.netty.InboundEnvelopeDecoderTest.java

License:Apache License

@Test
public void testBufferStaging() throws Exception {
    final InboundEnvelopeDecoder decoder = new InboundEnvelopeDecoder(this.bufferProviderBroker);
    final EmbeddedChannel ch = new EmbeddedChannel(new OutboundEnvelopeEncoder(), decoder);

    when(this.bufferProviderBroker.getBufferProvider(anyJobId(), anyChannelId()))
            .thenReturn(this.bufferProvider);

    // --------------------------------------------------------------------

    Envelope[] envelopes = nextEnvelopes(3, true);

    ByteBuf buf = encode(ch, envelopes);

    when(this.bufferProvider
            .registerBufferAvailabilityListener(Matchers.<BufferAvailabilityListener>anyObject()))
                    .thenReturn(BufferAvailabilityRegistration.SUCCEEDED_REGISTERED);

    Buffer buffer = allocBuffer(envelopes[2].getBuffer().size());

    when(this.bufferProvider.requestBuffer(anyInt())).thenReturn(null, null, buffer, null);

    // --------------------------------------------------------------------

    // slices: [0] => full envelope, [1] => half envelope, [2] => remaining half + full envelope
    ByteBuf[] slices = slice(buf, OutboundEnvelopeEncoder.HEADER_SIZE + envelopes[0].getBuffer().size(),
            OutboundEnvelopeEncoder.HEADER_SIZE + envelopes[1].getBuffer().size() / 2);

    // 1. no buffer available, incoming slice contains all data
    int refCount = slices[0].refCnt();

    decodeAndVerify(ch, slices[0]);/*from   w w  w  . j  a  va 2  s .  co m*/

    Assert.assertEquals(refCount + 1, slices[0].refCnt());
    Assert.assertFalse(ch.config().isAutoRead());

    // notify of available buffer (=> bufferAvailable() callback does return a buffer
    // of the current network buffer size; the decoder needs to adjust its size to the
    // requested size
    decoder.bufferAvailable(allocBuffer(envelopes[0].getBuffer().size() * 2));
    ch.runPendingTasks();

    Assert.assertEquals(refCount - 1, slices[0].refCnt());
    Assert.assertTrue(ch.config().isAutoRead());

    decodeAndVerify(ch, envelopes[0]);

    // 2. no buffer available, incoming slice does NOT contain all data
    refCount = slices[1].refCnt();

    decodeAndVerify(ch, slices[1]);

    Assert.assertEquals(refCount + 1, slices[1].refCnt());
    Assert.assertFalse(ch.config().isAutoRead());

    decoder.bufferAvailable(allocBuffer());
    ch.runPendingTasks();

    Assert.assertEquals(refCount - 1, slices[1].refCnt());
    Assert.assertTrue(ch.config().isAutoRead());

    decodeAndVerify(ch);

    // 3. buffer available
    refCount = slices[2].refCnt();

    decodeAndVerify(ch, slices[2], envelopes[1], envelopes[2]);

    Assert.assertEquals(refCount - 1, slices[2].refCnt());
    Assert.assertTrue(ch.config().isAutoRead());

    Assert.assertEquals(1, buf.refCnt());
    buf.release();
}

From source file:eu.stratosphere.runtime.io.network.netty.InboundEnvelopeDecoderTest.java

License:Apache License

@Test
public void testEncodeDecodeRandomEnvelopes() throws Exception {
    final InboundEnvelopeDecoder decoder = new InboundEnvelopeDecoder(this.bufferProviderBroker);
    final EmbeddedChannel ch = new EmbeddedChannel(new OutboundEnvelopeEncoder(), decoder);

    when(this.bufferProviderBroker.getBufferProvider(anyJobId(), anyChannelId()))
            .thenReturn(this.bufferProvider);

    when(this.bufferProvider.requestBuffer(anyInt())).thenAnswer(new Answer<Object>() {
        @Override/*from   ww w.  j a va  2 s . co m*/
        public Object answer(InvocationOnMock invocation) throws Throwable {
            // fulfill the buffer request with the requested size
            return allocBuffer((Integer) invocation.getArguments()[0]);
        }
    });

    Random randomAnswerSource = new Random(RANDOM_SEED);

    RandomBufferRequestAnswer randomBufferRequestAnswer = new RandomBufferRequestAnswer(randomAnswerSource);

    RandomBufferAvailabilityRegistrationAnswer randomBufferAvailabilityRegistrationAnswer = new RandomBufferAvailabilityRegistrationAnswer(
            randomAnswerSource, randomBufferRequestAnswer);

    when(this.bufferProvider.requestBuffer(anyInt())).thenAnswer(randomBufferRequestAnswer);

    when(this.bufferProvider
            .registerBufferAvailabilityListener(Matchers.<BufferAvailabilityListener>anyObject()))
                    .thenAnswer(randomBufferAvailabilityRegistrationAnswer);

    // --------------------------------------------------------------------

    Envelope[] envelopes = nextRandomEnvelopes(1024);

    ByteBuf buf = encode(ch, envelopes);

    ByteBuf[] slices = randomSlices(buf);

    for (ByteBuf slice : slices) {
        int refCount = slice.refCnt();
        ch.writeInbound(slice);

        // registered BufferAvailabilityListener => call bufferAvailable(buffer)
        while (randomBufferAvailabilityRegistrationAnswer.isRegistered()) {
            randomBufferAvailabilityRegistrationAnswer.unregister();

            Assert.assertFalse(ch.config().isAutoRead());
            Assert.assertEquals(refCount + 1, slice.refCnt());

            // return a buffer of max size => decoder needs to limit buffer size
            decoder.bufferAvailable(allocBuffer(MAX_BUFFER_SIZE));
            ch.runPendingTasks();
        }

        Assert.assertEquals(refCount - 1, slice.refCnt());
        Assert.assertTrue(ch.config().isAutoRead());
    }

    Envelope[] expected = randomBufferAvailabilityRegistrationAnswer.removeSkippedEnvelopes(envelopes);

    decodeAndVerify(ch, expected);

    Assert.assertEquals(1, buf.refCnt());

    buf.release();
}

From source file:org.apache.activemq.artemis.tests.unit.core.remoting.impl.netty.NettyConnectionTest.java

License:Apache License

@Test
public void testWrite() throws Exception {
    ActiveMQBuffer buff = ActiveMQBuffers.wrappedBuffer(ByteBuffer.allocate(128));
    EmbeddedChannel channel = createChannel();

    Assert.assertEquals(0, channel.outboundMessages().size());

    NettyConnection conn = new NettyConnection(emptyMap, channel, new MyListener(), false, false);
    conn.write(buff);/*from   w  ww.  j  av  a 2  s. c o  m*/
    channel.runPendingTasks();
    Assert.assertEquals(1, channel.outboundMessages().size());
}

From source file:org.apache.flink.runtime.io.network.netty.PartitionRequestQueueTest.java

License:Apache License

@Test
public void testProducerFailedException() throws Exception {
    PartitionRequestQueue queue = new PartitionRequestQueue();

    EmbeddedChannel ch = new EmbeddedChannel(queue);

    ResultSubpartitionView view = mock(ResultSubpartitionView.class);
    when(view.isReleased()).thenReturn(true);
    when(view.getFailureCause()).thenReturn(new RuntimeException("Expected test exception"));

    // Enqueue the erroneous view
    queue.enqueue(view, new InputChannelID());
    ch.runPendingTasks();

    // Read the enqueued msg
    Object msg = ch.readOutbound();

    assertEquals(msg.getClass(), NettyMessage.ErrorResponse.class);

    NettyMessage.ErrorResponse err = (NettyMessage.ErrorResponse) msg;
    assertTrue(err.cause instanceof CancelTaskException);
}

From source file:org.hornetq.tests.unit.core.remoting.impl.netty.NettyConnectionTest.java

License:Apache License

@Test
public void testWrite() throws Exception {
    HornetQBuffer buff = HornetQBuffers.wrappedBuffer(ByteBuffer.allocate(128));
    EmbeddedChannel channel = createChannel();

    Assert.assertEquals(0, channel.outboundMessages().size());

    NettyConnection conn = new NettyConnection(emptyMap, channel, new MyListener(), false, false);
    conn.write(buff);//ww  w  .ja  v  a 2s. c  om
    channel.runPendingTasks();
    Assert.assertEquals(1, channel.outboundMessages().size());
}

From source file:org.jboss.aerogear.simplepush.server.netty.SimplePushSockJSServiceTest.java

License:Apache License

private Set<Ack> sendAcknowledge(final EmbeddedChannel channel, final Ack... acks) {
    final Set<Ack> ups = new HashSet<Ack>(Arrays.asList(acks));
    final TextWebSocketFrame ackFrame = ackFrame(ups);
    channel.writeInbound(ackFrame);/*w  w w.  j a  v a 2  s  .  c  o  m*/
    channel.runPendingTasks();

    final Object out = channel.readOutbound();
    if (out == null) {
        return Collections.emptySet();
    }

    final NotificationMessageImpl unacked = responseToType(out, NotificationMessageImpl.class);
    return unacked.getAcks();
}

From source file:org.opendaylight.ocpjava.protocol.impl.core.connection.ChannelOutboundQueue02Test.java

License:Open Source License

/**
 * Test write to closed / opened channel
 * @throws Exception//from  w  w w  .  j  a v  a  2 s. c  o m
 */
@Test
public void test01() throws Exception {
    EmbeddedChannel ec = new EmbeddedChannel(new EmbededChannelHandler());
    adapter = new ConnectionAdapterImpl(ec, InetSocketAddress.createUnresolved("localhost", 9876));
    cache = CacheBuilder.newBuilder().concurrencyLevel(1)
            .expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES).removalListener(REMOVAL_LISTENER)
            .build();
    adapter.setResponseCache(cache);
    ChannelOutboundQueue cq = (ChannelOutboundQueue) ec.pipeline().last();
    counter = 0;
    adapter.healthCheck(healthCheckInput);
    adapter.hello(helloInput);
    cq.channelInactive(ec.pipeline().lastContext());
    ec.runPendingTasks();
    Assert.assertEquals("Wrong - ChannelOutboundHandlerAdapter.write was invoked on closed channel", 0,
            counter);
    cq.channelActive(ec.pipeline().lastContext());
    counter = 0;
    adapter.healthCheck(healthCheckInput);
    adapter.getParam(getParamInput);
    ec.runPendingTasks();
    Assert.assertEquals("Wrong - ChannelOutboundHandlerAdapter.write has not been invoked on opened channel", 2,
            counter);
}

From source file:org.opendaylight.ocpjava.protocol.impl.core.connection.ConnectionAdapterImp02lTest.java

License:Open Source License

/**
 * Test Rpc Calls/*from ww w  .  ja va2  s.c  om*/
 */
@Test
public void testRcp() {
    EmbeddedChannel embChannel = new EmbeddedChannel(new EmbededChannelHandler());
    adapter = new ConnectionAdapterImpl(embChannel, InetSocketAddress.createUnresolved("localhost", 9876));
    cache = CacheBuilder.newBuilder().concurrencyLevel(1)
            .expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES).removalListener(REMOVAL_LISTENER)
            .build();
    adapter.setResponseCache(cache);

    // -- healthCheck
    adapter.healthCheck(healthCheckInput);
    embChannel.runPendingTasks();
    Assert.assertEquals("Wrong - healthCheck", healthCheckInput, responseOfCall);

    // -- getParam
    adapter.getParam(getParamInput);
    embChannel.runPendingTasks();
    Assert.assertEquals("Wrong - getParam", getParamInput, responseOfCall);

    // -- getState
    adapter.getState(getStateInput);
    embChannel.runPendingTasks();
    Assert.assertEquals("Wrong - getState", getStateInput, responseOfCall);

    adapter.disconnect();
}

From source file:org.opendaylight.ocpjava.protocol.impl.core.connection.ConnectionAdapterImplOcpStatisticsTest.java

License:Open Source License

/**
 * Test statistic counter for all rpc calls (counters DS_ENTERED_OCPJAVA and DS_FLOW_MODS_ENTERED have to be enabled)
 *///from   w w w .  j av a 2  s .  c  o m
@Test
public void testEnterOFJavaCounter() {
    if (!statCounters.isCounterEnabled(CounterEventTypes.DS_ENTERED_OCPJAVA)) {
        Assert.fail("Counter " + CounterEventTypes.DS_ENTERED_OCPJAVA + " is not enabled");
    }
    if (!statCounters.isCounterEnabled(CounterEventTypes.DS_FLOW_MODS_ENTERED)) {
        Assert.fail("Counter " + CounterEventTypes.DS_FLOW_MODS_ENTERED + " is not enabled");
    }
    EmbeddedChannel embChannel = new EmbeddedChannel(new EmbededChannelHandler());
    adapter = new ConnectionAdapterImpl(embChannel, InetSocketAddress.createUnresolved("localhost", 9876));
    cache = CacheBuilder.newBuilder().concurrencyLevel(1)
            .expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES).removalListener(REMOVAL_LISTENER)
            .build();
    adapter.setResponseCache(cache);
    adapter.healthCheck(healthCheckInput);
    adapter.getParam(getParamInput);

    embChannel.runPendingTasks();
    Assert.assertEquals("Wrong - bad counter value for ConnectionAdapterImpl rpc methods", 2,
            statCounters.getCounter(CounterEventTypes.DS_ENTERED_OCPJAVA).getCounterValue());
    adapter.disconnect();
}