Search in sources :

Example 1 with DisposableWrapper

use of org.jocean.idiom.DisposableWrapper in project jocean-http by isdom.

the class StreamUtil method src2dwb.

public static <SRC, STATE> Transformer<SRC, DisposableWrapper<ByteBuf>> src2dwb(final Func0<DisposableWrapper<ByteBuf>> newdwb, final Func1<SRC, byte[]> src2bytes, final Func1<SRC, STATE> newstate, final Action2<SRC, STATE> updatestate) {
    final AtomicReference<DisposableWrapper<ByteBuf>> ref = new AtomicReference<>();
    return new Transformer<SRC, DisposableWrapper<ByteBuf>>() {

        @Override
        public Observable<DisposableWrapper<ByteBuf>> call(final Observable<SRC> upstream) {
            return upstream.flatMap(new Func1<SRC, Observable<DisposableWrapper<ByteBuf>>>() {

                @Override
                public Observable<DisposableWrapper<ByteBuf>> call(final SRC src) {
                    if (null == ref.get()) {
                        ref.set(newdwb.call());
                        StateableUtil.setStateTo(newstate.call(src), ref.get());
                    }
                    final byte[] bytes = src2bytes.call(src);
                    if (bytes.length <= ref.get().unwrap().maxWritableBytes()) {
                        ref.get().unwrap().writeBytes(bytes);
                        updatestate.call(src, StateableUtil.<STATE>stateOf(ref.get()));
                        return Observable.empty();
                    } else {
                        final DisposableWrapper<ByteBuf> newbuf = newdwb.call();
                        newbuf.unwrap().writeBytes(bytes);
                        StateableUtil.setStateTo(newstate.call(src), newbuf);
                        return Observable.just(ref.getAndSet(newbuf));
                    }
                }
            }, new Func1<Throwable, Observable<DisposableWrapper<ByteBuf>>>() {

                @Override
                public Observable<DisposableWrapper<ByteBuf>> call(final Throwable e) {
                    return Observable.error(e);
                }
            }, new Func0<Observable<DisposableWrapper<ByteBuf>>>() {

                @Override
                public Observable<DisposableWrapper<ByteBuf>> call() {
                    if (null == ref.get()) {
                        LOG.debug("src2dwb onCompleted with ref is null");
                        return Observable.empty();
                    } else {
                        final DisposableWrapper<ByteBuf> last = ref.getAndSet(null);
                        if (last.unwrap().readableBytes() > 0) {
                            LOG.debug("src2dwb onCompleted with last as content");
                            return Observable.just(last);
                        } else {
                            last.dispose();
                            LOG.debug("src2dwb onCompleted with last NO content");
                            return Observable.empty();
                        }
                    }
                }
            }).doOnUnsubscribe(new Action0() {

                @Override
                public void call() {
                    final DisposableWrapper<ByteBuf> last = ref.getAndSet(null);
                    if (null != last) {
                        LOG.debug("src2dwb doOnUnsubscribe with last disposed.");
                        last.dispose();
                    }
                }
            });
        }
    };
}
Also used : Action0(rx.functions.Action0) Transformer(rx.Observable.Transformer) DisposableWrapper(org.jocean.idiom.DisposableWrapper) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteBuf(io.netty.buffer.ByteBuf) Observable(rx.Observable) Func1(rx.functions.Func1) Func0(rx.functions.Func0)

Example 2 with DisposableWrapper

use of org.jocean.idiom.DisposableWrapper in project jocean-http by isdom.

the class DefaultHttpClientTestCase method testInitiatorInteractionNo1NotSendNo2SuccessReuseChannelAsHttps.

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

            @Override
            public void interact(final HttpInitiator initiator, final Observable<DisposableWrapper<FullHttpResponse>> getresp) throws Exception {
                final TestSubscriber<DisposableWrapper<FullHttpResponse>> subscriber = new TestSubscriber<>();
                getresp.subscribe(subscriber);
                subscriber.awaitTerminalEvent();
                subscriber.assertError(RuntimeException.class);
                subscriber.assertNoValues();
            }
        }).transport();
        assertEquals(0, allActiveAllocationsCount(allocator));
        final Channel ch2 = (Channel) startInteraction(client.initiator().remoteAddress(new LocalAddress(addr)), Observable.just(fullHttpRequest()), standardInteraction(allocator, trades)).transport();
        assertEquals(0, allActiveAllocationsCount(allocator));
        assertSame(ch1, ch2);
    } finally {
        client.close();
        server.unsubscribe();
    }
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) DisposableWrapper(org.jocean.idiom.DisposableWrapper) Channel(io.netty.channel.Channel) 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 3 with DisposableWrapper

use of org.jocean.idiom.DisposableWrapper in project jocean-http by isdom.

the class DefaultHttpClientTestCase method testInitiatorMultiInteractionSuccessAsHttp.

@Test(timeout = 5000)
public void testInitiatorMultiInteractionSuccessAsHttp() throws Exception {
    // 配置 池化分配器 为 取消缓存,使用 Heap
    configDefaultAllocator();
    final PooledByteBufAllocator allocator = defaultAllocator();
    assertEquals(0, allActiveAllocationsCount(allocator));
    final BlockingQueue<HttpTrade> trades = new ArrayBlockingQueue<>(1);
    final String addr = UUID.randomUUID().toString();
    final Subscription server = TestHttpUtil.createTestServerWith(addr, trades, Feature.ENABLE_LOGGING);
    final DefaultHttpClient client = new DefaultHttpClient(new TestChannelCreator(), Feature.ENABLE_LOGGING);
    try (final HttpInitiator initiator = client.initiator().remoteAddress(new LocalAddress(addr)).build().toBlocking().single()) {
        {
            final Observable<? extends DisposableWrapper<HttpObject>> cached = initiator.defineInteraction(Observable.just(fullHttpRequest())).cache();
            cached.subscribe();
            // server side recv req
            final HttpTrade trade = trades.take();
            // recv all request
            trade.inbound().toCompletable().await();
            assertEquals(0, allActiveAllocationsCount(allocator));
            final ByteBuf svrRespContent = allocator.buffer(CONTENT.length).writeBytes(CONTENT);
            // send back resp
            trade.outbound(TestHttpUtil.buildByteBufResponse("text/plain", svrRespContent));
            // wait for recv all resp at client side
            cached.toCompletable().await();
            svrRespContent.release();
            assertTrue(Arrays.equals(dumpResponseContentAsBytes(cached.compose(RxNettys.message2fullresp(initiator))), CONTENT));
            cached.doOnNext(DISPOSE_EACH).toCompletable().await();
        }
        assertEquals(0, allActiveAllocationsCount(allocator));
        {
            final Observable<? extends DisposableWrapper<HttpObject>> cached = initiator.defineInteraction(Observable.just(fullHttpRequest())).cache();
            final Observable<HttpObject> resp2 = cached.map(DisposableWrapperUtil.<HttpObject>unwrap());
            resp2.subscribe();
            // server side recv req
            final HttpTrade trade = trades.take();
            // recv all request
            trade.inbound().toCompletable().await();
            // assertEquals(0, allActiveAllocationsCount(allocator));
            final ByteBuf svrRespContent = allocator.buffer(CONTENT.length).writeBytes(CONTENT);
            // send back resp
            trade.outbound(TestHttpUtil.buildByteBufResponse("text/plain", svrRespContent));
            // wait for recv all resp at client side
            resp2.toCompletable().await();
            svrRespContent.release();
            assertTrue(Arrays.equals(dumpResponseContentAsBytes(cached.compose(RxNettys.message2fullresp(initiator))), CONTENT));
        }
    } finally {
        assertEquals(0, allActiveAllocationsCount(allocator));
        client.close();
        server.unsubscribe();
    }
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) DisposableWrapper(org.jocean.idiom.DisposableWrapper) ByteBuf(io.netty.buffer.ByteBuf) ConnectableObservable(rx.observables.ConnectableObservable) Observable(rx.Observable) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) HttpInitiator(org.jocean.http.client.HttpClient.HttpInitiator) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) HttpObject(io.netty.handler.codec.http.HttpObject) Subscription(rx.Subscription) Test(org.junit.Test)

Example 4 with DisposableWrapper

use of org.jocean.idiom.DisposableWrapper in project jocean-http by isdom.

the class DefaultHttpClientTestCase method testInitiatorMultiCalldefineInteractionAndSubscribe.

@Test(timeout = 5000)
public void testInitiatorMultiCalldefineInteractionAndSubscribe() throws Exception {
    // 配置 池化分配器 为 取消缓存,使用 Heap
    configDefaultAllocator();
    final PooledByteBufAllocator allocator = defaultAllocator();
    assertEquals(0, allActiveAllocationsCount(allocator));
    final BlockingQueue<HttpTrade> trades = new ArrayBlockingQueue<>(1);
    final String addr = UUID.randomUUID().toString();
    final Subscription server = TestHttpUtil.createTestServerWith(addr, trades, Feature.ENABLE_LOGGING);
    final DefaultHttpClient client = new DefaultHttpClient(new TestChannelCreator(), Feature.ENABLE_LOGGING);
    try (final HttpInitiator initiator = client.initiator().remoteAddress(new LocalAddress(addr)).build().toBlocking().single()) {
        final Observable<? extends DisposableWrapper<HttpObject>> resp1 = initiator.defineInteraction(Observable.just(fullHttpRequest()));
        final Observable<? extends DisposableWrapper<HttpObject>> resp2 = initiator.defineInteraction(Observable.just(fullHttpRequest()));
        resp1.subscribe();
        final TestSubscriber<DisposableWrapper<HttpObject>> subscriber = new TestSubscriber<>();
        resp2.subscribe(subscriber);
        subscriber.awaitTerminalEvent();
        subscriber.assertError(RuntimeException.class);
    // assertEquals(0, allActiveAllocationsCount(allocator));
    } finally {
        client.close();
        server.unsubscribe();
    }
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) DisposableWrapper(org.jocean.idiom.DisposableWrapper) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) HttpInitiator(org.jocean.http.client.HttpClient.HttpInitiator) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) HttpObject(io.netty.handler.codec.http.HttpObject) TestSubscriber(rx.observers.TestSubscriber) Subscription(rx.Subscription) Test(org.junit.Test)

Example 5 with DisposableWrapper

use of org.jocean.idiom.DisposableWrapper in project jocean-http by isdom.

the class DefaultHttpClientTestCase method testInitiatorInteractionSuccessAsHttp.

@Test(timeout = 5000)
public void testInitiatorInteractionSuccessAsHttp() throws Exception {
    // 配置 池化分配器 为 取消缓存,使用 Heap
    configDefaultAllocator();
    final PooledByteBufAllocator allocator = defaultAllocator();
    assertEquals(0, allActiveAllocationsCount(allocator));
    final BlockingQueue<HttpTrade> trades = new ArrayBlockingQueue<>(1);
    final String addr = UUID.randomUUID().toString();
    final Subscription server = TestHttpUtil.createTestServerWith(addr, trades, Feature.ENABLE_LOGGING);
    final DefaultHttpClient client = new DefaultHttpClient(new TestChannelCreator(), Feature.ENABLE_LOGGING);
    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 Observable<DisposableWrapper<FullHttpResponse>> cached = getresp.cache();
                cached.subscribe();
                // response.subscribe();
                // server side recv req
                final HttpTrade trade = trades.take();
                // recv all request
                trade.inbound().toCompletable().await();
                assertEquals(0, allActiveAllocationsCount(allocator));
                final ByteBuf svrRespContent = allocator.buffer(CONTENT.length).writeBytes(CONTENT);
                assertEquals(1, allActiveAllocationsCount(allocator));
                // send back resp
                trade.outbound(TestHttpUtil.buildByteBufResponse("text/plain", svrRespContent));
                // wait for recv all resp at client side
                cached.toCompletable().await();
                svrRespContent.release();
                // holder create clientside resp's content
                assertEquals(1, allActiveAllocationsCount(allocator));
                assertTrue(Arrays.equals(dumpResponseContentAsBytes(cached), CONTENT));
            }
        });
    } finally {
        assertEquals(0, allActiveAllocationsCount(allocator));
        client.close();
        server.unsubscribe();
    }
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) DisposableWrapper(org.jocean.idiom.DisposableWrapper) ByteBuf(io.netty.buffer.ByteBuf) SSLException(javax.net.ssl.SSLException) TransportException(org.jocean.http.TransportException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ConnectableObservable(rx.observables.ConnectableObservable) Observable(rx.Observable) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) HttpInitiator(org.jocean.http.client.HttpClient.HttpInitiator) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) Subscription(rx.Subscription) Test(org.junit.Test)

Aggregations

DisposableWrapper (org.jocean.idiom.DisposableWrapper)32 HttpTrade (org.jocean.http.server.HttpServerBuilder.HttpTrade)29 Test (org.junit.Test)28 HttpInitiator (org.jocean.http.client.HttpClient.HttpInitiator)23 PooledByteBufAllocator (io.netty.buffer.PooledByteBufAllocator)20 LocalAddress (io.netty.channel.local.LocalAddress)20 ArrayBlockingQueue (java.util.concurrent.ArrayBlockingQueue)20 Subscription (rx.Subscription)20 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)19 TestSubscriber (rx.observers.TestSubscriber)19 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)18 IOException (java.io.IOException)18 ConnectException (java.net.ConnectException)17 CertificateException (java.security.cert.CertificateException)17 SSLException (javax.net.ssl.SSLException)17 TransportException (org.jocean.http.TransportException)17 ByteBuf (io.netty.buffer.ByteBuf)12 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)12 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)12 Observable (rx.Observable)11