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.king.platform.net.http.netty.sse.ServerEventDecoder.java

License:Apache License

public void onReceivedContentPart(ByteBuf content) throws KingHttpException {
    String contentString = content.toString(StandardCharsets.UTF_8);
    try {//w w  w.java2  s . com
        char[] chars = contentString.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];

            if (isCRLF(i, chars)) {
                continue;
            }

            if (isNewLine(c)) {
                String line = buffer.toString();
                buffer.setLength(0);
                parseLine(line);
            } else {
                buffer.append(c);
            }

        }
    } catch (Exception e) {
        throw new KingHttpException("Failed to parse incoming content in SSE stream", e);
    }
}

From source file:com.kixeye.kixmpp.client.KixmppClient.java

License:Apache License

/**
 * Performs auth.//from w  w  w .j  av  a2  s.  c  o  m
 */
private void performAuth() {
    byte[] authToken = ("\0" + jid.getNode() + "\0" + password).getBytes(StandardCharsets.UTF_8);

    Element auth = new Element("auth", "urn:ietf:params:xml:ns:xmpp-sasl");
    auth.setAttribute("mechanism", "PLAIN");

    ByteBuf rawCredentials = channel.get().alloc().buffer().writeBytes(authToken);
    ByteBuf encodedCredentials = Base64.encode(rawCredentials);
    String encodedCredentialsString = encodedCredentials.toString(StandardCharsets.UTF_8);
    encodedCredentials.release();
    rawCredentials.release();

    auth.setText(encodedCredentialsString);

    channel.get().writeAndFlush(auth);
}

From source file:com.kixeye.kixmpp.KixmppCodec.java

License:Apache License

/**
 * @see io.netty.handler.codec.ByteToMessageCodec#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)
 *///ww  w .  ja v a 2 s . c o m
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("Received: [{}]", in.toString(StandardCharsets.UTF_8));
    }

    int retryCount = 0;
    Exception thrownException = null;

    // feed the data into the async xml input feeded
    byte[] data = new byte[in.readableBytes()];
    in.readBytes(data);

    if (streamReader != null) {
        while (retryCount < 2) {
            try {
                asyncInputFeeder.feedInput(data, 0, data.length);

                int event = -1;

                while (isValidEvent(event = streamReader.next())) {
                    // handle stream start/end
                    if (streamReader.getDepth() == STANZA_ELEMENT_DEPTH - 1) {
                        if (event == XMLStreamConstants.END_ELEMENT) {
                            out.add(new KixmppStreamEnd());

                            asyncInputFeeder.endOfInput();
                            streamReader.close();

                            streamReader = null;
                            asyncInputFeeder = null;

                            break;
                        } else if (event == XMLStreamConstants.START_ELEMENT) {
                            StAXElementBuilder streamElementBuilder = new StAXElementBuilder(true);

                            streamElementBuilder.process(streamReader);

                            out.add(new KixmppStreamStart(null, true));
                        }
                        // only handle events that have element depth of 2 and above (everything under <stream:stream>..)
                    } else if (streamReader.getDepth() >= STANZA_ELEMENT_DEPTH) {
                        // if this is the beginning of the element and this is at stanza depth
                        if (event == XMLStreamConstants.START_ELEMENT
                                && streamReader.getDepth() == STANZA_ELEMENT_DEPTH) {
                            elementBuilder = new StAXElementBuilder(true);
                            elementBuilder.process(streamReader);

                            // get the constructed element
                            Element element = elementBuilder.getElement();

                            if ("stream:stream".equals(element.getQualifiedName())) {
                                throw new RuntimeException("Starting a new stream.");
                            }
                            // if this is the ending of the element and this is at stanza depth
                        } else if (event == XMLStreamConstants.END_ELEMENT
                                && streamReader.getDepth() == STANZA_ELEMENT_DEPTH) {
                            elementBuilder.process(streamReader);

                            // get the constructed element
                            Element element = elementBuilder.getElement();

                            out.add(element);

                            // just process the event
                        } else {
                            elementBuilder.process(streamReader);
                        }
                    }
                }

                break;
            } catch (Exception e) {
                retryCount++;

                logger.info("Attempting to recover from impropper XML: " + e.getMessage());

                thrownException = e;

                try {
                    streamReader.close();
                } finally {
                    streamReader = inputFactory.createAsyncXMLStreamReader();
                    asyncInputFeeder = streamReader.getInputFeeder();
                }
            }
        }

        if (retryCount > 1) {
            throw thrownException;
        }
    }
}

From source file:com.kixeye.kixmpp.KixmppCodec.java

License:Apache License

/**
 * @see io.netty.handler.codec.ByteToMessageCodec#encode(io.netty.channel.ChannelHandlerContext, java.lang.Object, io.netty.buffer.ByteBuf)
 *///from  w  ww.  j a va  2s  .c o m
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
    if (msg instanceof Element) {
        new XMLOutputter().output((Element) msg, new ByteBufOutputStream(out));
    } else if (msg instanceof KixmppStreamStart) {
        KixmppStreamStart streamStart = (KixmppStreamStart) msg;
        if (streamStart.doesIncludeXmlHeader()) {
            out.writeBytes("<?xml version='1.0' encoding='UTF-8'?>".getBytes(StandardCharsets.UTF_8));
        }
        out.writeBytes("<stream:stream ".getBytes(StandardCharsets.UTF_8));
        if (streamStart.getId() != null) {
            out.writeBytes(String.format("id=\"%s\" ", streamStart.getId()).getBytes(StandardCharsets.UTF_8));
        }
        if (streamStart.getFrom() != null) {
            out.writeBytes(String.format("from=\"%s\" ", streamStart.getFrom().getFullJid())
                    .getBytes(StandardCharsets.UTF_8));
        }
        if (streamStart.getTo() != null) {
            out.writeBytes(String.format("to=\"%s\" ", streamStart.getTo().getFullJid())
                    .getBytes(StandardCharsets.UTF_8));
        }
        out.writeBytes(
                "version=\"1.0\" xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\">"
                        .getBytes(StandardCharsets.UTF_8));
    } else if (msg instanceof KixmppStreamEnd) {
        out.writeBytes("</stream:stream>".getBytes(StandardCharsets.UTF_8));
    } else if (msg instanceof String) {
        out.writeBytes(((String) msg).getBytes(StandardCharsets.UTF_8));
    } else if (msg instanceof ByteBuf) {
        ByteBuf buf = (ByteBuf) msg;

        out.writeBytes(buf, 0, buf.readableBytes());
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Sending: [{}]", out.toString(StandardCharsets.UTF_8));
    }
}

From source file:com.kixeye.kixmpp.KixmppWebSocketCodec.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
    WebSocketFrame frame = (WebSocketFrame) msg;

    ByteBuf content = frame.retain().content();
    String frameString = content.toString(StandardCharsets.UTF_8);

    if (logger.isDebugEnabled()) {
        logger.debug("Received: [{}]", frameString);
    }/*from  w  w  w  .j av  a  2  s . co  m*/

    if (frameString.startsWith("<?xml")) {
        frameString = frameString.replaceFirst("<\\?xml.*?\\?>", "");
    }

    if (frameString.startsWith("<stream:stream")) {
        out.add(new KixmppStreamStart(null, true));
    } else if (frameString.startsWith("</stream:stream")) {
        out.add(new KixmppStreamEnd());
    } else {

        SAXBuilder saxBuilder = new SAXBuilder(readerFactory);
        Document document = saxBuilder.build(new ByteBufInputStream(content));

        Element element = document.getRootElement();

        out.add(element);
    }

}

From source file:com.lambdaworks.redis.codec.StringCodecTest.java

License:Apache License

@Test
public void encodeUtf8Buf() throws Exception {

    StringCodec codec = new StringCodec(LettuceCharsets.UTF8);

    ByteBuf buffer = Unpooled.buffer(1234);
    codec.encode(teststring, buffer);/*w w w  .  j  a  v a 2s  . c  o  m*/

    assertThat(buffer.toString(StandardCharsets.UTF_8)).isEqualTo(teststring);
}

From source file:com.lambdaworks.redis.codec.StringCodecTest.java

License:Apache License

@Test
public void encodeAsciiBuf() throws Exception {

    StringCodec codec = new StringCodec(LettuceCharsets.ASCII);

    ByteBuf buffer = Unpooled.buffer(1234);
    codec.encode(teststringPlain, buffer);

    assertThat(buffer.toString(LettuceCharsets.ASCII)).isEqualTo(teststringPlain);
}

From source file:com.lambdaworks.redis.codec.StringCodecTest.java

License:Apache License

@Test
public void encodeIso88591Buf() throws Exception {

    StringCodec codec = new StringCodec(StandardCharsets.ISO_8859_1);

    ByteBuf buffer = Unpooled.buffer(1234);
    codec.encodeValue(teststringPlain, buffer);

    assertThat(buffer.toString(StandardCharsets.ISO_8859_1)).isEqualTo(teststringPlain);
}

From source file:com.lambdaworks.redis.protocol.CommandArgsTest.java

License:Apache License

@Test
public void addValues() throws Exception {

    CommandArgs<String, String> args = new CommandArgs<>(codec).addValues(Arrays.asList("1", "2"));

    ByteBuf buffer = Unpooled.buffer();
    args.encode(buffer);/*from ww w  .  j  a  v  a2  s. c  om*/

    ByteBuf expected = Unpooled.buffer();
    expected.writeBytes(("$1\r\n" + "1\r\n" + "$1\r\n" + "2\r\n").getBytes());

    assertThat(buffer.toString(LettuceCharsets.ASCII)).isEqualTo(expected.toString(LettuceCharsets.ASCII));
}

From source file:com.lambdaworks.redis.protocol.CommandArgsTest.java

License:Apache License

@Test
public void addByte() throws Exception {

    CommandArgs<String, String> args = new CommandArgs<>(codec).add("one".getBytes());

    ByteBuf buffer = Unpooled.buffer();
    args.encode(buffer);//from   w w  w  . j av  a 2  s.com

    ByteBuf expected = Unpooled.buffer();
    expected.writeBytes(("$3\r\n" + "one\r\n").getBytes());

    assertThat(buffer.toString(LettuceCharsets.ASCII)).isEqualTo(expected.toString(LettuceCharsets.ASCII));
}