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:org.apache.tinkerpop.gremlin.server.handler.NioGremlinBinaryRequestDecoder.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext channelHandlerContext, final ByteBuf byteBuf,
        final List<Object> objects) throws Exception {
    switch (state()) {
    case MESSAGE_LENGTH:
        messageLength = byteBuf.readInt();
        checkpoint(DecoderState.MESSAGE);
    case MESSAGE:
        try {/*from  www .  j a va2 s  . com*/
            final ByteBuf messageFrame = byteBuf.readBytes(messageLength);
            final int contentTypeLength = messageFrame.readByte();
            final ByteBuf contentTypeFrame = messageFrame.readBytes(contentTypeLength);
            final String contentType = contentTypeFrame.toString(CharsetUtil.UTF_8);

            final MessageSerializer serializer = select(contentType, Serializers.DEFAULT_REQUEST_SERIALIZER);

            // it's important to re-initialize these channel attributes as they apply globally to the channel. in
            // other words, the next request to this channel might not come with the same configuration and mixed
            // state can carry through from one request to the next
            channelHandlerContext.channel().attr(StateKey.SESSION).set(null);
            channelHandlerContext.channel().attr(StateKey.SERIALIZER).set(serializer);
            channelHandlerContext.channel().attr(StateKey.USE_BINARY).set(true);

            // subtract the contentTypeLength and the byte that held it from the full message length to
            // figure out how long the rest of the message is
            final int payloadLength = messageLength - 1 - contentTypeLength;
            objects.add(serializer.deserializeRequest(messageFrame.readBytes(payloadLength)));
        } catch (SerializationException se) {
            objects.add(RequestMessage.INVALID);
        }

        checkpoint(DecoderState.MESSAGE_LENGTH);
        break;
    default:
        throw new Error("Invalid message sent to Gremlin Server");
    }
}

From source file:org.apache.tinkerpop.gremlin.server.handler.WsGremlinBinaryRequestDecoder.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext channelHandlerContext, final BinaryWebSocketFrame frame,
        final List<Object> objects) throws Exception {
    final ByteBuf messageBytes = frame.content();
    final byte len = messageBytes.readByte();
    if (len <= 0) {
        objects.add(RequestMessage.INVALID);
        return;/*from  ww w . ja va 2s .c  o m*/
    }

    final ByteBuf contentTypeBytes = channelHandlerContext.alloc().buffer(len);
    try {
        messageBytes.readBytes(contentTypeBytes);
        final String contentType = contentTypeBytes.toString(UTF8);
        final MessageSerializer serializer = select(contentType, Serializers.DEFAULT_REQUEST_SERIALIZER);

        // it's important to re-initialize these channel attributes as they apply globally to the channel. in
        // other words, the next request to this channel might not come with the same configuration and mixed
        // state can carry through from one request to the next
        channelHandlerContext.channel().attr(StateKey.SESSION).set(null);
        channelHandlerContext.channel().attr(StateKey.SERIALIZER).set(serializer);
        channelHandlerContext.channel().attr(StateKey.USE_BINARY).set(true);

        try {
            objects.add(serializer.deserializeRequest(messageBytes.discardReadBytes()));
        } catch (SerializationException se) {
            objects.add(RequestMessage.INVALID);
        }
    } finally {
        contentTypeBytes.release();
    }
}

From source file:org.apache.tinkerpop.gremlin.server.handler.WsGremlinCloseRequestDecoder.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext channelHandlerContext, final CloseWebSocketFrame frame,
        final List<Object> objects) throws Exception {
    final ByteBuf messageBytes = frame.content();
    final byte len = messageBytes.readByte();
    if (len <= 0) {
        objects.add(RequestMessage.INVALID);
        return;/*from  w  w w.jav a 2  s  . co m*/
    }

    final ByteBuf contentTypeBytes = channelHandlerContext.alloc().buffer(len);
    try {
        messageBytes.readBytes(contentTypeBytes);
        final String contentType = contentTypeBytes.toString(UTF8);
        final MessageSerializer serializer = select(contentType, Serializers.DEFAULT_REQUEST_SERIALIZER);

        // it's important to re-initialize these channel attributes as they apply globally to the channel. in
        // other words, the next request to this channel might not come with the same configuration and mixed
        // state can carry through from one request to the next
        channelHandlerContext.channel().attr(StateKey.SESSION).set(null);
        channelHandlerContext.channel().attr(StateKey.SERIALIZER).set(serializer);
        channelHandlerContext.channel().attr(StateKey.USE_BINARY).set(true);

        try {
            objects.add(serializer.deserializeRequest(messageBytes.discardReadBytes()));
        } catch (SerializationException se) {
            objects.add(RequestMessage.INVALID);
        }
    } finally {
        contentTypeBytes.release();
    }
}

From source file:org.asynchttpclient.netty.util.ByteBufUtils.java

License:Open Source License

public static String byteBuf2String(Charset charset, ByteBuf buf) throws CharacterCodingException {
    if (charset == UTF_8 || charset == US_ASCII) {
        return Utf8ByteBufCharsetDecoder.decodeUtf8(buf);
    } else {// www . j a va  2  s  . co  m
        return buf.toString(charset);
    }
}

From source file:org.asynchttpclient.netty.util.Utf8ByteBufCharsetDecoder.java

License:Open Source License

public String decode(ByteBuf buf) throws CharacterCodingException {
    if (buf.isDirect()) {
        return buf.toString(UTF_8);
    }/*from  www. j av a 2  s .co  m*/

    int length = buf.readableBytes();
    ensureCapacity(length);

    if (buf.nioBufferCount() == 1) {
        decodeSingleNioBuffer(buf.internalNioBuffer(buf.readerIndex(), length).duplicate(), length);
    } else {
        decode(buf.nioBuffers(), buf.readableBytes());
    }

    return charBuffer.flip().toString();
}

From source file:org.asynchttpclient.netty.util.Utf8ByteBufCharsetDecoder.java

License:Open Source License

public String decode(ByteBuf... bufs) throws CharacterCodingException {
    if (bufs.length == 1) {
        return decode(bufs[0]);
    }/* ww  w.ja  v a2s  .  c  om*/

    int totalSize = 0;
    int totalNioBuffers = 0;
    boolean direct = false;
    for (ByteBuf buf : bufs) {
        if (buf.isDirect()) {
            direct = true;
            break;
        }
        totalSize += buf.readableBytes();
        totalNioBuffers += buf.nioBufferCount();
    }

    if (direct) {
        ByteBuf wrappedBuffer = Unpooled.wrappedBuffer(bufs);
        try {
            return wrappedBuffer.toString(UTF_8);
        } finally {
            wrappedBuffer.release();
        }

    } else {
        ByteBuffer[] nioBuffers = new ByteBuffer[totalNioBuffers];
        int i = 0;
        for (ByteBuf buf : bufs) {
            for (ByteBuffer nioBuffer : buf.nioBuffers()) {
                nioBuffers[i++] = nioBuffer;
            }
        }

        ensureCapacity(totalSize);
        decode(nioBuffers, totalSize);

        return charBuffer.flip().toString();
    }
}

From source file:org.asynchttpclient.providers.netty.handler.WebSocketProtocol.java

License:Apache License

@Override
public void handle(Channel channel, NettyResponseFuture<?> future, Object e) throws Exception {
    WebSocketUpgradeHandler h = WebSocketUpgradeHandler.class.cast(future.getAsyncHandler());
    Request request = future.getRequest();

    if (e instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) e;
        HttpResponseStatus status = new ResponseStatus(future.getURI(), response, config);
        HttpResponseHeaders responseHeaders = new ResponseHeaders(future.getURI(), response.headers());

        if (handleResponseFiltersReplayRequestAndExit(channel, future, status, responseHeaders)) {
            return;
        }//from  www .  ja  va 2 s.c om

        future.setHttpHeaders(response.headers());
        if (handleRedirectAndExit(request, future, response, channel))
            return;

        boolean validStatus = response.getStatus().equals(SWITCHING_PROTOCOLS);
        boolean validUpgrade = response.headers().get(HttpHeaders.Names.UPGRADE) != null;
        String c = response.headers().get(HttpHeaders.Names.CONNECTION);
        if (c == null) {
            c = response.headers().get(HttpHeaders.Names.CONNECTION.toLowerCase(Locale.ENGLISH));
        }

        boolean validConnection = c != null && c.equalsIgnoreCase(HttpHeaders.Values.UPGRADE);

        status = new ResponseStatus(future.getURI(), response, config);
        final boolean statusReceived = h.onStatusReceived(status) == STATE.UPGRADE;

        if (!statusReceived) {
            try {
                h.onCompleted();
            } finally {
                future.done();
            }
            return;
        }

        final boolean headerOK = h.onHeadersReceived(responseHeaders) == STATE.CONTINUE;
        if (!headerOK || !validStatus || !validUpgrade || !validConnection) {
            channels.abort(future, new IOException("Invalid handshake response"));
            return;
        }

        String accept = response.headers().get(HttpHeaders.Names.SEC_WEBSOCKET_ACCEPT);
        String key = WebSocketUtil.getAcceptKey(
                future.getNettyRequest().getHttpRequest().headers().get(HttpHeaders.Names.SEC_WEBSOCKET_KEY));
        if (accept == null || !accept.equals(key)) {
            channels.abort(future,
                    new IOException(String.format("Invalid challenge. Actual: %s. Expected: %s", accept, key)));
        }

        Channels.upgradePipelineForWebSockets(channel);

        invokeOnSucces(channel, h);
        future.done();

    } else if (e instanceof WebSocketFrame) {

        final WebSocketFrame frame = (WebSocketFrame) e;
        NettyWebSocket webSocket = NettyWebSocket.class.cast(h.onCompleted());
        invokeOnSucces(channel, h);

        if (webSocket != null) {
            if (frame instanceof CloseWebSocketFrame) {
                Channels.setDefaultAttribute(channel, DiscardEvent.INSTANCE);
                CloseWebSocketFrame closeFrame = CloseWebSocketFrame.class.cast(frame);
                webSocket.onClose(closeFrame.statusCode(), closeFrame.reasonText());
            } else {
                ByteBuf buf = frame.content();
                if (buf != null && buf.readableBytes() > 0) {
                    try {
                        NettyResponseBodyPart rp = nettyConfig.getBodyPartFactory().newResponseBodyPart(buf,
                                frame.isFinalFragment());
                        h.onBodyPartReceived(rp);

                        if (frame instanceof BinaryWebSocketFrame) {
                            webSocket.onBinaryFragment(rp.getBodyPartBytes(), frame.isFinalFragment());
                        } else {
                            webSocket.onTextFragment(buf.toString(StandardCharsets.UTF_8),
                                    frame.isFinalFragment());
                        }
                    } finally {
                        buf.release();
                    }
                }
            }
        } else {
            LOGGER.debug("UpgradeHandler returned a null NettyWebSocket ");
        }
    } else if (e instanceof LastHttpContent) {
        // FIXME what to do with this kind of messages?
    } else {
        LOGGER.error("Invalid message {}", e);
    }
}

From source file:org.clitherproject.clither.server.net.packet.Packet.java

License:Open Source License

@SuppressWarnings("deprecation")
public static String readUTF16(ByteBuf in) {
    in = in.order(ByteOrder.BIG_ENDIAN);
    ByteBuf buffer = in.alloc().buffer();
    char chr;//w  ww.ja v a 2  s. c  o  m
    while (in.readableBytes() > 1 && (chr = in.readChar()) != 0) {
        buffer.writeChar(chr);
    }

    return buffer.toString(Charsets.UTF_16LE);
}

From source file:org.cloudfoundry.reactor.routing.v1.tcproutes.EventStreamDecoderChannelHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext context, Object message) throws Exception {
    if (!(message instanceof DefaultHttpContent)) {
        super.channelRead(context, message);
        return;//from   w w  w . ja v  a2s  .  c o  m
    }

    ByteBuf byteBuf = ((DefaultHttpContent) message).content();
    this.characters = this.characters != null ? this.characters + byteBuf.toString(UTF8)
            : byteBuf.toString(UTF8);
    byteBuf.release();

    while (this.position < this.characters.length()) {
        char c = this.characters.charAt(this.position);

        switch (this.stage) {
        case COLON:
            colon(c);
            break;
        case COMMENT:
            comment(c);
            break;
        case CRLF:
            crlf(context, c);
            break;
        case NAME:
            name(c);
            break;
        case VALUE:
            value(c);
            break;
        }
    }

    if (Stage.CRLF == this.stage) {
        crlf(context, '\0');
    }

    if (Stage.NAME == this.stage) {
        reset();
    }
}

From source file:org.dcache.xrootd.security.StringBucket.java

License:Open Source License

public static StringBucket deserialize(BucketType type, ByteBuf buffer) {

    String s = buffer.toString(US_ASCII);
    return new StringBucket(type, s);
}