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:com.zz.learning.netty5.chap10.xml.codec.AbstractHttpXmlDecoder.java

License:Apache License

protected Object decode0(ChannelHandlerContext arg0, ByteBuf body) throws Exception {
    /*// w ww.  j  a va  2 s  . c om
     * factory = BindingDirectory.getFactory(clazz); String content =
     * body.toString(UTF_8); if (isPrint)
     * System.out.println("The body is : " + content); reader = new
     * StringReader(content); IUnmarshallingContext uctx =
     * factory.createUnmarshallingContext(); Object result =
     * uctx.unmarshalDocument(reader); reader.close(); reader = null; return
     * result;
     */

    /*        String orderStr = body.toString(UTF_8);
            
            System.out.println("The body is : " + orderStr);
            return stream.fromXML(orderStr);*/
    String s = body.toString(UTF_8);
    if (isPrint) {
        System.out.println(s);
    }
    Object o2 = JSON.parseObject(s, clazz);
    return o2;
}

From source file:de.jackwhite20.japs.shared.pipeline.handler.JSONObjectDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> out)
        throws Exception {

    byteBuf.readInt();//from   w w  w .j  a v a  2s.c  o m
    out.add(new JSONObject(byteBuf.toString(CharsetUtil.UTF_8)));
}

From source file:deathcap.wsmc.web.HTTPHandler.java

License:Apache License

public void httpRequest(ChannelHandlerContext context, FullHttpRequest request) throws IOException {
    if (!request.getDecoderResult().isSuccess()) {
        sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;//w  w w . j a  va  2 s . co  m
    }
    if (request.getUri().equals("/server")) {
        context.fireChannelRead(request);
        return;
    }

    if ((request.getMethod() == OPTIONS || request.getMethod() == HEAD) && request.getUri().equals("/chunk")) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
        response.headers().add("Access-Control-Allow-Origin", "*");
        response.headers().add("Access-Control-Allow-Methods", "POST");
        if (request.getMethod() == OPTIONS) {
            response.headers().add("Access-Control-Allow-Headers", "origin, content-type, accept");
        }
        sendHttpResponse(context, request, response);
    }

    if (request.getMethod() != GET) {
        sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    // TODO: send browserified page
    if (request.getUri().equals("/")) {
        request.setUri("/index.html");
    }

    InputStream stream = null;
    /*
    if (request.getUri().startsWith("/resources/")) {
    File file = new File(
            plugin.getResourceDir(),
            request.getUri().substring("/resources/".length())
    );
    stream = new FileInputStream(file);
    } else {
    */
    stream = this.getClass().getClassLoader().getResourceAsStream("www" + request.getUri());
    if (stream == null) {
        sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND));
        return;
    }
    ByteBufOutputStream out = new ByteBufOutputStream(Unpooled.buffer());
    copyStream(stream, out);
    stream.close();
    out.close();

    ByteBuf buffer = out.buffer();
    if (request.getUri().equals("/index.html")) {
        String page = buffer.toString(CharsetUtil.UTF_8);
        page = page.replaceAll("%SERVERPORT%", Integer.toString(this.port));
        buffer.release();
        buffer = Unpooled.wrappedBuffer(page.getBytes(CharsetUtil.UTF_8));
    }

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buffer);
    if (request.getUri().startsWith("/resources/")) {
        response.headers().add("Access-Control-Allow-Origin", "*");
    }

    String ext = request.getUri().substring(request.getUri().lastIndexOf('.') + 1);
    String type = mimeTypes.containsKey(ext) ? mimeTypes.get(ext) : "text/plain";
    if (type.startsWith("text/")) {
        type += "; charset=UTF-8";
    }
    response.headers().set(CONTENT_TYPE, type);
    setContentLength(response, response.content().readableBytes());
    sendHttpResponse(context, request, response);

}

From source file:discord4j.gateway.DefaultGatewayClient.java

License:Open Source License

private void trace(Logger log, ByteBuf buf) {
    if (log.isTraceEnabled()) {
        log.trace(buf.toString(StandardCharsets.UTF_8).replaceAll("(\"token\": ?\")([A-Za-z0-9.-]*)(\")",
                "$1hunter2$3"));
    }// w ww .  java 2 s. c  o m
}

From source file:discord4j.gateway.payload.JacksonPayloadReader.java

License:Open Source License

@Override
public Mono<GatewayPayload<?>> read(ByteBuf payload) {
    return Mono.create(sink -> {
        try {/* w  w  w  . ja v a  2s . c  o  m*/
            GatewayPayload<?> value = mapper.readValue(payload.array(), new TypeReference<GatewayPayload<?>>() {
            });
            sink.success(value);
        } catch (IOException | IllegalArgumentException e) {
            if (lenient) {
                // if eof input - just ignore
                if (payload.readableBytes() > 0) {
                    log.warn("Error while decoding JSON ({} bytes): {}", payload.readableBytes(),
                            payload.toString(StandardCharsets.UTF_8), e);
                }
                sink.success();
            } else {
                sink.error(Exceptions.propagate(e));
            }
        }
    });
}

From source file:divconq.http.multipart.HttpPostMultipartRequestDecoder.java

License:Apache License

/**
 * Read one line up to the CRLF or LF/*from   ww w. ja v a  2  s  .  c  o m*/
 *
 * @return the String from one line
 * @throws NotEnoughDataDecoderException
 *             Need more chunks and reset the readerInder to the previous
 *             value
 */
private String readLineStandard() {
    int readerIndex = undecodedChunk.readerIndex();
    try {
        ByteBuf line = buffer(64);

        while (undecodedChunk.isReadable()) {
            byte nextByte = undecodedChunk.readByte();
            if (nextByte == HttpConstants.CR) {
                nextByte = undecodedChunk.readByte();
                if (nextByte == HttpConstants.LF) {
                    return line.toString(charset);
                }
            } else if (nextByte == HttpConstants.LF) {
                return line.toString(charset);
            } else {
                line.writeByte(nextByte);
            }
        }
    } catch (IndexOutOfBoundsException e) {
        undecodedChunk.readerIndex(readerIndex);
        throw new NotEnoughDataDecoderException(e);
    }
    undecodedChunk.readerIndex(readerIndex);
    throw new NotEnoughDataDecoderException();
}

From source file:divconq.http.multipart.HttpPostMultipartRequestDecoder.java

License:Apache License

/**
 * Read one line up to the CRLF or LF/*  w w  w  .j  ava2s . c  o  m*/
 *
 * @return the String from one line
 * @throws NotEnoughDataDecoderException
 *             Need more chunks and reset the readerInder to the previous
 *             value
 */
private String readLine() {
    SeekAheadOptimize sao;
    try {
        sao = new SeekAheadOptimize(undecodedChunk);
    } catch (SeekAheadNoBackArrayException e1) {
        return readLineStandard();
    }
    int readerIndex = undecodedChunk.readerIndex();
    try {
        ByteBuf line = buffer(64);

        while (sao.pos < sao.limit) {
            byte nextByte = sao.bytes[sao.pos++];
            if (nextByte == HttpConstants.CR) {
                if (sao.pos < sao.limit) {
                    nextByte = sao.bytes[sao.pos++];
                    if (nextByte == HttpConstants.LF) {
                        sao.setReadPosition(0);
                        return line.toString(charset);
                    }
                } else {
                    line.writeByte(nextByte);
                }
            } else if (nextByte == HttpConstants.LF) {
                sao.setReadPosition(0);
                return line.toString(charset);
            } else {
                line.writeByte(nextByte);
            }
        }
    } catch (IndexOutOfBoundsException e) {
        undecodedChunk.readerIndex(readerIndex);
        throw new NotEnoughDataDecoderException(e);
    }
    undecodedChunk.readerIndex(readerIndex);
    throw new NotEnoughDataDecoderException();
}

From source file:divconq.http.multipart.InternalAttribute.java

License:Apache License

@Override
public String toString() {
    StringBuilder result = new StringBuilder();
    for (ByteBuf elt : value) {
        result.append(elt.toString(charset));
    }//w w w .j ava  2 s . c o m
    return result.toString();
}

From source file:edumsg.netty.EduMsgNettyServerHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (correlationId == 0L)
        correlationId = System.currentTimeMillis();
    System.out.println(correlationId + "-");

    //        System.out.println("CH:" + ctx.channel().toString());

    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;
        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);/* w w w .  j  a  va  2 s  . c  o  m*/
        }

    }
    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;
        ByteBuf content = httpContent.content();
        //            System.out.println("req " + content.toString(CharsetUtil.UTF_8));
        setRequestBody(content.toString(CharsetUtil.UTF_8));
    }
    if (msg instanceof LastHttpContent) {
        LastHttpContent trailer = (LastHttpContent) msg;
        //            ByteBuf content = trailer.content();
        //            System.out.println("ss " + content.toString(CharsetUtil.UTF_8));
        writeresponse(trailer, ctx);
    }
}

From source file:etcd.client.HttpClientTest.java

License:Open Source License

@Test
public void httpClient() throws Exception {
    final ServerList serverList = new ServerList();
    serverList.addServer(URI.create("http://localhost:2001"), true);
    final HttpClient httpClient = new HttpClient(new NioEventLoopGroup(), Runnable::run, serverList, false);
    final CountDownLatch latch = new CountDownLatch(1);
    httpClient.send(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/v2/keys/"),
            (response) -> {//from  w  w w .j  a  v  a  2  s.c  o  m
                final DefaultFullHttpResponse httpResponse = response.getHttpResponse();
                final ByteBuf contentBuffer = httpResponse.content();
                System.out.println(contentBuffer.toString(Charset.defaultCharset()));
                latch.countDown();
            });
    assertTrue(latch.await(500, TimeUnit.MILLISECONDS), "Failed to get valid response from server.");
}