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

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

Introduction

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

Prototype

public boolean writeOutbound(Object... msgs) 

Source Link

Document

Write messages to the outbound of this Channel .

Usage

From source file:com.couchbase.client.core.endpoint.AbstractGenericHandlerTest.java

License:Apache License

@Test(expected = CouchbaseException.class)
public void whenDecodeFailureShouldOnErrorFailureWrappedInCouchbaseException() {
    AbstractGenericHandler<Object, Object, GetDesignDocumentRequest> handler = createFakeHandler(
            new FakeHandlerDelegate<Object, Object, GetDesignDocumentRequest>() {
                @Override/*from  ww w . j  a v a2 s  .  c  o m*/
                public Object encodeRequest(ChannelHandlerContext ctx, GetDesignDocumentRequest msg)
                        throws Exception {
                    return new Object();
                }

                @Override
                public CouchbaseResponse decodeResponse(ChannelHandlerContext ctx, Object msg)
                        throws Exception {
                    throw new IllegalStateException("this is fake");
                }
            });
    EmbeddedChannel channel = new EmbeddedChannel(handler);
    GetDesignDocumentRequest request = new GetDesignDocumentRequest("any", false, "bucket", "password");
    channel.writeOutbound(request);
    channel.writeInbound(new Object());

    try {
        request.observable().timeout(1, TimeUnit.SECONDS).toBlocking().last();
    } catch (CouchbaseException e) {
        assertNotNull(e.getCause());
        assertTrue(e.getCause() instanceof IllegalStateException);
        assertEquals("this is fake", e.getCause().getMessage());
        throw e;
    }
}

From source file:com.couchbase.client.core.endpoint.AbstractGenericHandlerTest.java

License:Apache License

@Test(expected = CouchbaseException.class)
public void whenDecodeFailureIsCouchbaseExceptionShouldOnErrorIt() {
    AbstractGenericHandler<Object, Object, GetDesignDocumentRequest> handler = createFakeHandler(
            new FakeHandlerDelegate<Object, Object, GetDesignDocumentRequest>() {
                @Override//ww  w .j av a2s . c o m
                public Object encodeRequest(ChannelHandlerContext ctx, GetDesignDocumentRequest msg)
                        throws Exception {
                    return new Object();
                }

                @Override
                public CouchbaseResponse decodeResponse(ChannelHandlerContext ctx, Object msg)
                        throws Exception {
                    throw new CouchbaseException("this is fake");
                }
            });
    EmbeddedChannel channel = new EmbeddedChannel(handler);
    GetDesignDocumentRequest request = new GetDesignDocumentRequest("any", false, "bucket", "password");
    channel.writeOutbound(request);
    channel.writeInbound(new Object());

    try {
        request.observable().timeout(1, TimeUnit.SECONDS).toBlocking().last();
    } catch (CouchbaseException e) {
        assertNull(e.getCause());
        assertEquals("this is fake", e.getMessage());
        throw e;
    }
}

From source file:com.ebay.jetstream.http.netty.client.HttpClient.java

License:MIT License

public void post(URI uri, Object content, Map<String, String> headers, ResponseFuture responsefuture)
        throws Exception {

    if (m_shutDown.get()) {
        throw new IOException("IO has been Shutdown = ");

    }/*from  ww w .  jav  a 2  s.  c  o  m*/

    if (uri == null)
        throw new NullPointerException("uri is null or incorrect");

    if (!m_started.get()) {
        synchronized (this) {
            if (!m_started.get()) {
                start();
                m_started.set(true);
            }
        }
    }

    ByteBuf byteBuf = Unpooled.buffer(m_config.getInitialRequestBufferSize());
    ByteBufOutputStream outputStream = new ByteBufOutputStream(byteBuf);

    // transform to json
    try {
        m_mapper.writeValue(outputStream, content);
    } catch (JsonGenerationException e) {
        throw e;
    } catch (JsonMappingException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        outputStream.close();
    }

    EmbeddedChannel encoder;
    String contenteEncoding;
    if ("gzip".equals(m_config.getCompressEncoder())) {
        encoder = new EmbeddedChannel(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP, 1));
        contenteEncoding = "gzip";

    } else if ("deflate".equals(m_config.getCompressEncoder())) {
        encoder = new EmbeddedChannel(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.ZLIB, 1));
        contenteEncoding = "deflate";
    } else {
        encoder = null;
        contenteEncoding = null;
    }

    if (encoder != null) {
        encoder.config().setAllocator(UnpooledByteBufAllocator.DEFAULT);
        encoder.writeOutbound(byteBuf);
        encoder.finish();
        byteBuf = (ByteBuf) encoder.readOutbound();
        encoder.close();
    }

    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
            uri.toString(), byteBuf);
    if (contenteEncoding != null) {
        HttpHeaders.setHeader(request, HttpHeaders.Names.CONTENT_ENCODING, contenteEncoding);
    }
    HttpHeaders.setHeader(request, HttpHeaders.Names.ACCEPT_ENCODING, "gzip, deflate");
    HttpHeaders.setHeader(request, HttpHeaders.Names.CONTENT_TYPE, "application/json");
    HttpHeaders.setContentLength(request, byteBuf.readableBytes());

    if (isKeepAlive())
        HttpHeaders.setHeader(request, HttpHeaders.Names.CONNECTION, "keep-alive");

    if (headers != null) {
        @SuppressWarnings("rawtypes")
        Iterator it = headers.entrySet().iterator();
        while (it.hasNext()) {
            @SuppressWarnings("rawtypes")
            Map.Entry pairs = (Map.Entry) it.next();
            HttpHeaders.setHeader(request, (String) pairs.getKey(), pairs.getValue());
        }
    }

    if (responsefuture != null) {
        RequestId reqid = RequestId.newRequestId();

        m_responseDispatcher.add(reqid, responsefuture);

        HttpHeaders.setHeader(request, "X_EBAY_REQ_ID", reqid.toString());
        // we expect this to be echoed in the response used for correlation.
    }

    if (m_dataQueue.size() < m_workQueueCapacity) {
        ProcessHttpWorkRequest workRequest = new ProcessHttpWorkRequest(this, uri, request);

        if (!m_dataQueue.offer(workRequest)) {
            if (responsefuture != null) {
                responsefuture.setFailure();
                m_responseDispatcher.remove(request.headers().get("X_EBAY_REQ_ID"));
            }
        }
    } else {
        throw new IOException("downstream Queue is full ");
    }

}

From source file:com.github.nettybook.ch7.junit.Base64EncoderTest.java

License:Apache License

@Test
public void testEncoder() {
    String writeData = "";

    ByteBuf request = Unpooled.wrappedBuffer(writeData.getBytes());

    Base64Encoder encoder = new Base64Encoder();
    EmbeddedChannel embeddedChannel = new EmbeddedChannel(encoder);

    embeddedChannel.writeOutbound(request);
    ByteBuf response = (ByteBuf) embeddedChannel.readOutbound();

    String expect = "7JWI64WV7ZWY7IS47JqU";

    assertEquals(expect, response.toString(Charset.defaultCharset()));

    embeddedChannel.finish();// w  ww  .j  a va 2s .  co  m
}

From source file:com.github.sparkfy.network.ProtocolSuite.java

License:Apache License

private void testServerToClient(Message msg) {
    EmbeddedChannel serverChannel = new EmbeddedChannel(new FileRegionEncoder(), new MessageEncoder());
    serverChannel.writeOutbound(msg);

    EmbeddedChannel clientChannel = new EmbeddedChannel(NettyUtils.createFrameDecoder(), new MessageDecoder());

    while (!serverChannel.outboundMessages().isEmpty()) {
        clientChannel.writeInbound(serverChannel.readOutbound());
    }//from w w  w  .  j av  a 2  s  .c  om

    assertEquals(1, clientChannel.inboundMessages().size());
    assertEquals(msg, clientChannel.readInbound());
}

From source file:com.github.sparkfy.network.ProtocolSuite.java

License:Apache License

private void testClientToServer(Message msg) {
    EmbeddedChannel clientChannel = new EmbeddedChannel(new FileRegionEncoder(), new MessageEncoder());
    clientChannel.writeOutbound(msg);

    EmbeddedChannel serverChannel = new EmbeddedChannel(NettyUtils.createFrameDecoder(), new MessageDecoder());

    while (!clientChannel.outboundMessages().isEmpty()) {
        serverChannel.writeInbound(clientChannel.readOutbound());
    }/* ww w .j a va 2  s .c om*/

    assertEquals(1, serverChannel.inboundMessages().size());
    assertEquals(msg, serverChannel.readInbound());
}

From source file:com.linkedin.r2.transport.http.client.TestRAPClientCodec.java

License:Apache License

@Test(dataProvider = "restRequest")
public void testRequestEncoder(String uri, RestRequest request) {
    final EmbeddedChannel ch = new EmbeddedChannel(new RAPClientCodec());

    ch.writeOutbound(request);
    FullHttpRequest nettyRequest = (FullHttpRequest) ch.readOutbound();

    Assert.assertEquals(nettyRequest.uri(), uri);
    Assert.assertEquals(nettyRequest.method(), HttpMethod.valueOf(request.getMethod()));
    Assert.assertEquals(nettyRequest.content().toString(CHARSET), request.getEntity().asString(CHARSET));
    Assert.assertEquals(nettyRequest.headers().get(HttpHeaderNames.HOST), HOST);
    assertList(nettyRequest.headers().getAll(HttpConstants.REQUEST_COOKIE_HEADER_NAME), request.getCookies());

    for (String name : request.getHeaders().keySet()) {
        Assert.assertEquals(nettyRequest.headers().get(name), request.getHeader(name));
    }/*w  w w  .ja va2s  .c  o  m*/

    ch.finish();
}

From source file:com.uber.tchannel.codecs.CodecTestUtil.java

License:Open Source License

public static TFrame encodeDecode(TFrame frame) {
    EmbeddedChannel channel = new EmbeddedChannel(new TChannelLengthFieldBasedFrameDecoder(),
            new TFrameCodec());

    channel.writeOutbound(frame);
    channel.writeInbound(channel.readOutbound());
    return channel.readInbound();
}

From source file:com.uber.tchannel.codecs.TFrameCodecTest.java

License:Open Source License

@Test
public void shouldEncodeAndDecodeFrame() {

    EmbeddedChannel channel = new EmbeddedChannel(new TChannelLengthFieldBasedFrameDecoder(),
            new TFrameCodec());

    String payload = "Hello, World!";
    ByteBuf buffer = Unpooled.wrappedBuffer(payload.getBytes());

    TFrame frame = new TFrame(payload.getBytes().length, FrameType.InitRequest, Integer.MAX_VALUE, buffer);

    channel.writeOutbound(frame);
    channel.writeInbound(channel.readOutbound());

    TFrame newFrame = channel.readInbound();
    assertNotNull(newFrame);/*  w w  w. ja v a2  s . c  om*/
    assertEquals(frame.size, newFrame.size);
    assertEquals(frame.type, newFrame.type);
    assertEquals(frame.id, newFrame.id);
    newFrame.release();

}

From source file:com.uber.tchannel.handlers.FrameFragmenterTest.java

License:Open Source License

@Test
public void testEncode() throws Exception {
    EmbeddedChannel channel = new EmbeddedChannel(new MessageFragmenter());

    // arg1//from  ww w .  j a  v  a 2  s  .c  o  m
    byte[] arg1Bytes = new byte[CallFrame.MAX_ARG1_LENGTH];
    new Random().nextBytes(arg1Bytes);
    ByteBuf arg1 = Unpooled.wrappedBuffer(arg1Bytes);

    // arg2
    byte[] arg2Bytes = new byte[BUFFER_SIZE];
    new Random().nextBytes(arg2Bytes);
    ByteBuf arg2 = Unpooled.wrappedBuffer(arg2Bytes);

    // arg 3
    byte[] arg3Bytes = new byte[BUFFER_SIZE];
    new Random().nextBytes(arg3Bytes);
    ByteBuf arg3 = Unpooled.wrappedBuffer(arg3Bytes);

    RawRequest rawRequest = new RawRequest.Builder("some-service", arg1).setArg2(arg2).setArg3(arg3).setId(0)
            .setTimeout(100).build();

    channel.writeOutbound(rawRequest);

    for (int i = 0; i < 4; i++) {
        CallFrame req = (CallFrame) MessageCodec.decode(MessageCodec.decode((ByteBuf) channel.readOutbound()));
        req.release();
        assertNotNull(req);
    }

    ByteBuf buf = channel.readOutbound();
    assertNull(buf);

    rawRequest.release();
}