Example usage for io.netty.util CharsetUtil UTF_8

List of usage examples for io.netty.util CharsetUtil UTF_8

Introduction

In this page you can find the example usage for io.netty.util CharsetUtil UTF_8.

Prototype

Charset UTF_8

To view the source code for io.netty.util CharsetUtil UTF_8.

Click Source Link

Document

8-bit UTF (UCS Transformation Format)

Usage

From source file:cloudeventbus.codec.Decoder.java

License:Open Source License

@Override
public Frame decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    in.markReaderIndex();/*from   w w  w.j  a  v a2  s.c  o m*/
    final int frameLength = indexOf(in, Codec.DELIMITER);
    // Frame hasn't been fully read yet.
    if (frameLength < 0) {
        if (in.readableBytes() > maxMessageSize) {
            throw new TooLongFrameException("Frame exceeds maximum size");
        }
        in.resetReaderIndex();
        return null;
    }
    // Empty frame, discard and continue decoding
    if (frameLength == 0) {
        in.skipBytes(Codec.DELIMITER.length);
        return decode(ctx, in);
    }
    if (frameLength > maxMessageSize) {
        throw new TooLongFrameException("Frame exceeds maximum size");
    }
    final String command = in.readBytes(frameLength).toString(CharsetUtil.UTF_8);
    in.skipBytes(Codec.DELIMITER.length);
    final String[] parts = command.split("\\s+");
    final char frameTypeChar = parts[0].charAt(0);
    final FrameType frameType = FrameType.getFrameType(frameTypeChar);
    if (frameType == null) {
        throw new DecodingException("Invalid frame type " + frameTypeChar);
    }
    LOGGER.debug("Decoding frame of type {}", frameType);
    final int argumentsLength = parts.length - 1;
    switch (frameType) {
    case AUTH_RESPONSE:
        assertArgumentsLength(3, argumentsLength, "authentication response");
        final CertificateChain certificates = new CertificateChain();
        final byte[] rawCertificates = Base64.decodeBase64(parts[1].getBytes());
        CertificateStoreLoader.load(new ByteArrayInputStream(rawCertificates), certificates);
        final byte[] salt = Base64.decodeBase64(parts[2]);
        final byte[] digitalSignature = Base64.decodeBase64(parts[3]);
        return new AuthenticationResponseFrame(certificates, salt, digitalSignature);
    case AUTHENTICATE:
        assertArgumentsLength(1, argumentsLength, "authentication request");
        final byte[] challenge = Base64.decodeBase64(parts[1]);
        return new AuthenticationRequestFrame(challenge);
    case ERROR:
        if (parts.length == 0) {
            throw new DecodingException("Error is missing error code");
        }
        final Integer errorNumber = Integer.valueOf(parts[1]);
        final ErrorFrame.Code errorCode = ErrorFrame.Code.lookupCode(errorNumber);
        int messageIndex = 1;
        messageIndex = skipWhiteSpace(messageIndex, command);
        while (messageIndex < command.length() && Character.isDigit(command.charAt(messageIndex))) {
            messageIndex++;
        }
        messageIndex = skipWhiteSpace(messageIndex, command);
        final String errorMessage = command.substring(messageIndex).trim();
        if (errorMessage.length() > 0) {
            return new ErrorFrame(errorCode, errorMessage);
        } else {
            return new ErrorFrame(errorCode);
        }
    case GREETING:
        assertArgumentsLength(3, argumentsLength, "greeting");
        final int version = Integer.valueOf(parts[1]);
        final String agent = parts[2];
        final long id = Long.valueOf(parts[3]);
        return new GreetingFrame(version, agent, id);
    case PING:
        return PingFrame.PING;
    case PONG:
        return PongFrame.PONG;
    case PUBLISH:
        if (argumentsLength < 2 || argumentsLength > 3) {
            throw new DecodingException(
                    "Expected message frame to have 2 or 3 arguments. It has " + argumentsLength + ".");
        }
        final String messageSubject = parts[1];
        final String replySubject;
        final Integer messageLength;
        if (parts.length == 3) {
            replySubject = null;
            messageLength = Integer.valueOf(parts[2]);
        } else {
            replySubject = parts[2];
            messageLength = Integer.valueOf(parts[3]);
        }
        if (in.readableBytes() < messageLength + Codec.DELIMITER.length) {
            // If we haven't received the entire message body (plus the CRLF), wait until it arrives.
            in.resetReaderIndex();
            return null;
        }
        final ByteBuf messageBytes = in.readBytes(messageLength);
        final String messageBody = new String(messageBytes.array(), CharsetUtil.UTF_8);
        in.skipBytes(Codec.DELIMITER.length); // Ignore the CRLF after the message body.
        return new PublishFrame(new Subject(messageSubject),
                replySubject == null ? null : new Subject(replySubject), messageBody);
    case SERVER_READY:
        return ServerReadyFrame.SERVER_READY;
    case SUBSCRIBE:
        assertArgumentsLength(1, argumentsLength, "subscribe");
        return new SubscribeFrame(new Subject(parts[1]));
    case UNSUBSCRIBE:
        assertArgumentsLength(1, argumentsLength, "unsubscribe");
        return new UnsubscribeFrame(new Subject(parts[1]));
    default:
        throw new DecodingException("Unknown frame type " + frameType);
    }
}

From source file:cloudeventbus.codec.Encoder.java

License:Open Source License

@Override
public void encode(ChannelHandlerContext ctx, Frame frame, ByteBuf out) throws Exception {
    LOGGER.debug("Encoding frame {}", frame);
    switch (frame.getFrameType()) {
    case AUTHENTICATE:
        final AuthenticationRequestFrame authenticationRequestFrame = (AuthenticationRequestFrame) frame;
        out.writeByte(FrameType.AUTHENTICATE.getOpcode());
        out.writeByte(' ');
        final String challenge = Base64.encodeBase64String(authenticationRequestFrame.getChallenge());
        writeString(out, challenge);/*w  w w .j  a v  a  2  s .  c om*/
        break;
    case AUTH_RESPONSE:
        final AuthenticationResponseFrame authenticationResponseFrame = (AuthenticationResponseFrame) frame;
        out.writeByte(FrameType.AUTH_RESPONSE.getOpcode());
        out.writeByte(' ');

        // Write certificate chain
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final OutputStream base64Out = new Base64OutputStream(outputStream, true, Integer.MAX_VALUE,
                new byte[0]);
        CertificateStoreLoader.store(base64Out, authenticationResponseFrame.getCertificates());
        out.writeBytes(outputStream.toByteArray());
        out.writeByte(' ');

        // Write salt
        final byte[] encodedSalt = Base64.encodeBase64(authenticationResponseFrame.getSalt());
        out.writeBytes(encodedSalt);
        out.writeByte(' ');

        // Write signature
        final byte[] encodedDigitalSignature = Base64
                .encodeBase64(authenticationResponseFrame.getDigitalSignature());
        out.writeBytes(encodedDigitalSignature);
        break;
    case ERROR:
        final ErrorFrame errorFrame = (ErrorFrame) frame;
        out.writeByte(FrameType.ERROR.getOpcode());
        out.writeByte(' ');
        writeString(out, Integer.toString(errorFrame.getCode().getErrorNumber()));
        if (errorFrame.getMessage() != null) {
            out.writeByte(' ');
            writeString(out, errorFrame.getMessage());
        }
        break;
    case GREETING:
        final GreetingFrame greetingFrame = (GreetingFrame) frame;
        out.writeByte(FrameType.GREETING.getOpcode());
        out.writeByte(' ');
        writeString(out, Integer.toString(greetingFrame.getVersion()));
        out.writeByte(' ');
        writeString(out, greetingFrame.getAgent());
        out.writeByte(' ');
        writeString(out, Long.toString(greetingFrame.getId()));
        break;
    case PING:
        out.writeByte(FrameType.PING.getOpcode());
        break;
    case PONG:
        out.writeByte(FrameType.PONG.getOpcode());
        break;
    case PUBLISH:
        final PublishFrame publishFrame = (PublishFrame) frame;
        out.writeByte(FrameType.PUBLISH.getOpcode());
        out.writeByte(' ');
        writeString(out, publishFrame.getSubject().toString());
        if (publishFrame.getReplySubject() != null) {
            out.writeByte(' ');
            writeString(out, publishFrame.getReplySubject().toString());
        }
        out.writeByte(' ');
        final ByteBuf body = Unpooled.wrappedBuffer(publishFrame.getBody().getBytes(CharsetUtil.UTF_8));
        writeString(out, Integer.toString(body.readableBytes()));
        out.writeBytes(Codec.DELIMITER);
        out.writeBytes(body);
        break;
    case SERVER_READY:
        out.writeByte(FrameType.SERVER_READY.getOpcode());
        break;
    case SUBSCRIBE:
        final SubscribeFrame subscribeFrame = (SubscribeFrame) frame;
        out.writeByte(FrameType.SUBSCRIBE.getOpcode());
        out.writeByte(' ');
        writeString(out, subscribeFrame.getSubject().toString());
        break;
    case UNSUBSCRIBE:
        final UnsubscribeFrame unsubscribeFrame = (UnsubscribeFrame) frame;
        out.writeByte(FrameType.UNSUBSCRIBE.getOpcode());
        out.writeByte(' ');
        writeString(out, unsubscribeFrame.getSubject().toString());
        break;
    default:
        throw new EncodingException("Don't know how to encode message of type " + frame.getClass().getName());
    }
    out.writeBytes(Codec.DELIMITER);
}

From source file:cloudeventbus.codec.Encoder.java

License:Open Source License

private void writeString(ByteBuf out, String string) {
    out.writeBytes(string.getBytes(CharsetUtil.UTF_8));
}

From source file:cn.dennishucd.nettyhttpserver.HttpServerHandler.java

License:Apache License

@SuppressWarnings("deprecation")
@Override/*from  ww  w  .j  a  va 2  s.  c  o m*/
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        request = (HttpRequest) msg;

        if (HttpUtil.is100ContinueExpected(request)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }

        if (!request.uri().equalsIgnoreCase(URL)) {
            sendError(ctx, NOT_FOUND);

            return;
        }
    }

    if (msg instanceof HttpContent) {
        HttpContent content = (HttpContent) msg;
        ByteBuf buf = content.content();
        UserToken ut = CTools.JSONStr2Object(buf.toString(io.netty.util.CharsetUtil.UTF_8), UserToken.class);

        logger.info("request body: " + buf.toString(io.netty.util.CharsetUtil.UTF_8));
        buf.release();

        boolean keepAlive = HttpUtil.isKeepAlive(request);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
                Unpooled.wrappedBuffer(CONTENT.getBytes()));
        response.headers().set(CONTENT_TYPE, "application/json");
        response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

        logger.info("response body: " + CONTENT);

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, KEEP_ALIVE);
            ctx.write(response);
        }

    } else {
        ctx.fireChannelRead(msg);
    }
}

From source file:cn.dennishucd.nettyhttpserver.HttpServerHandler.java

License:Apache License

private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status,
            Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");

    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:cn.easyplay.proxy.WebSocketClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ctx.channel(), (FullHttpResponse) msg);
        LOGGER.debug("WebSocket Client connected!");
        handshakeFuture.setSuccess();/*w w w.  j av a  2  s .c om*/
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status()
                + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        // frame
        telnetChannel.writeAndFlush(textFrame.text());
        LOGGER.debug("WebSocket Client received message: " + textFrame.text());
    } else if (frame instanceof PongWebSocketFrame) {
        LOGGER.debug("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
        LOGGER.debug("WebSocket Client received closing");
        ctx.close();
        telnetChannel.close();
    }
}

From source file:cn.jpush.api.common.connection.HttpResponseHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    Integer streamId = msg.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        System.err.println("HttpResponseHandler unexpected message received: " + msg);
        return;//from w  w w .  jav  a2  s. c  o  m
    } else {
        LOG.debug("HttpResponseHandler response message received: " + msg);
    }

    Entry<ChannelFuture, ChannelPromise> entry = streamidPromiseMap.get(streamId);
    List<String> list = new ArrayList<String>();
    list.add(msg.status().code() + "");
    if (entry == null) {
        System.err.println("Message received for unknown stream id " + streamId);
    } else {
        // Do stuff with the message (for now just print it)
        ByteBuf byteBuf = msg.content();
        if (byteBuf.isReadable()) {
            int contentLength = byteBuf.readableBytes();
            byte[] arr = new byte[contentLength];
            byteBuf.readBytes(arr);
            String content = new String(arr, 0, contentLength, CharsetUtil.UTF_8);
            list.add(content);
            System.out.println("Protocol version: " + msg.protocolVersion());
            System.out.println("status: " + list.get(0) + " response content: " + list.get(1));
            LOG.debug("Protocol version: " + msg.protocolVersion());
            LOG.debug("status: " + list.get(0) + " response content: " + list.get(1));
        }

        mNettyHttp2Client.setResponse(streamId + ctx.channel().id().asShortText(), list);
        if (null != mCallback) {
            ResponseWrapper wrapper = new ResponseWrapper();
            wrapper.responseCode = Integer.valueOf(list.get(0));
            if (list.size() > 1) {
                wrapper.responseContent = list.get(1);
            }
            mCallback.onSucceed(wrapper);
        }

        entry.getValue().setSuccess();
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;
            System.err.println("content: " + content.content().toString(CharsetUtil.UTF_8));
            System.err.flush();

            if (content instanceof LastHttpContent) {
                System.err.println(" end of content");
                //                    ctx.close();
            }
        }

    }
}

From source file:cn.npt.net.handler.BaseWebSocketClientHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();/*from   www  . j  a v  a  2  s  .  com*/
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        log.info("WebSocket Client connected to " + ctx.channel());
        handshakeFuture.setSuccess();
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.getStatus()
                + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        doReceive(textFrame.text());
    } else if (frame instanceof PongWebSocketFrame) {
        //System.out.println("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
        log.info("WebSocket Client received closing");
        ch.close();
    }
}

From source file:cn.pengj.udpdemo.EchoSeverHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    // ??/*from w  ww .  j  av  a2  s . c om*/
    ByteBuf buf = (ByteBuf) packet.copy().content();
    byte[] req = new byte[buf.readableBytes()];
    buf.readBytes(req);
    String body = new String(req, CharsetUtil.UTF_8);
    System.out.println("?NOTE>>>>>> ?" + body);

    // ???
    ctx.writeAndFlush(new DatagramPacket(
            Unpooled.copiedBuffer("HelloServer" + System.currentTimeMillis(),
                    CharsetUtil.UTF_8),
            packet.sender())).sync();
}

From source file:cn.scujcc.bug.bitcoinplatformandroid.util.socket.websocket.WebSocketClientHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();//from   w w  w .j  a v  a  2  s  .  c o  m
    moniter.updateTime();
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        System.out.println("WebSocket Client connected!");
        handshakeFuture.setSuccess();
        return;
    }

    if (msg instanceof FullHttpResponse) {
        FullHttpResponse response = (FullHttpResponse) msg;
        throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.getStatus()
                + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
    }

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        service.onReceive(textFrame.text());
    } else if (frame instanceof BinaryWebSocketFrame) {
        BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
        service.onReceive(decodeByteBuff(binaryFrame.content()));
    } else if (frame instanceof PongWebSocketFrame) {
        System.out.println("WebSocket Client received pong");
    } else if (frame instanceof CloseWebSocketFrame) {
        System.out.println("WebSocket Client received closing");
        ch.close();
    }
}