Example usage for io.netty.buffer Unpooled wrappedBuffer

List of usage examples for io.netty.buffer Unpooled wrappedBuffer

Introduction

In this page you can find the example usage for io.netty.buffer Unpooled wrappedBuffer.

Prototype

public static ByteBuf wrappedBuffer(ByteBuffer... buffers) 

Source Link

Document

Creates a new big-endian composite buffer which wraps the slices of the specified NIO buffers without copying them.

Usage

From source file:com.corundumstudio.socketio.parser.PayloadTest.java

License:Apache License

@Test
public void testPayloadDecode() throws IOException {
    ByteBuf buffer = Unpooled
            .wrappedBuffer("\ufffd5\ufffd3:::5\ufffd7\ufffd3:::53d\ufffd3\ufffd0::".getBytes());
    List<Packet> payload = new ArrayList<Packet>();
    while (buffer.isReadable()) {
        Packet packet = decoder.decodePackets(buffer, null);
        payload.add(packet);// w w  w.j  ava  2s.c o m
    }

    Assert.assertEquals(3, payload.size());
    Packet msg1 = payload.get(0);
    Assert.assertEquals(PacketType.MESSAGE, msg1.getType());
    Assert.assertEquals("5", msg1.getData());
    Packet msg2 = payload.get(1);
    Assert.assertEquals(PacketType.MESSAGE, msg2.getType());
    Assert.assertEquals("53d", msg2.getData());
    Packet msg3 = payload.get(2);
    Assert.assertEquals(PacketType.DISCONNECT, msg3.getType());
}

From source file:com.corundumstudio.socketio.parser.UTF8CharsScannerTest.java

License:Apache License

@Test
public void testfindTailIndex() {
    String str = "132 4  \ufffd\ufffd  \\";
    UTF8CharsScanner p = new UTF8CharsScanner();
    ByteBuf b = Unpooled.wrappedBuffer(str.getBytes());
    int len = p.findTailIndex(b, b.readerIndex(), b.capacity(), str.length());
    Assert.assertEquals(b.capacity(), len);
}

From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java

License:Apache License

public ByteBuf preprocessJson(Integer jsonIndex, ByteBuf content) throws IOException {
    String packet = URLDecoder.decode(content.toString(CharsetUtil.UTF_8), CharsetUtil.UTF_8.name());

    int startPos = 0;
    if (jsonIndex != null) {
        // skip "d="
        startPos = 2;//w w w  .ja  va 2s. c  o  m

        /**
        * double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
        * (c) socket.io.js
        *
        * @see https://github.com/Automattic/socket.io-client/blob/1.3.3/socket.io.js#L2682
        */
        packet = packet.replace("\\\\n", "\\n");
    }

    int splitIndex = packet.indexOf(":");
    String len = packet.substring(startPos, splitIndex);
    Integer length = Integer.valueOf(len);

    packet = packet.substring(splitIndex + 1, splitIndex + length + 1);
    packet = new String(packet.getBytes(CharsetUtil.ISO_8859_1), CharsetUtil.UTF_8);

    return Unpooled.wrappedBuffer(packet.getBytes(CharsetUtil.UTF_8));
}

From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java

License:Apache License

public Packet decodePackets(ByteBuf buffer, ClientHead client) throws IOException {
    if (isStringPacket(buffer)) {
        // TODO refactor
        int headEndIndex = buffer.bytesBefore((byte) -1);
        int len = (int) readLong(buffer, headEndIndex);

        ByteBuf frame = buffer.slice(buffer.readerIndex() + 1, len);
        // skip this frame
        buffer.readerIndex(buffer.readerIndex() + 1 + len);
        return decode(client, frame);
    } else if (hasLengthHeader(buffer)) {
        // TODO refactor
        int lengthEndIndex = buffer.bytesBefore((byte) ':');
        int lenHeader = (int) readLong(buffer, lengthEndIndex);
        int len = utf8scanner.getActualLength(buffer, lenHeader);

        ByteBuf frame = buffer.slice(buffer.readerIndex() + 1, len);
        if (lenHeader != len) {
            frame = Unpooled.wrappedBuffer(frame.toString(CharsetUtil.UTF_8).getBytes(CharsetUtil.ISO_8859_1));
        }//ww  w  . ja va2 s  .  co m
        // skip this frame
        buffer.readerIndex(buffer.readerIndex() + 1 + len);
        return decode(client, frame);
    }
    return decode(client, buffer);
}

From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java

License:Apache License

private Packet parseBinary(ClientHead head, ByteBuf frame) throws IOException {
    if (frame.getByte(0) == 1) {
        frame.readByte();//from w ww. ja  va  2  s  .co  m
        int headEndIndex = frame.bytesBefore((byte) -1);
        int len = (int) readLong(frame, headEndIndex);
        ByteBuf oldFrame = frame;
        frame = frame.slice(oldFrame.readerIndex() + 1, len);
        oldFrame.readerIndex(oldFrame.readerIndex() + 1 + len);
    }

    if (frame.getByte(0) == 'b' && frame.getByte(1) == '4') {
        frame.readShort();
    } else if (frame.getByte(0) == 4) {
        frame.readByte();
    }

    Packet binaryPacket = head.getLastBinaryPacket();
    if (binaryPacket != null) {
        ByteBuf attachBuf;
        if (frame.getByte(0) == 'b' && frame.getByte(1) == '4') {
            attachBuf = frame;
        } else {
            attachBuf = Base64.encode(frame);
        }
        binaryPacket.addAttachment(Unpooled.copiedBuffer(attachBuf));
        frame.readerIndex(frame.readerIndex() + frame.readableBytes());

        if (binaryPacket.isAttachmentsLoaded()) {
            LinkedList<ByteBuf> slices = new LinkedList<ByteBuf>();
            ByteBuf source = binaryPacket.getDataSource();
            for (int i = 0; i < binaryPacket.getAttachments().size(); i++) {
                ByteBuf attachment = binaryPacket.getAttachments().get(i);
                ByteBuf scanValue = Unpooled.copiedBuffer("{\"_placeholder\":true,\"num\":" + i + "}",
                        CharsetUtil.UTF_8);
                int pos = PacketEncoder.find(source, scanValue);
                if (pos == -1) {
                    throw new IllegalStateException(
                            "Can't find attachment by index: " + i + " in packet source");
                }

                ByteBuf prefixBuf = source.slice(source.readerIndex(), pos - source.readerIndex());
                slices.add(prefixBuf);
                slices.add(QUOTES);
                slices.add(attachment);
                slices.add(QUOTES);

                source.readerIndex(pos + scanValue.readableBytes());
            }
            slices.add(source.slice());

            ByteBuf compositeBuf = Unpooled.wrappedBuffer(slices.toArray(new ByteBuf[slices.size()]));
            parseBody(head, compositeBuf, binaryPacket);
            head.setLastBinaryPacket(null);
            return binaryPacket;
        }
    }
    return new Packet(PacketType.MESSAGE);
}

From source file:com.corundumstudio.socketio.protocol.PacketEncoder.java

License:Apache License

public void encodePacket(Packet packet, ByteBuf buffer, ByteBufAllocator allocator, boolean binary)
        throws IOException {
    ByteBuf buf = buffer;//www  .j a  va2s  .  com
    if (!binary) {
        buf = allocateBuffer(allocator);
    }
    byte type = toChar(packet.getType().getValue());
    buf.writeByte(type);

    try {
        switch (packet.getType()) {

        case PONG: {
            buf.writeBytes(packet.getData().toString().getBytes(CharsetUtil.UTF_8));
            break;
        }

        case OPEN: {
            ByteBufOutputStream out = new ByteBufOutputStream(buf);
            jsonSupport.writeValue(out, packet.getData());
            break;
        }

        case MESSAGE: {

            ByteBuf encBuf = null;

            if (packet.getSubType() == PacketType.ERROR) {
                encBuf = allocateBuffer(allocator);

                ByteBufOutputStream out = new ByteBufOutputStream(encBuf);
                jsonSupport.writeValue(out, packet.getData());
            }

            if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.ACK) {

                List<Object> values = new ArrayList<Object>();
                if (packet.getSubType() == PacketType.EVENT) {
                    values.add(packet.getName());
                }

                encBuf = allocateBuffer(allocator);

                List<Object> args = packet.getData();
                values.addAll(args);
                ByteBufOutputStream out = new ByteBufOutputStream(encBuf);
                jsonSupport.writeValue(out, values);

                if (!jsonSupport.getArrays().isEmpty()) {
                    packet.initAttachments(jsonSupport.getArrays().size());
                    for (byte[] array : jsonSupport.getArrays()) {
                        packet.addAttachment(Unpooled.wrappedBuffer(array));
                    }
                    packet.setSubType(PacketType.BINARY_EVENT);
                }
            }

            byte subType = toChar(packet.getSubType().getValue());
            buf.writeByte(subType);

            if (packet.hasAttachments()) {
                byte[] ackId = toChars(packet.getAttachments().size());
                buf.writeBytes(ackId);
                buf.writeByte('-');
            }

            if (packet.getSubType() == PacketType.CONNECT) {
                if (!packet.getNsp().isEmpty()) {
                    buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8));
                }
            } else {
                if (!packet.getNsp().isEmpty()) {
                    buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8));
                    buf.writeByte(',');
                }
            }

            if (packet.getAckId() != null) {
                byte[] ackId = toChars(packet.getAckId());
                buf.writeBytes(ackId);
            }

            if (encBuf != null) {
                buf.writeBytes(encBuf);
                encBuf.release();
            }

            break;
        }
        }
    } finally {
        // we need to write a buffer in any case
        if (!binary) {
            buffer.writeByte(0);
            int length = buf.writerIndex();
            buffer.writeBytes(longToBytes(length));
            buffer.writeByte(0xff);
            buffer.writeBytes(buf);

            buf.release();
        }
    }
}

From source file:com.couchbase.client.core.endpoint.kv.KeyValueAuthHandler.java

License:Apache License

/**
 * Handles an incoming SASL AUTH response and - if needed - dispatches the SASL STEPs.
 *
 * @param ctx the handler context.// www  . ja  v a  2 s  . com
 * @param msg the incoming message to investigate.
 * @throws Exception if something goes wrong during negotiation.
 */
private void handleAuthResponse(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
    if (saslClient.isComplete()) {
        checkIsAuthed(msg);
        return;
    }

    byte[] response = new byte[msg.content().readableBytes()];
    msg.content().readBytes(response);
    byte[] evaluatedBytes = saslClient.evaluateChallenge(response);

    if (evaluatedBytes != null) {
        ByteBuf content;

        // This is needed against older server versions where the protocol does not
        // align on cram and plain, the else block is used for all the newer cram-sha*
        // mechanisms.
        //
        // Note that most likely this is only executed in the CRAM-MD5 case only, but
        // just to play it safe keep it for both mechanisms.
        if (selectedMechanism.equals("CRAM-MD5") || selectedMechanism.equals("PLAIN")) {
            String[] evaluated = new String(evaluatedBytes).split(" ");
            content = Unpooled.copiedBuffer(username + "\0" + evaluated[1], CharsetUtil.UTF_8);
        } else {
            content = Unpooled.wrappedBuffer(evaluatedBytes);
        }

        FullBinaryMemcacheRequest stepRequest = new DefaultFullBinaryMemcacheRequest(
                selectedMechanism.getBytes(CharsetUtil.UTF_8), Unpooled.EMPTY_BUFFER, content);
        stepRequest.setOpcode(SASL_STEP_OPCODE).setKeyLength((short) selectedMechanism.length())
                .setTotalBodyLength(content.readableBytes() + selectedMechanism.length());

        ChannelFuture future = ctx.writeAndFlush(stepRequest);
        future.addListener(new GenericFutureListener<Future<Void>>() {
            @Override
            public void operationComplete(Future<Void> future) throws Exception {
                if (!future.isSuccess()) {
                    LOGGER.warn("Error during SASL Auth negotiation phase.", future);
                }
            }
        });
    } else {
        throw new AuthenticationException("SASL Challenge evaluation returned null.");
    }
}

From source file:com.couchbase.client.core.message.kv.subdoc.simple.AbstractSubdocRequest.java

License:Apache License

/**
 * Creates a new {@link AbstractSubdocRequest}.
 *
 * @param key           the key of the document.
 * @param path          the subdocument path to consider inside the document.
 * @param bucket        the bucket of the document.
 * @param observable    the observable which receives responses.
 * @param restOfContent the optional remainder of the {@link #content()} of the final protocol message, or null if not applicable
 * @throws NullPointerException if the path is null (see {@link #EXCEPTION_NULL_PATH})
 *//*  w ww. ja v  a 2s . c om*/
public AbstractSubdocRequest(String key, String path, String bucket,
        Subject<CouchbaseResponse, CouchbaseResponse> observable, ByteBuf... restOfContent) {
    super(key, bucket, null, observable);
    this.path = path;
    ByteBuf pathByteBuf;
    if (path == null || path.isEmpty()) {
        pathByteBuf = Unpooled.EMPTY_BUFFER;
    } else {
        pathByteBuf = Unpooled.wrappedBuffer(path.getBytes(CharsetUtil.UTF_8));
    }
    this.pathLength = pathByteBuf.readableBytes();
    this.content = createContent(pathByteBuf, restOfContent);

    //checking nullity here allows to release all of restOfContent through cleanUpAndThrow releasing content()
    if (this.path == null) {
        cleanUpAndThrow(EXCEPTION_NULL_PATH);
    }
}

From source file:com.digitalpetri.modbus.requests.WriteMultipleCoilsRequest.java

License:Apache License

/**
 * @param address  0x0000 to 0xFFFF (0 to 65535)
 * @param quantity 0x0001 to 0x07B0 (1 to 2000)
 * @param values   buffer of at least N bytes, where N = (quantity + 7) / 8
 *///from w  w w  . ja  v a 2 s .c  o m
public WriteMultipleCoilsRequest(int address, int quantity, byte[] values) {
    this(address, quantity, Unpooled.wrappedBuffer(values));
}

From source file:com.digitalpetri.modbus.requests.WriteMultipleCoilsRequest.java

License:Apache License

/**
 * @param address  0x0000 to 0xFFFF (0 to 65535)
 * @param quantity 0x0001 to 0x07B0 (1 to 2000)
 * @param values   buffer of at least N bytes, where N = (quantity + 7) / 8
 *///  w w w  .j  a  va 2s. com
public WriteMultipleCoilsRequest(int address, int quantity, ByteBuffer values) {
    this(address, quantity, Unpooled.wrappedBuffer(values));
}