use of org.jocean.http.server.HttpServerBuilder 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);
}
}
use of org.jocean.http.server.HttpServerBuilder in project jocean-http by isdom.
the class HttpServerForCloopen method main.
public static void main(final String[] args) throws Exception {
@SuppressWarnings("resource") final HttpServerBuilder server = new DefaultHttpServerBuilder();
@SuppressWarnings("unused") final Subscription subscription = server.defineServer(new InetSocketAddress("0.0.0.0", 8888)).subscribe(new Action1<HttpTrade>() {
@Override
public void call(final HttpTrade trade) {
// final HttpMessageHolder holder = new HttpMessageHolder();
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 byte[] bytes = Nettys.dumpByteBufAsBytes(fullreq.content());
final String reqcontent = bytes.length > 0 ? new String(bytes, Charsets.UTF_8) : "empty";
LOG.debug("receive HttpRequest: {}\ncontent:\n{}", fullreq, reqcontent);
} catch (Exception e) {
LOG.warn("exception when dump http req content, detail:{}", ExceptionUtils.exception2detail(e));
}
byte[] bytes = new String("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response><statuscode>000000</statuscode></Response>").getBytes(Charsets.UTF_8);
final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(bytes));
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
return response;
}
}));
}
});
}
use of org.jocean.http.server.HttpServerBuilder 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();
}
}
Aggregations