Search in sources :

Example 11 with TestChannelCreator

use of org.jocean.http.client.impl.TestChannelCreator in project jocean-http by isdom.

the class DefaultSignalClientTestCase method testSignalClientOnlySignalForPost.

@Test
public void testSignalClientOnlySignalForPost() throws Exception {
    final TestResponse respToSendback = new TestResponse("0", "OK");
    final AtomicReference<HttpMethod> reqMethodReceivedRef = new AtomicReference<>();
    final AtomicReference<String> reqpathReceivedRef = new AtomicReference<>();
    final AtomicReference<TestRequestByPost> reqbeanReceivedRef = new AtomicReference<>();
    final Action2<FullHttpRequest, HttpTrade> requestAndTradeAwareWhenCompleted = new Action2<FullHttpRequest, HttpTrade>() {

        @Override
        public void call(final FullHttpRequest req, final HttpTrade trade) {
            try {
                reqMethodReceivedRef.set(req.method());
                reqpathReceivedRef.set(req.uri());
                reqbeanReceivedRef.set((TestRequestByPost) JSON.parseObject(Nettys.dumpByteBufAsBytes(req.content()), TestRequestByPost.class));
            } catch (IOException e) {
                LOG.warn("exception when Nettys.dumpByteBufAsBytes, detail: {}", ExceptionUtils.exception2detail(e));
            }
            trade.outbound(buildResponse(respToSendback, trade.onTerminate()));
        }
    };
    final String testAddr = UUID.randomUUID().toString();
    final Subscription server = TestHttpUtil.createTestServerWith(testAddr, requestAndTradeAwareWhenCompleted, Feature.ENABLE_LOGGING, Feature.ENABLE_COMPRESSOR);
    try {
        final TestChannelCreator creator = new TestChannelCreator();
        final TestChannelPool pool = new TestChannelPool(1);
        final DefaultHttpClient httpclient = new DefaultHttpClient(creator, pool);
        final DefaultSignalClient signalClient = new DefaultSignalClient(new URI("http://test"), httpclient);
        signalClient.registerRequestType(TestRequestByPost.class, TestResponse.class, null, buildUri2Addr(testAddr), Feature.ENABLE_LOGGING);
        final TestRequestByPost reqToSend = new TestRequestByPost("1", null);
        final TestResponse respReceived = ((SignalClient) signalClient).interaction().request(reqToSend).<TestResponse>build().timeout(1, TimeUnit.SECONDS).toBlocking().single();
        assertEquals(HttpMethod.POST, reqMethodReceivedRef.get());
        assertEquals("/test/simpleRequest", reqpathReceivedRef.get());
        assertEquals(reqToSend, reqbeanReceivedRef.get());
        assertEquals(respToSendback, respReceived);
        pool.awaitRecycleChannels();
    } finally {
        server.unsubscribe();
    }
}
Also used : FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Action2(rx.functions.Action2) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) URI(java.net.URI) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) TestChannelPool(org.jocean.http.client.impl.TestChannelPool) DefaultSignalClient(org.jocean.http.rosa.impl.DefaultSignalClient) Subscription(rx.Subscription) HttpMethod(io.netty.handler.codec.http.HttpMethod) TestChannelCreator(org.jocean.http.client.impl.TestChannelCreator) Test(org.junit.Test)

Example 12 with TestChannelCreator

use of org.jocean.http.client.impl.TestChannelCreator in project jocean-http by isdom.

the class DefaultSignalClientTestCase method testSignalClientOnlySignalForPostWithJSONContentWithoutRegisterRespType.

@Test
public void testSignalClientOnlySignalForPostWithJSONContentWithoutRegisterRespType() throws Exception {
    final byte[] respToSendback = new byte[] { 12, 13, 14, 15 };
    final AtomicReference<HttpMethod> reqMethodReceivedRef = new AtomicReference<>();
    final AtomicReference<String> reqpathReceivedRef = new AtomicReference<>();
    final AtomicReference<TestRequestByPost> reqbeanReceivedRef = new AtomicReference<>();
    final Action2<FullHttpRequest, HttpTrade> requestAndTradeAwareWhenCompleted = new Action2<FullHttpRequest, HttpTrade>() {

        @Override
        public void call(final FullHttpRequest req, final HttpTrade trade) {
            try {
                reqMethodReceivedRef.set(req.method());
                reqpathReceivedRef.set(req.uri());
                reqbeanReceivedRef.set((TestRequestByPost) JSON.parseObject(Nettys.dumpByteBufAsBytes(req.content()), TestRequestByPost.class));
            } catch (IOException e) {
                LOG.warn("exception when Nettys.dumpByteBufAsBytes, detail: {}", ExceptionUtils.exception2detail(e));
            }
            trade.outbound(buildBytesResponse(respToSendback, trade.onTerminate()));
        }
    };
    final String testAddr = UUID.randomUUID().toString();
    final Subscription server = TestHttpUtil.createTestServerWith(testAddr, requestAndTradeAwareWhenCompleted, Feature.ENABLE_LOGGING, Feature.ENABLE_COMPRESSOR);
    try {
        final TestChannelCreator creator = new TestChannelCreator();
        final TestChannelPool pool = new TestChannelPool(1);
        final DefaultHttpClient httpclient = new DefaultHttpClient(creator, pool, Feature.ENABLE_LOGGING);
        final DefaultSignalClient signalClient = new DefaultSignalClient(new URI("http://test"), buildUri2Addr(testAddr), httpclient);
        final TestRequestByPost reqToSend = new TestRequestByPost("1", null);
        final byte[] bytesReceived = ((SignalClient) signalClient).interaction().request(reqToSend).feature(new SignalClient.UsingPath("/test/simpleRequest"), new SignalClient.UsingMethod(POST.class), new SignalClient.JSONContent("{\"code\": \"added\"}")).<byte[]>build().toBlocking().single();
        assertEquals(HttpMethod.POST, reqMethodReceivedRef.get());
        assertEquals("/test/simpleRequest", reqpathReceivedRef.get());
        reqToSend.setCode("added");
        assertEquals(reqToSend, reqbeanReceivedRef.get());
        assertTrue(Arrays.equals(respToSendback, bytesReceived));
        pool.awaitRecycleChannels();
    } finally {
        server.unsubscribe();
    }
}
Also used : FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) Action2(rx.functions.Action2) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) URI(java.net.URI) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) TestChannelPool(org.jocean.http.client.impl.TestChannelPool) DefaultSignalClient(org.jocean.http.rosa.impl.DefaultSignalClient) Subscription(rx.Subscription) HttpMethod(io.netty.handler.codec.http.HttpMethod) TestChannelCreator(org.jocean.http.client.impl.TestChannelCreator) Test(org.junit.Test)

Example 13 with TestChannelCreator

use of org.jocean.http.client.impl.TestChannelCreator in project jocean-http by isdom.

the class DefaultHttpServerBuilderTestCase method testTradeReadControl.

/* // TODO using initiator
    @Test
    public void testHttpHappyPathOnce() throws Exception {
        final String testAddr = UUID.randomUUID().toString();
        final HttpServerBuilder server = new DefaultHttpServerBuilder(
                new AbstractBootstrapCreator(
                new DefaultEventLoopGroup(1), new DefaultEventLoopGroup()) {
            @Override
            protected void initializeBootstrap(final ServerBootstrap bootstrap) {
                bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
                bootstrap.channel(LocalServerChannel.class);
            }});
        
        final Subscription testServer = 
                server.defineServer(new LocalAddress(testAddr),
                Feature.ENABLE_LOGGING,
                Feature.ENABLE_COMPRESSOR)
            .subscribe(echoReactor(null));
        final DefaultHttpClient client = new DefaultHttpClient(new TestChannelCreator());
        try {
            final Iterator<HttpObject> itr = 
                client.defineInteraction(
                    new LocalAddress(testAddr), 
                    Observable.just(buildFullRequest(CONTENT)),
                    Feature.ENABLE_LOGGING)
                .map(RxNettys.<HttpObject>retainer())
                .toBlocking().toIterable().iterator();
            
            final byte[] bytes = RxNettys.httpObjectsAsBytes(itr);
            
            assertTrue(Arrays.equals(bytes, CONTENT));
        } finally {
            client.close();
            testServer.unsubscribe();
            server.close();
        }
    }

    @Test
    public void testHttpHappyPathTwice() throws Exception {
        final String testAddr = UUID.randomUUID().toString();
        final HttpServerBuilder server = new DefaultHttpServerBuilder(
                new AbstractBootstrapCreator(
                new DefaultEventLoopGroup(1), new DefaultEventLoopGroup()) {
            @Override
            protected void initializeBootstrap(final ServerBootstrap bootstrap) {
                bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
                bootstrap.channel(LocalServerChannel.class);
            }});
        final AtomicReference<Object> transportRef = new AtomicReference<Object>();
        
        final Subscription testServer = 
                server.defineServer(new LocalAddress(testAddr),
                Feature.ENABLE_LOGGING,
                Feature.ENABLE_COMPRESSOR)
            .subscribe(echoReactor(transportRef));
        final TestChannelPool pool = new TestChannelPool(1);
        final DefaultHttpClient client = new DefaultHttpClient(new TestChannelCreator(), pool);
        try {
        
            final CountDownLatch unsubscribed = new CountDownLatch(1);
            
            final Iterator<HttpObject> itr = 
                client.defineInteraction(
                    new LocalAddress(testAddr), 
                    Observable.just(buildFullRequest(CONTENT)),
                    Feature.ENABLE_LOGGING)
                .compose(RxFunctions.<HttpObject>countDownOnUnsubscribe(unsubscribed))
                .map(RxNettys.<HttpObject>retainer())
                .toBlocking().toIterable().iterator();
            
            final byte[] bytes = RxNettys.httpObjectsAsBytes(itr);
            
            assertTrue(Arrays.equals(bytes, CONTENT));
            
            final Object channel1 = transportRef.get();
            
            unsubscribed.await();
            //  await for 1 second
            pool.awaitRecycleChannels(1);
            
            //  TODO
            //  TOBE fix, client maybe not reused, so server channel not reused, 
            //  so ensure client channel will be reused
            final Iterator<HttpObject> itr2 = 
                    client.defineInteraction(
                        new LocalAddress(testAddr), 
                        Observable.just(buildFullRequest(CONTENT)),
                        Feature.ENABLE_LOGGING)
                    .map(RxNettys.<HttpObject>retainer())
                    .toBlocking().toIterable().iterator();
                
                final byte[] bytes2 = RxNettys.httpObjectsAsBytes(itr2);
                
                assertTrue(Arrays.equals(bytes2, CONTENT));
                
                final Object channel2 = transportRef.get();
                assertTrue(channel1 == channel2);
                
        } finally {
            client.close();
            testServer.unsubscribe();
            server.close();
        }
    }
    */
@Test
public void testTradeReadControl() throws Exception {
    final String testAddr = UUID.randomUUID().toString();
    final HttpServerBuilder server = new DefaultHttpServerBuilder(new AbstractBootstrapCreator(new DefaultEventLoopGroup(1), new DefaultEventLoopGroup()) {

        @Override
        protected void initializeBootstrap(final ServerBootstrap bootstrap) {
            bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
            bootstrap.channel(LocalServerChannel.class);
        }
    });
    final BlockingQueue<HttpTrade> trades = new ArrayBlockingQueue<>(2);
    final Subscription testServer = server.defineServer(new LocalAddress(testAddr), Feature.ENABLE_LOGGING, Feature.ENABLE_COMPRESSOR).subscribe(new Action1<HttpTrade>() {

        @Override
        public void call(final HttpTrade trade) {
            LOG.debug("on trade {}", trade);
            try {
                trades.put(trade);
                LOG.debug("after offer trade {}", trade);
            } catch (InterruptedException e) {
                LOG.warn("exception when put trade, detail: {}", ExceptionUtils.exception2detail(e));
            }
        }
    });
    final TestChannelPool pool = new TestChannelPool(1);
    final DefaultHttpClient client = new DefaultHttpClient(new TestChannelCreator(), pool);
    try (final HttpInitiator initiator = client.initiator().remoteAddress(new LocalAddress(testAddr)).build().toBlocking().single()) {
        final FullHttpRequest reqToSend1 = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
        initiator.defineInteraction(Observable.just(reqToSend1)).subscribe();
        final HttpTrade trade1 = trades.take();
        // trade receive all inbound msg
        // trade1.obsrequest().toCompletable().await();
        final FullHttpRequest reqReceived1 = trade1.inbound().compose(RxNettys.message2fullreq(trade1)).toBlocking().single().unwrap();
        assertEquals(reqToSend1, reqReceived1);
        final Channel channel = (Channel) initiator.transport();
        final FullHttpRequest reqToSend2 = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/2nd");
        channel.writeAndFlush(reqToSend2).sync();
        assertTrue(null == trades.poll(1L, TimeUnit.SECONDS));
        // after send other interaction req, then first trade send response
        final FullHttpResponse responseToSend1 = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
        trade1.outbound(Observable.<HttpObject>just(responseToSend1));
        // initiator.inbound().message().toCompletable().await();
        // final FullHttpResponse resp = initiator.inbound().messageHolder().
        // httpMessageBuilder(RxNettys.BUILD_FULL_RESPONSE).call();
        // assertEquals(responseToSend1, resp);
        final HttpTrade trade2 = trades.take();
        // receive all inbound msg
        // trade2.obsrequest().toCompletable().await();
        final FullHttpRequest reqReceived2 = trade2.inbound().compose(RxNettys.message2fullreq(trade2)).toBlocking().single().unwrap();
        assertEquals(reqToSend2, reqReceived2);
    } finally {
        client.close();
        testServer.unsubscribe();
        server.close();
    }
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) LocalAddress(io.netty.channel.local.LocalAddress) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Channel(io.netty.channel.Channel) HttpServerBuilder(org.jocean.http.server.HttpServerBuilder) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) HttpInitiator(org.jocean.http.client.HttpClient.HttpInitiator) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) TestChannelPool(org.jocean.http.client.impl.TestChannelPool) LocalServerChannel(io.netty.channel.local.LocalServerChannel) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) Subscription(rx.Subscription) TestChannelCreator(org.jocean.http.client.impl.TestChannelCreator) Test(org.junit.Test)

Aggregations

FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)13 DefaultHttpClient (org.jocean.http.client.impl.DefaultHttpClient)13 TestChannelCreator (org.jocean.http.client.impl.TestChannelCreator)13 HttpTrade (org.jocean.http.server.HttpServerBuilder.HttpTrade)13 Subscription (rx.Subscription)13 TestChannelPool (org.jocean.http.client.impl.TestChannelPool)12 Test (org.junit.Test)12 HttpMethod (io.netty.handler.codec.http.HttpMethod)11 URI (java.net.URI)11 AtomicReference (java.util.concurrent.atomic.AtomicReference)11 DefaultSignalClient (org.jocean.http.rosa.impl.DefaultSignalClient)11 Action2 (rx.functions.Action2)11 IOException (java.io.IOException)8 SignalClient (org.jocean.http.rosa.SignalClient)5 HttpObject (io.netty.handler.codec.http.HttpObject)4 QueryStringDecoder (io.netty.handler.codec.http.QueryStringDecoder)4 POST (javax.ws.rs.POST)3 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)2 DefaultEventLoopGroup (io.netty.channel.DefaultEventLoopGroup)2 LocalAddress (io.netty.channel.local.LocalAddress)2