Search in sources :

Example 6 with TestChannelCreator

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

the class HttpServerDemo method main.

public static void main(final String[] args) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    final // SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
    SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    // create for LocalChannel
    @SuppressWarnings("resource") 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);
        }
    }, Feature.ENABLE_LOGGING, new Feature.ENABLE_SSL(sslCtx));
    @SuppressWarnings("unused") final Subscription subscription = server.defineServer(new LocalAddress("test")).subscribe(new Action1<HttpTrade>() {

        @Override
        public void call(final HttpTrade trade) {
            trade.outbound(trade.inbound().compose(RxNettys.message2fullreq(trade)).map(DisposableWrapperUtil.<FullHttpRequest>unwrap()).map(new Func1<FullHttpRequest, HttpObject>() {

                @Override
                public HttpObject call(final FullHttpRequest fullreq) {
                    try {
                        final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(Nettys.dumpByteBufAsBytes(fullreq.content())));
                        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
                        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
                        return response;
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }));
        }
    });
    @SuppressWarnings("resource") final DefaultHttpClient client = new DefaultHttpClient(new TestChannelCreator(), Feature.ENABLE_LOGGING, new Feature.ENABLE_SSL(SslContextBuilder.forClient().build()));
    while (true) {
        final ByteBuf content = Unpooled.buffer(0);
        content.writeBytes("test content".getBytes("UTF-8"));
        final DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/", content);
        HttpUtil.setContentLength(request, content.readableBytes());
        /* // TODO using initiator
            final Iterator<HttpObject> itr =
                client.defineInteraction(
                new LocalAddress("test"), 
                Observable.just(request))
                .map(RxNettys.<HttpObject>retainer())
                .toBlocking().toIterable().iterator();
            
            final byte[] bytes = RxNettys.httpObjectsAsBytes(itr);
            LOG.info("recv Response: {}", new String(bytes, "UTF-8"));
            */
        Thread.sleep(1000);
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) HttpServerBuilder(org.jocean.http.server.HttpServerBuilder) ByteBuf(io.netty.buffer.ByteBuf) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) Feature(org.jocean.http.Feature) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) LocalServerChannel(io.netty.channel.local.LocalServerChannel) HttpObject(io.netty.handler.codec.http.HttpObject) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) Subscription(rx.Subscription) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) LocalAddress(io.netty.channel.local.LocalAddress) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) TestChannelCreator(org.jocean.http.client.impl.TestChannelCreator)

Example 7 with TestChannelCreator

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

the class DefaultSignalClientTestCase method testSignalClientWithAttachmentSuccess.

@Test
public void testSignalClientWithAttachmentSuccess() 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 List<FileUpload> uploads = new ArrayList<>();
    final Action2<FullHttpRequest, HttpTrade> requestAndTradeAwareWhenCompleted = new Action2<FullHttpRequest, HttpTrade>() {

        @Override
        public void call(final FullHttpRequest req, final HttpTrade trade) {
            reqMethodReceivedRef.set(req.method());
            reqpathReceivedRef.set(req.uri());
            HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(HTTP_DATA_FACTORY, req);
            // first is signal
            boolean isfirst = true;
            while (decoder.hasNext()) {
                final InterfaceHttpData data = decoder.next();
                if (!isfirst) {
                    if (data instanceof FileUpload) {
                        uploads.add((FileUpload) data);
                    }
                } else {
                    isfirst = false;
                    try {
                        reqbeanReceivedRef.set((TestRequestByPost) JSON.parseObject(Nettys.dumpByteBufAsBytes(((FileUpload) data).content()), TestRequestByPost.class));
                    } catch (Exception e) {
                        LOG.warn("exception when JSON.parseObject, detail: {}", ExceptionUtils.exception2detail(e));
                    }
                }
            }
            trade.outbound(buildResponse(respToSendback, trade.onTerminate()));
        }
    };
    // launch test server for attachment send
    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, new AttachmentBuilder4InMemory());
        signalClient.registerRequestType(TestRequestByPost.class, TestResponse.class, null, buildUri2Addr(testAddr), Feature.ENABLE_LOGGING);
        final AttachmentInMemory[] attachsToSend = new AttachmentInMemory[] { new AttachmentInMemory("1", "text/plain", "11111111111111".getBytes(Charsets.UTF_8)), new AttachmentInMemory("2", "text/plain", "22222222222222222".getBytes(Charsets.UTF_8)), new AttachmentInMemory("3", "text/plain", "333333333333333".getBytes(Charsets.UTF_8)) };
        final TestRequestByPost reqToSend = new TestRequestByPost("1", null);
        final TestResponse respReceived = ((SignalClient) signalClient).interaction().request(reqToSend).feature(attachsToSend).<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);
        final FileUpload[] attachsReceived = uploads.toArray(new FileUpload[0]);
        assertEquals(attachsToSend.length, attachsReceived.length);
        for (int idx = 0; idx < attachsToSend.length; idx++) {
            final AttachmentInMemory inmemory = attachsToSend[idx];
            final FileUpload upload = attachsReceived[idx];
            assertEquals(inmemory.filename, upload.getName());
            assertEquals(inmemory.contentType, upload.getContentType());
            assertTrue(Arrays.equals(inmemory.content(), upload.get()));
        }
        pool.awaitRecycleChannels();
    } finally {
        server.unsubscribe();
    }
}
Also used : FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) ArrayList(java.util.ArrayList) URI(java.net.URI) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) AttachmentInMemory(org.jocean.http.rosa.impl.AttachmentInMemory) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) DefaultSignalClient(org.jocean.http.rosa.impl.DefaultSignalClient) InterfaceHttpData(io.netty.handler.codec.http.multipart.InterfaceHttpData) AttachmentBuilder4InMemory(org.jocean.http.rosa.impl.AttachmentBuilder4InMemory) Subscription(rx.Subscription) FileUpload(io.netty.handler.codec.http.multipart.FileUpload) Action2(rx.functions.Action2) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpPostRequestDecoder(io.netty.handler.codec.http.multipart.HttpPostRequestDecoder) SSLException(javax.net.ssl.SSLException) IOException(java.io.IOException) TestChannelPool(org.jocean.http.client.impl.TestChannelPool) SignalClient(org.jocean.http.rosa.SignalClient) DefaultSignalClient(org.jocean.http.rosa.impl.DefaultSignalClient) HttpMethod(io.netty.handler.codec.http.HttpMethod) TestChannelCreator(org.jocean.http.client.impl.TestChannelCreator) Test(org.junit.Test)

Example 8 with TestChannelCreator

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

the class DefaultSignalClientTestCase method testSignalClientWithoutSignalBeanForPostWithJSONContentAndDecodeResponseAs.

@Test
public void testSignalClientWithoutSignalBeanForPostWithJSONContentAndDecodeResponseAs() 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, Feature.ENABLE_LOGGING);
        final DefaultSignalClient signalClient = new DefaultSignalClient(buildUri2Addr(testAddr), httpclient);
        final TestResponse respReceived = ((SignalClient) signalClient).interaction().request(new Object()).feature(new SignalClient.UsingUri(new URI("http://test")), new SignalClient.UsingPath("/test/raw"), new SignalClient.UsingMethod(POST.class), new SignalClient.JSONContent("{\"code\": \"added\"}"), new SignalClient.DecodeResponseBodyAs(TestResponse.class)).<TestResponse>build().timeout(1, TimeUnit.SECONDS).toBlocking().single();
        assertEquals(HttpMethod.POST, reqMethodReceivedRef.get());
        assertEquals("/test/raw", reqpathReceivedRef.get());
        assertEquals(new TestRequestByPost(null, "added"), reqbeanReceivedRef.get());
        assertEquals(respToSendback, respReceived);
        pool.awaitRecycleChannels();
    } finally {
        server.unsubscribe();
    }
}
Also used : FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) POST(javax.ws.rs.POST) URI(java.net.URI) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) HttpTrade(org.jocean.http.server.HttpServerBuilder.HttpTrade) DefaultSignalClient(org.jocean.http.rosa.impl.DefaultSignalClient) Subscription(rx.Subscription) Action2(rx.functions.Action2) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) TestChannelPool(org.jocean.http.client.impl.TestChannelPool) SignalClient(org.jocean.http.rosa.SignalClient) DefaultSignalClient(org.jocean.http.rosa.impl.DefaultSignalClient) HttpObject(io.netty.handler.codec.http.HttpObject) HttpMethod(io.netty.handler.codec.http.HttpMethod) TestChannelCreator(org.jocean.http.client.impl.TestChannelCreator) Test(org.junit.Test)

Example 9 with TestChannelCreator

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

the class DefaultSignalClientTestCase method testSignalClientOnlySignalForPostWithHeaderParam.

@Test
public void testSignalClientOnlySignalForPostWithHeaderParam() throws Exception {
    final TestResponse respToSendback = new TestResponse("0", "OK");
    final AtomicReference<HttpMethod> reqMethodReceivedRef = new AtomicReference<>();
    final AtomicReference<String> reqpathReceivedRef = new AtomicReference<>();
    final AtomicReference<TestRequestByPostWithHeaderParam> 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());
                final TestRequestByPostWithHeaderParam reqbean = (TestRequestByPostWithHeaderParam) JSON.parseObject(Nettys.dumpByteBufAsBytes(req.content()), TestRequestByPostWithHeaderParam.class);
                reqbean._headerp = req.headers().get("X-P");
                reqbeanReceivedRef.set(reqbean);
            } 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(TestRequestByPostWithHeaderParam.class, TestResponse.class, null, buildUri2Addr(testAddr), Feature.ENABLE_LOGGING);
        final TestRequestByPostWithHeaderParam reqToSend = new TestRequestByPostWithHeaderParam("1", "test");
        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 10 with TestChannelCreator

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

the class DefaultSignalClientTestCase method testSignalClientOnlySignalForGetDuplicateFeatures.

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

        @Override
        public void call(final FullHttpRequest req, final HttpTrade trade) {
            reqMethodReceivedRef.set(req.method());
            final QueryStringDecoder decoder = new QueryStringDecoder(req.uri());
            reqpathReceivedRef.set(decoder.path());
            reqbeanReceivedRef.set(decoder.parameters().get("id").get(0));
            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(TestRequest.class, TestResponse.class, null, buildUri2Addr(testAddr), // duplicate ENABLE_SETURI
        RosaProfiles.ENABLE_SETPATH, Feature.ENABLE_LOGGING);
        final TestRequest reqToSend = new TestRequest("1");
        final TestResponse respReceived = ((SignalClient) signalClient).interaction().request(reqToSend).<TestResponse>build().timeout(1, TimeUnit.SECONDS).toBlocking().single();
        assertEquals(HttpMethod.GET, reqMethodReceivedRef.get());
        assertEquals("/test/simpleRequest", reqpathReceivedRef.get());
        assertEquals(reqToSend.getId(), 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) URI(java.net.URI) DefaultHttpClient(org.jocean.http.client.impl.DefaultHttpClient) QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) 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)

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