Search in sources :

Example 56 with HttpTrade

use of org.jocean.http.server.HttpServerBuilder.HttpTrade in project jocean-http by isdom.

the class DefaultHttpClientTestCase method testInitiatorInteractionUnsubscribedAlreadyAsHttp.

@Test(timeout = 5000)
public void testInitiatorInteractionUnsubscribedAlreadyAsHttp() throws Exception {
    // 配置 池化分配器 为 取消缓存,使用 Heap
    configDefaultAllocator();
    final PooledByteBufAllocator allocator = defaultAllocator();
    final String addr = UUID.randomUUID().toString();
    final BlockingQueue<HttpTrade> trades = new ArrayBlockingQueue<>(1);
    final Subscription server = TestHttpUtil.createTestServerWith(addr, trades, Feature.ENABLE_LOGGING);
    final DefaultHttpClient client = new DefaultHttpClient(new TestChannelCreator(), Feature.ENABLE_LOGGING);
    assertEquals(0, allActiveAllocationsCount(allocator));
    try {
        startInteraction(client.initiator().remoteAddress(new LocalAddress(addr)), Observable.just(fullHttpRequest()), new Interaction() {

            @Override
            public void interact(final HttpInitiator initiator, final Observable<DisposableWrapper<FullHttpResponse>> getresp) throws Exception {
                final TestSubscriber<DisposableWrapper<FullHttpResponse>> subscriber = new TestSubscriber<>();
                subscriber.unsubscribe();
                final Subscription subscription = getresp.subscribe(subscriber);
                assertTrue(subscription.isUnsubscribed());
                subscriber.assertNoTerminalEvent();
                subscriber.assertNoValues();
            }
        });
        assertEquals(0, allActiveAllocationsCount(allocator));
    } finally {
        client.close();
        server.unsubscribe();
    }
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) DisposableWrapper(org.jocean.idiom.DisposableWrapper) SSLException(javax.net.ssl.SSLException) TransportException(org.jocean.http.TransportException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) HttpInitiator(org.jocean.http.client.HttpClient.HttpInitiator) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) TestSubscriber(rx.observers.TestSubscriber) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) Subscription(rx.Subscription) Test(org.junit.Test)

Example 57 with HttpTrade

use of org.jocean.http.server.HttpServerBuilder.HttpTrade 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)

Example 58 with HttpTrade

use of org.jocean.http.server.HttpServerBuilder.HttpTrade in project jocean-http by isdom.

the class DefaultHttpTradeTestCase method testTradeForCompleteRound.

@Test
public final void testTradeForCompleteRound() {
    final DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/", Nettys4Test.buildByteBuf("test content"));
    final EmbeddedChannel channel = new EmbeddedChannel();
    final HttpTrade trade = new DefaultHttpTrade(channel);
    // trade.inboundHolder().setMaxBlockSize(-1);
    writeToInboundAndFlush(channel, request);
    assertTrue(trade.isActive());
    final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
    trade.outbound(Observable.<HttpObject>just(response));
    assertFalse(trade.isActive());
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) Nettys4Test(org.jocean.http.util.Nettys4Test) Test(org.junit.Test)

Example 59 with HttpTrade

use of org.jocean.http.server.HttpServerBuilder.HttpTrade in project jocean-http by isdom.

the class DefaultHttpTradeTestCase method testTradeForCompleteRoundWithMultiContentRequest.

@Test
public final void testTradeForCompleteRoundWithMultiContentRequest() {
    final DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
    final HttpContent[] req_contents = Nettys4Test.buildContentArray(REQ_CONTENT.getBytes(Charsets.UTF_8), 1);
    final EmbeddedChannel channel = new EmbeddedChannel();
    final HttpTrade trade = new DefaultHttpTrade(channel);
    Observable.<HttpObject>concat(Observable.<HttpObject>just(request), Observable.<HttpObject>from(req_contents), Observable.<HttpObject>just(LastHttpContent.EMPTY_LAST_CONTENT)).subscribe(obj -> writeToInboundAndFlush(channel, obj));
    // new Action1<HttpObject>() {
    // @Override
    // public void call(final HttpObject obj) {
    // writeToInboundAndFlush(channel, obj);
    // }}
    assertTrue(trade.isActive());
    final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
    trade.outbound(Observable.<HttpObject>just(response));
    assertFalse(trade.isActive());
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpObject(io.netty.handler.codec.http.HttpObject) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Nettys4Test(org.jocean.http.util.Nettys4Test) Test(org.junit.Test)

Aggregations

HttpTrade (org.jocean.http.server.HttpServerBuilder.HttpTrade)59 Test (org.junit.Test)56 Subscription (rx.Subscription)41 DisposableWrapper (org.jocean.idiom.DisposableWrapper)29 LocalAddress (io.netty.channel.local.LocalAddress)26 IOException (java.io.IOException)25 ArrayBlockingQueue (java.util.concurrent.ArrayBlockingQueue)25 PooledByteBufAllocator (io.netty.buffer.PooledByteBufAllocator)24 HttpInitiator (org.jocean.http.client.HttpClient.HttpInitiator)24 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)23 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)23 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)20 Nettys4Test (org.jocean.http.util.Nettys4Test)20 TestSubscriber (rx.observers.TestSubscriber)20 SSLException (javax.net.ssl.SSLException)18 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)17 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)17 HttpObject (io.netty.handler.codec.http.HttpObject)17 ConnectException (java.net.ConnectException)17 CertificateException (java.security.cert.CertificateException)17