Example usage for io.netty.buffer ByteBuf toString

List of usage examples for io.netty.buffer ByteBuf toString

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf toString.

Prototype

public abstract String toString(Charset charset);

Source Link

Document

Decodes this buffer's readable bytes into a string with the specified character set name.

Usage

From source file:io.vertx.core.net.NetTest.java

License:Open Source License

private void testNetClientInternal_(HttpServerOptions options, boolean expectSSL) throws Exception {
    waitFor(2);//from w  w w  .j av a 2s  . c  o  m
    HttpServer server = vertx.createHttpServer(options);
    server.requestHandler(req -> {
        req.response().end("Hello World");
    });
    CountDownLatch latch = new CountDownLatch(1);
    server.listen(onSuccess(v -> {
        latch.countDown();
    }));
    awaitLatch(latch);
    client.connect(1234, "localhost", onSuccess(so -> {
        NetSocketInternal soInt = (NetSocketInternal) so;
        assertEquals(expectSSL, soInt.isSsl());
        ChannelHandlerContext chctx = soInt.channelHandlerContext();
        ChannelPipeline pipeline = chctx.pipeline();
        pipeline.addBefore("handler", "http", new HttpClientCodec());
        AtomicInteger status = new AtomicInteger();
        soInt.handler(buff -> fail());
        soInt.messageHandler(obj -> {
            switch (status.getAndIncrement()) {
            case 0:
                assertTrue(obj instanceof HttpResponse);
                HttpResponse resp = (HttpResponse) obj;
                assertEquals(200, resp.status().code());
                break;
            case 1:
                assertTrue(obj instanceof LastHttpContent);
                ByteBuf content = ((LastHttpContent) obj).content();
                assertEquals(!expectSSL, content.isDirect());
                assertEquals(1, content.refCnt());
                String val = content.toString(StandardCharsets.UTF_8);
                assertTrue(content.release());
                assertEquals("Hello World", val);
                complete();
                break;
            default:
                fail();
            }
        });
        soInt.writeMessage(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/somepath"),
                onSuccess(v -> complete()));
    }));
    await();
}

From source file:io.vertx.proton.impl.ProtonWritableBufferImplTest.java

License:Apache License

@Test
public void testPutString() {
    String ascii = new String("ASCII");

    ByteBuf buffer = Unpooled.buffer(1024);
    ProtonWritableBufferImpl writable = new ProtonWritableBufferImpl(buffer);

    assertEquals(0, writable.position());
    writable.put(ascii);//from ww  w. j a  v  a2s.  c o m
    assertEquals(ascii.length(), writable.position());

    ByteBuf written = writable.getBuffer();
    assertEquals(ascii, written.toString(StandardCharsets.UTF_8));
}

From source file:io.vertx.test.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 -> {/*from   www  . ja v  a 2  s  .co  m*/
        contextThread.set(Thread.currentThread());
        latch.countDown();
    });
    awaitLatch(latch);
    ServerBootstrap bs = new ServerBootstrap();
    bs.group(context.nettyEventLoop());
    bs.channel(NioServerSocketChannel.class);
    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(() -> {
                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(() -> {
                            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(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                        });
                    }

                    @Override
                    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                        assertSame(contextThread.get(), Thread.currentThread());
                        context.executeFromIO(() -> {
                            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(() -> {
                            assertSame(contextThread.get(), Thread.currentThread());
                            assertSame(context, Vertx.currentContext());
                            testComplete();
                        });
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        fail(cause.getMessage());
                    }
                });
            });
        }
    });
    bs.bind("localhost", 1234).sync();
    vertx.createNetClient(new NetClientOptions()).connect(1234, "localhost", ar -> {
        assertTrue(ar.succeeded());
        NetSocket so = ar.result();
        so.write(Buffer.buffer("hello"));
    });
    await();
}

From source file:io.vertx.test.core.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 -> {/*  ww w .  j a  va 2  s. com*/
        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());
        assertEquals(DEFAULT_HTTPS_HOST_AND_PORT, req.getHeader(":authority"));
        assertTrue(req.isSSL());
        assertEquals("https", req.getHeader(":scheme"));
        assertEquals("/", req.getHeader(":path"));
        assertEquals("GET", req.getHeader(":method"));
        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.test.core.Http2ServerTest.java

License:Open Source License

@Test
public void testNetSocketConnect() throws Exception {
    waitFor(2);//  w ww . j a va 2 s . c o  m
    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);
                break;
            case 1:
                assertEquals(Buffer.buffer("last-data"), buff);
                break;
            default:
                fail();
                break;
            }
        });
        socket.endHandler(v -> {
            assertEquals(2, status.getAndIncrement());
            socket.write(Buffer.buffer("last-data"));
        });
        socket.closeHandler(v -> {
            assertEquals(3, status.getAndIncrement());
            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.test.core.Http2ServerTest.java

License:Open Source License

@Test
public void testServerCloseNetSocket() throws Exception {
    waitFor(2);/*w ww. jav a2  s.  co m*/
    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);
                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();
        });
    });

    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:itlab.teleport.HttpServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws SQLException, IOException {
    if (msg instanceof FullHttpRequest) {
        HttpRequest req = (HttpRequest) msg;
        final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false),
                req);/*from   ww w. j  a  v a2s.  c  om*/

        List<InterfaceHttpData> data = decoder.getBodyHttpDatas();
        for (InterfaceHttpData entry : data) {
            Attribute attr = (Attribute) entry;
            try {
                System.out.println(String.format("name: %s value: %s", attr.getName(), attr.getValue()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    if (msg instanceof HttpContent) {
        String json_input = "";

        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            json_input = content.toString(CharsetUtil.UTF_8);
            buf.append("CONTENT: ");
            buf.append(content.toString(CharsetUtil.UTF_8));
            buf.append("\r\n");
        }

        if (msg instanceof LastHttpContent) {
            buf.append("END OF CONTENT\r\n");

            LastHttpContent trailer = (LastHttpContent) msg;
            if (!trailer.trailingHeaders().isEmpty()) {
                buf.append("\r\n");
                for (CharSequence name : trailer.trailingHeaders().names()) {
                    for (CharSequence value : trailer.trailingHeaders().getAll(name)) {
                        buf.append("TRAILING HEADER: ");
                        buf.append(name).append(" = ").append(value).append("\r\n");
                    }
                }
                buf.append("\r\n");
            }
            System.out.println(buf);

            try {
                Statement st = BD_Connect.c.createStatement();// ?
                ResultSet rs = st.executeQuery("Select 1");
            } catch (Exception e) {
                new BD_Connect().BD_Connection_open(); //   
            }

            String json_output = new JSON_Handler().Parse_JSON(json_input); //   JSON ?

            ByteBuf response_content = Unpooled.wrappedBuffer(json_output.getBytes(CharsetUtil.UTF_8));
            HttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, OK, response_content);

            ctx.writeAndFlush(resp);
            ctx.close();
            new BD_Connect().BD_Connection_close(); //  ?? ? 

        }
    }
}

From source file:jazmin.server.im.mobile.MobileDecoder.java

License:Open Source License

@Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    ByteBuf decoded = (ByteBuf) super.decode(ctx, in);
    if (decoded == null) {
        return decoded;
    }//w ww  .j a  va  2s  .co  m
    String s = decoded.toString(charset);
    if (logger.isDebugEnabled()) {
        logger.debug("\ndecode message--------------------------------------\n" + DumpUtil.formatJSON(s));
    }
    IMRequestMessage reqMessage = new IMRequestMessage();
    reqMessage.isBadRequest = false;
    reqMessage.rawData = s.getBytes(charset);
    JSONObject reqObj = JSON.parseObject(s);
    reqMessage.mobileId = reqObj.getString("msgType");
    networkTrafficStat.inBound(s.getBytes().length);
    return (reqMessage);
}

From source file:jazmin.server.msg.codec.json.JSONDecoder.java

License:Open Source License

@Override
protected final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    ByteBuf decoded = decode(ctx, in);
    if (decoded == null) {
        return;//from   w  w  w .  ja v  a 2 s .c  o m
    }
    String s = decoded.toString(charset);
    RequestMessage reqMessage = JSONRequestParser.createRequestMessage(s);
    if (logger.isDebugEnabled()) {
        logger.debug("\ndecode message--------------------------------------\n" + DumpUtil.formatJSON(s));
    }
    networkTrafficStat.inBound(s.getBytes().length);
    out.add(reqMessage);
}

From source file:jj.resource.Sha1Resource.java

License:Apache License

@Inject
Sha1Resource(final Dependencies dependencies, final Path path, final Sha1ResourceTarget target)
        throws IOException {
    super(dependencies);

    // 3 possibilities
    // either there is no file at path, so we read in our target bytes to make one
    // or there is a file, but it's out of date, so we read in our target bytes and make a new one
    // or it's all good and we use it

    // 59 is the maximum size of the contents as described above.
    ByteBuf byteBuffer = Unpooled.buffer(59, 59);
    String sha = null;/*from  w w  w  .  j av  a2s  .  c  o m*/
    long size = -1;

    if (Files.exists(path)) {
        byteBuffer.writeBytes(Files.readAllBytes(path));
        Matcher matcher = FORMAT.matcher(byteBuffer.toString(US_ASCII));
        if (!matcher.matches()) {
            throw new AssertionError("someone messed with the contents of Sha1Resource file");
        }
        sha = matcher.group(1);
        size = Long.parseLong(matcher.group(2));
    } else {
        sha = SHA1Helper.keyFor(target.resource.path());
        size = target.resource.size();

        Files.write(path, (sha + size).getBytes(US_ASCII));
    }

    // yuckerdo! but java makes this hard to extract
    // TODO - make this nicer. you have a test to validate it and everything
    if (size != target.resource.size()) {
        sha = SHA1Helper.keyFor(target.resource.path());
        size = target.resource.size();

        Files.write(path, (sha + size).getBytes(US_ASCII));
    }

    representedSha = sha;
    representedFileSize = size;

    sha1 = SHA1Helper.keyFor(representedSha, String.valueOf(size));

    target.resource.addDependent(this);
}