List of usage examples for io.netty.buffer ByteBuf toString
public abstract String toString(Charset charset);
From source file:io.scalecube.socketio.serialization.PacketDecoder.java
License:Apache License
public static Packet decodePacket(final ByteBuf payload) throws IOException { int payloadSize = payload.readableBytes(); // Decode packet type int typeDelimiterIndex = payload.forEachByte(packetDelimiterFinder); if (typeDelimiterIndex == -1) { return Packet.NULL_INSTANCE; }//from ww w . j a va 2 s .c om ByteBuf typeBytes = payload.slice(0, typeDelimiterIndex); String typeString = typeBytes.toString(CharsetUtil.UTF_8); int typeId = Integer.valueOf(typeString); PacketType type = PacketType.valueOf(typeId); // Skip message id int messageIdDelimiterIndex = payload.forEachByte(typeDelimiterIndex + 1, payloadSize - typeDelimiterIndex - 1, packetDelimiterFinder); if (messageIdDelimiterIndex == -1) { return Packet.NULL_INSTANCE; } // Skip endpoint int endpointDelimiterIndex = payload.forEachByte(messageIdDelimiterIndex + 1, payloadSize - messageIdDelimiterIndex - 1, packetDelimiterFinder); // Create instance of packet Packet packet = new Packet(type); // Decode data boolean messagingType = type == PacketType.MESSAGE || type == PacketType.JSON; if (endpointDelimiterIndex != -1 && messagingType) { int dataLength = payloadSize - endpointDelimiterIndex - 1; if (dataLength > 0) { ByteBuf data = payload.copy(endpointDelimiterIndex + 1, dataLength); packet.setData(data); } } return packet; }
From source file:io.vertx.core.EventLoopGroupTest.java
License:Open Source License
@Test public void testNettyServerUsesContextEventLoop() throws Exception { ContextInternal context = (ContextInternal) vertx.getOrCreateContext(); AtomicReference<Thread> contextThread = new AtomicReference<>(); CountDownLatch latch = new CountDownLatch(1); context.runOnContext(v -> {/* w ww .java2 s . co m*/ contextThread.set(Thread.currentThread()); latch.countDown(); }); awaitLatch(latch); ServerBootstrap bs = new ServerBootstrap(); bs.group(context.nettyEventLoop()); bs.channelFactory(((VertxInternal) vertx).transport().serverChannelFactory(false)); bs.option(ChannelOption.SO_BACKLOG, 100); bs.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(v -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Vertx.currentContext()); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(v -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Vertx.currentContext()); }); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; assertEquals("hello", buf.toString(StandardCharsets.UTF_8)); assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(v -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Vertx.currentContext()); }); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(v -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Vertx.currentContext()); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); }); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { assertSame(contextThread.get(), Thread.currentThread()); context.executeFromIO(v -> { assertSame(contextThread.get(), Thread.currentThread()); assertSame(context, Vertx.currentContext()); testComplete(); }); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { fail(cause.getMessage()); } }); }); } }); ChannelFuture fut = bs.bind("localhost", 1234); try { fut.sync(); vertx.createNetClient(new NetClientOptions()).connect(1234, "localhost", ar -> { assertTrue(ar.succeeded()); NetSocket so = ar.result(); so.write(Buffer.buffer("hello")); }); await(); } finally { fut.channel().close().sync(); } }
From source file:io.vertx.core.http.Http2ServerTest.java
License:Open Source License
@Test public void testGet() throws Exception { String expected = TestUtils.randomAlphaString(1000); AtomicBoolean requestEnded = new AtomicBoolean(); Context ctx = vertx.getOrCreateContext(); server.requestHandler(req -> {/*w w w . j a va 2 s . c om*/ assertOnIOContext(ctx); req.endHandler(v -> { assertOnIOContext(ctx); requestEnded.set(true); }); HttpServerResponse resp = req.response(); assertEquals(HttpMethod.GET, req.method()); assertEquals(DEFAULT_HTTPS_HOST_AND_PORT, req.host()); assertEquals("/", req.path()); assertTrue(req.isSSL()); assertEquals("https", req.scheme()); assertEquals("/", req.uri()); assertEquals("foo_request_value", req.getHeader("Foo_request")); assertEquals("bar_request_value", req.getHeader("bar_request")); assertEquals(2, req.headers().getAll("juu_request").size()); assertEquals("juu_request_value_1", req.headers().getAll("juu_request").get(0)); assertEquals("juu_request_value_2", req.headers().getAll("juu_request").get(1)); assertEquals(Collections.singletonList("cookie_1; cookie_2; cookie_3"), req.headers().getAll("cookie")); resp.putHeader("content-type", "text/plain"); resp.putHeader("Foo_response", "foo_response_value"); resp.putHeader("bar_response", "bar_response_value"); resp.putHeader("juu_response", (List<String>) Arrays.asList("juu_response_value_1", "juu_response_value_2")); resp.end(expected); }); startServer(ctx); TestClient client = new TestClient(); ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { int id = request.nextStreamId(); request.decoder.frameListener(new Http2EventAdapter() { @Override public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception { vertx.runOnContext(v -> { assertEquals(id, streamId); assertEquals("200", headers.status().toString()); assertEquals("text/plain", headers.get("content-type").toString()); assertEquals("foo_response_value", headers.get("foo_response").toString()); assertEquals("bar_response_value", headers.get("bar_response").toString()); assertEquals(2, headers.getAll("juu_response").size()); assertEquals("juu_response_value_1", headers.getAll("juu_response").get(0).toString()); assertEquals("juu_response_value_2", headers.getAll("juu_response").get(1).toString()); assertFalse(endStream); }); } @Override public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception { String actual = data.toString(StandardCharsets.UTF_8); vertx.runOnContext(v -> { assertEquals(id, streamId); assertEquals(expected, actual); assertTrue(endOfStream); testComplete(); }); return super.onDataRead(ctx, streamId, data, padding, endOfStream); } }); Http2Headers headers = GET("/").authority(DEFAULT_HTTPS_HOST_AND_PORT); headers.set("foo_request", "foo_request_value"); headers.set("bar_request", "bar_request_value"); headers.set("juu_request", "juu_request_value_1", "juu_request_value_2"); headers.set("cookie", Arrays.asList("cookie_1", "cookie_2", "cookie_3")); request.encoder.writeHeaders(request.context, id, headers, 0, true, request.context.newPromise()); request.context.flush(); }); fut.sync(); await(); }
From source file:io.vertx.core.http.Http2ServerTest.java
License:Open Source License
private void testStreamWritability(Function<HttpServerRequest, WriteStream<Buffer>> streamProvider) throws Exception { Context ctx = vertx.getOrCreateContext(); String content = TestUtils.randomAlphaString(1024); StringBuilder expected = new StringBuilder(); Future<Void> whenFull = Future.future(); AtomicBoolean drain = new AtomicBoolean(); server.requestHandler(req -> {/*from w w w . j av a 2 s.c om*/ WriteStream<Buffer> stream = streamProvider.apply(req); vertx.setPeriodic(1, timerID -> { if (stream.writeQueueFull()) { stream.drainHandler(v -> { assertOnIOContext(ctx); expected.append("last"); stream.end(Buffer.buffer("last")); }); vertx.cancelTimer(timerID); drain.set(true); whenFull.complete(); } else { expected.append(content); Buffer buf = Buffer.buffer(content); stream.write(buf); } }); }); startServer(ctx); TestClient client = new TestClient(); ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { AtomicInteger toAck = new AtomicInteger(); int id = request.nextStreamId(); Http2ConnectionEncoder encoder = request.encoder; encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise()); request.decoder.frameListener(new Http2FrameAdapter() { StringBuilder received = new StringBuilder(); @Override public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception { received.append(data.toString(StandardCharsets.UTF_8)); int delta = super.onDataRead(ctx, streamId, data, padding, endOfStream); if (endOfStream) { vertx.runOnContext(v -> { assertEquals(expected.toString(), received.toString()); testComplete(); }); return delta; } else { if (drain.get()) { return delta; } else { toAck.getAndAdd(delta); return 0; } } } }); whenFull.setHandler(ar -> { request.context.executor().execute(() -> { try { request.decoder.flowController().consumeBytes(request.connection.stream(id), toAck.intValue()); request.context.flush(); } catch (Http2Exception e) { e.printStackTrace(); fail(e); } }); }); }); fut.sync(); await(); }
From source file:io.vertx.core.http.Http2ServerTest.java
License:Open Source License
private void testPushPromise(Http2Headers requestHeaders, BiConsumer<HttpServerResponse, Handler<AsyncResult<HttpServerResponse>>> pusher, Consumer<Http2Headers> headerChecker) throws Exception { Context ctx = vertx.getOrCreateContext(); server.requestHandler(req -> {// ww w . j av a2 s. c om Handler<AsyncResult<HttpServerResponse>> handler = ar -> { assertSame(ctx, Vertx.currentContext()); assertTrue(ar.succeeded()); HttpServerResponse response = ar.result(); response./*putHeader("content-type", "application/plain").*/end("the_content"); assertIllegalStateException(() -> response.push(HttpMethod.GET, "/wibble2", resp -> { })); }; pusher.accept(req.response(), handler); }); startServer(ctx); TestClient client = new TestClient(); ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { int id = request.nextStreamId(); Http2ConnectionEncoder encoder = request.encoder; encoder.writeHeaders(request.context, id, requestHeaders, 0, true, request.context.newPromise()); Map<Integer, Http2Headers> pushed = new HashMap<>(); request.decoder.frameListener(new Http2FrameAdapter() { @Override public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId, Http2Headers headers, int padding) throws Http2Exception { pushed.put(promisedStreamId, headers); } @Override public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception { int delta = super.onDataRead(ctx, streamId, data, padding, endOfStream); String content = data.toString(StandardCharsets.UTF_8); vertx.runOnContext(v -> { assertEquals(Collections.singleton(streamId), pushed.keySet()); assertEquals("the_content", content); Http2Headers pushedHeaders = pushed.get(streamId); headerChecker.accept(pushedHeaders); testComplete(); }); return delta; } }); }); fut.sync(); await(); }
From source file:io.vertx.core.http.Http2ServerTest.java
License:Open Source License
@Test public void testResponseCompressionDisabled() throws Exception { waitFor(2);/*from ww w . ja v a2 s . c o m*/ String expected = TestUtils.randomAlphaString(1000); server.requestHandler(req -> { req.response().end(expected); }); startServer(); TestClient client = new TestClient(); ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { request.decoder.frameListener(new Http2EventAdapter() { @Override public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception { vertx.runOnContext(v -> { assertEquals(null, headers.get(HttpHeaderNames.CONTENT_ENCODING)); complete(); }); } @Override public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception { String s = data.toString(StandardCharsets.UTF_8); vertx.runOnContext(v -> { assertEquals(expected, s); complete(); }); return super.onDataRead(ctx, streamId, data, padding, endOfStream); } }); int id = request.nextStreamId(); request.encoder.writeHeaders(request.context, id, GET("/").add("accept-encoding", "gzip"), 0, true, request.context.newPromise()); request.context.flush(); }); fut.sync(); await(); }
From source file:io.vertx.core.http.Http2ServerTest.java
License:Open Source License
@Test public void testNetSocketConnect() throws Exception { waitFor(2);//from w w w .j av a2s .co m List<Integer> callbacks = Collections.synchronizedList(new ArrayList<>()); server.requestHandler(req -> { NetSocket socket = req.netSocket(); AtomicInteger status = new AtomicInteger(); socket.handler(buff -> { switch (status.getAndIncrement()) { case 0: assertEquals(Buffer.buffer("some-data"), buff); socket.write(buff, onSuccess(v2 -> callbacks.add(0))); break; case 1: assertEquals(Buffer.buffer("last-data"), buff); break; default: fail(); break; } }); socket.endHandler(v1 -> { assertEquals(2, status.getAndIncrement()); socket.write(Buffer.buffer("last-data"), onSuccess(v2 -> callbacks.add(1))); }); socket.closeHandler(v -> { assertEquals(2, callbacks.size()); assertEquals(Arrays.asList(0, 1), callbacks); complete(); }); }); startServer(); TestClient client = new TestClient(); ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { int id = request.nextStreamId(); request.decoder.frameListener(new Http2EventAdapter() { @Override public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception { vertx.runOnContext(v -> { assertEquals("200", headers.status().toString()); assertFalse(endStream); }); request.encoder.writeData(request.context, id, Buffer.buffer("some-data").getByteBuf(), 0, false, request.context.newPromise()); request.context.flush(); } StringBuilder received = new StringBuilder(); @Override public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception { String s = data.toString(StandardCharsets.UTF_8); received.append(s); if (received.toString().equals("some-data")) { received.setLength(0); vertx.runOnContext(v -> { assertFalse(endOfStream); }); request.encoder.writeData(request.context, id, Buffer.buffer("last-data").getByteBuf(), 0, true, request.context.newPromise()); } else if (endOfStream) { vertx.runOnContext(v -> { assertEquals("last-data", received.toString()); complete(); }); } return data.readableBytes() + padding; } }); request.encoder.writeHeaders(request.context, id, GET("/"), 0, false, request.context.newPromise()); request.context.flush(); }); fut.sync(); await(); }
From source file:io.vertx.core.http.Http2ServerTest.java
License:Open Source License
@Test public void testServerCloseNetSocket() throws Exception { waitFor(2);//w w w. j a v a 2s. c o m final AtomicInteger writeAcks = new AtomicInteger(0); AtomicInteger status = new AtomicInteger(); server.requestHandler(req -> { NetSocket socket = req.netSocket(); socket.handler(buff -> { switch (status.getAndIncrement()) { case 0: assertEquals(Buffer.buffer("some-data"), buff); socket.write(buff, onSuccess(v -> writeAcks.incrementAndGet())); socket.close(); break; case 1: assertEquals(Buffer.buffer("last-data"), buff); break; default: fail(); break; } }); socket.endHandler(v -> { assertEquals(2, status.getAndIncrement()); }); socket.closeHandler(v -> { assertEquals(3, status.getAndIncrement()); complete(); assertEquals(1, writeAcks.get()); }); }); startServer(); TestClient client = new TestClient(); ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> { int id = request.nextStreamId(); request.decoder.frameListener(new Http2EventAdapter() { int count = 0; @Override public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception { int c = count++; vertx.runOnContext(v -> { assertEquals(0, c); }); request.encoder.writeData(request.context, id, Buffer.buffer("some-data").getByteBuf(), 0, false, request.context.newPromise()); request.context.flush(); } StringBuilder received = new StringBuilder(); @Override public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception { String s = data.toString(StandardCharsets.UTF_8); received.append(s); if (endOfStream) { request.encoder.writeData(request.context, id, Buffer.buffer("last-data").getByteBuf(), 0, true, request.context.newPromise()); vertx.runOnContext(v -> { assertEquals("some-data", received.toString()); complete(); }); } return data.readableBytes() + padding; } }); request.encoder.writeHeaders(request.context, id, GET("/"), 0, false, request.context.newPromise()); request.context.flush(); }); fut.sync(); await(); }
From source file:io.vertx.core.http.Http2ServerTest.java
License:Open Source License
@Test public void testHttp1xOrH2CHandlerHttp2Request() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(new TestHttp1xOrH2CHandler()); ByteBuf expected = Unpooled.copiedBuffer(Http1xOrH2CHandler.HTTP_2_PREFACE, StandardCharsets.UTF_8); ch.writeInbound(expected);/*from w ww.j a v a2s .co m*/ assertEquals(1, expected.refCnt()); assertEquals(1, ch.outboundMessages().size()); ByteBuf res = (ByteBuf) ch.outboundMessages().poll(); assertEquals(Http1xOrH2CHandler.HTTP_2_PREFACE, res.toString(StandardCharsets.UTF_8)); assertNull(ch.pipeline().get(TestHttp1xOrH2CHandler.class)); }
From source file:io.vertx.core.http.Http2ServerTest.java
License:Open Source License
@Test public void testHttp1xOrH2CHandlerFragmentedHttp2Request() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(new TestHttp1xOrH2CHandler()); ByteBuf expected = Unpooled.copiedBuffer(Http1xOrH2CHandler.HTTP_2_PREFACE, StandardCharsets.UTF_8); ByteBuf buff = expected.copy(0, 1);/*from w ww. j a v a2 s.com*/ ch.writeInbound(buff); assertEquals(0, buff.refCnt()); assertEquals(0, ch.outboundMessages().size()); buff = expected.copy(1, expected.readableBytes() - 1); ch.writeInbound(buff); assertEquals(0, buff.refCnt()); assertEquals(1, ch.outboundMessages().size()); ByteBuf res = (ByteBuf) ch.outboundMessages().poll(); assertEquals(1, res.refCnt()); assertEquals(Http1xOrH2CHandler.HTTP_2_PREFACE, res.toString(StandardCharsets.UTF_8)); assertNull(ch.pipeline().get(TestHttp1xOrH2CHandler.class)); }