Example usage for io.netty.buffer ByteBuf writeBytes

List of usage examples for io.netty.buffer ByteBuf writeBytes

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf writeBytes.

Prototype

public abstract ByteBuf writeBytes(ByteBuffer src);

Source Link

Document

Transfers the specified source buffer's data to this buffer starting at the current writerIndex until the source buffer's position reaches its limit, and increases the writerIndex by the number of the transferred bytes.

Usage

From source file:com.corundumstudio.socketio.handler.EncoderHandler.java

License:Apache License

private void handleWebsocket(final OutPacketMessage msg, ChannelHandlerContext ctx) throws IOException {
    while (true) {
        Queue<Packet> queue = msg.getClientHead().getPacketsQueue(msg.getTransport());
        Packet packet = queue.poll();// w ww.j  a  v a 2  s  .  c  om
        if (packet == null) {
            break;
        }

        final ByteBuf out = encoder.allocateBuffer(ctx.alloc());
        encoder.encodePacket(packet, out, ctx.alloc(), true);

        WebSocketFrame res = new TextWebSocketFrame(out);
        if (log.isTraceEnabled()) {
            log.trace("Out message: {} sessionId: {}", out.toString(CharsetUtil.UTF_8), msg.getSessionId());
        }
        if (out.isReadable()) {
            ctx.channel().writeAndFlush(res);
        } else {
            out.release();
        }

        for (ByteBuf buf : packet.getAttachments()) {
            ByteBuf outBuf = encoder.allocateBuffer(ctx.alloc());
            outBuf.writeByte(4);
            outBuf.writeBytes(buf);
            if (log.isTraceEnabled()) {
                log.trace("Out attachment: {} sessionId: {}", ByteBufUtil.hexDump(outBuf), msg.getSessionId());
            }
            ctx.channel().writeAndFlush(new BinaryWebSocketFrame(outBuf));
        }
    }
}

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

License:Apache License

public void encodeJsonP(String param, String msg, ByteBuf out) throws IOException {
    String message = "io.j[" + param + "](" + jsonSupport.writeValueAsString(msg) + ");";
    out.writeBytes(message.getBytes());
}

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

License:Apache License

public void encodePackets(Queue<Packet> packets, ByteBuf buffer, ByteBufAllocator allocator)
        throws IOException {
    if (packets.size() == 1) {
        Packet packet = packets.poll();//from  w  w w .j  av  a 2s . co m
        encodePacket(packet, buffer);
    } else {
        int counter = 0;
        while (true) {
            Packet packet = packets.poll();
            if (packet == null) {
                break;
            }
            counter++;
            // to prevent infinity out message
            if (counter == 100) {
                return;
            }

            ByteBuf packetBuffer = allocateBuffer(allocator);
            try {
                int len = encodePacket(packet, packetBuffer);
                byte[] lenBytes = toChars(len);

                buffer.writeBytes(Packet.DELIMITER_BYTES);
                buffer.writeBytes(lenBytes);
                buffer.writeBytes(Packet.DELIMITER_BYTES);
                buffer.writeBytes(packetBuffer);
            } finally {
                packetBuffer.release();
            }
        }
    }
}

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

License:Apache License

public int encodePacket(Packet packet, ByteBuf buffer) throws IOException {
    ByteBufOutputStream out = new ByteBufOutputStream(buffer);
    int start = buffer.writerIndex();
    int type = packet.getType().getValue();
    buffer.writeByte(toChar(type));//from  w w  w  .j av  a  2 s . c  o m
    buffer.writeByte(Packet.SEPARATOR);

    Long id = packet.getId();
    String endpoint = packet.getEndpoint();
    Object ack = packet.getAck();

    if (Packet.ACK_DATA.equals(ack)) {
        buffer.writeBytes(toChars(id));
        buffer.writeByte('+');
    } else {
        if (id != null) {
            buffer.writeBytes(toChars(id));
        }
    }
    buffer.writeByte(Packet.SEPARATOR);

    if (endpoint != null) {
        buffer.writeBytes(endpoint.getBytes());
    }

    switch (packet.getType()) {

    case MESSAGE:
        if (packet.getData() != null) {
            buffer.writeByte(Packet.SEPARATOR);
            byte[] data = packet.getData().toString().getBytes();
            buffer.writeBytes(data);
        }
        break;

    case EVENT:
        List<Object> args = packet.getArgs();
        if (args.isEmpty()) {
            args = null;
        }
        buffer.writeByte(Packet.SEPARATOR);
        Event event = new Event(packet.getName(), args);
        jsonSupport.writeValue(out, event);
        break;

    case JSON:
        buffer.writeByte(Packet.SEPARATOR);
        jsonSupport.writeValue(out, packet.getData());
        break;

    case CONNECT:
        if (packet.getQs() != null) {
            buffer.writeByte(Packet.SEPARATOR);
            byte[] qsData = packet.getQs().toString().getBytes();
            buffer.writeBytes(qsData);
        }
        break;

    case ACK:
        if (packet.getAckId() != null || !packet.getArgs().isEmpty()) {
            buffer.writeByte(Packet.SEPARATOR);
        }
        if (packet.getAckId() != null) {
            byte[] ackIdData = toChars(packet.getAckId());
            buffer.writeBytes(ackIdData);
        }
        if (!packet.getArgs().isEmpty()) {
            buffer.writeByte('+');
            jsonSupport.writeValue(out, packet.getArgs());
        }
        break;

    case ERROR:
        if (packet.getReason() != null || packet.getAdvice() != null) {
            buffer.writeByte(Packet.SEPARATOR);
        }
        if (packet.getReason() != null) {
            int reasonCode = packet.getReason().getValue();
            buffer.writeByte(toChar(reasonCode));
        }
        if (packet.getAdvice() != null) {
            int adviceCode = packet.getAdvice().getValue();
            buffer.writeByte('+');
            buffer.writeByte(toChar(adviceCode));
        }
        break;
    }
    return charsScanner.getLength(buffer, start);
}

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

License:Apache License

public void encodeJsonP(Integer jsonpIndex, Queue<Packet> packets, ByteBuf out, ByteBufAllocator allocator,
        int limit) throws IOException {
    boolean jsonpMode = jsonpIndex != null;

    ByteBuf buf = allocateBuffer(allocator);

    int i = 0;/*from   w  ww.  ja va2s  . c  o m*/
    while (true) {
        Packet packet = packets.poll();
        if (packet == null || i == limit) {
            break;
        }

        ByteBuf packetBuf = allocateBuffer(allocator);
        encodePacket(packet, packetBuf, allocator, true);

        int packetSize = packetBuf.writerIndex();
        buf.writeBytes(toChars(packetSize));
        buf.writeBytes(B64_DELIMITER);
        buf.writeBytes(packetBuf);

        packetBuf.release();

        i++;

        for (ByteBuf attachment : packet.getAttachments()) {
            ByteBuf encodedBuf = Base64.encode(attachment, Base64Dialect.URL_SAFE);
            buf.writeBytes(toChars(encodedBuf.readableBytes() + 2));
            buf.writeBytes(B64_DELIMITER);
            buf.writeBytes(BINARY_HEADER);
            buf.writeBytes(encodedBuf);
        }
    }

    if (jsonpMode) {
        out.writeBytes(JSONP_HEAD);
        out.writeBytes(toChars(jsonpIndex));
        out.writeBytes(JSONP_START);
    }

    processUtf8(buf, out, jsonpMode);
    buf.release();

    if (jsonpMode) {
        out.writeBytes(JSONP_END);
    }
}

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

License:Apache License

public void encodePackets(Queue<Packet> packets, ByteBuf buffer, ByteBufAllocator allocator, int limit)
        throws IOException {
    int i = 0;//from   w ww  . j ava 2  s  .  co m
    while (true) {
        Packet packet = packets.poll();
        if (packet == null || i == limit) {
            break;
        }
        encodePacket(packet, buffer, allocator, false);

        i++;

        for (ByteBuf attachment : packet.getAttachments()) {
            buffer.writeByte(1);
            buffer.writeBytes(longToBytes(attachment.readableBytes() + 1));
            buffer.writeByte(0xff);
            buffer.writeByte(4);
            buffer.writeBytes(attachment);
        }
    }
}

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;
    if (!binary) {
        buf = allocateBuffer(allocator);
    }//from   w  w w.j a  v a  2s  . com
    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.corundumstudio.socketio.SocketIOEncoder.java

License:Apache License

private void handle(AuthorizeMessage authMsg, Channel channel, ByteBuf out) throws IOException {
    String message = authMsg.getMsg();
    if (authMsg.getJsonpParam() != null) {
        encoder.encodeJsonP(authMsg.getJsonpParam(), message, out);
    } else {/*from   ww  w .ja  v  a  2 s .c  o  m*/
        out.writeBytes(message.getBytes());
    }
    sendMessage(authMsg, channel, out);
}

From source file:com.couchbase.client.core.endpoint.AbstractGenericHandler.java

License:Apache License

/**
 * Add basic authentication headers to a {@link HttpRequest}.
 *
 * The given information is Base64 encoded and the authorization header is set appropriately. Since this needs
 * to be done for every request, it is refactored out.
 *
 * @param ctx the handler context./*  w w  w .  j av  a2s  . c  o  m*/
 * @param request the request where the header should be added.
 * @param user the username for auth.
 * @param password the password for auth.
 */
public static void addHttpBasicAuth(final ChannelHandlerContext ctx, final HttpRequest request,
        final String user, final String password) {
    final String pw = password == null ? "" : password;

    ByteBuf raw = ctx.alloc().buffer(user.length() + pw.length() + 1);
    raw.writeBytes((user + ":" + pw).getBytes(CHARSET));
    ByteBuf encoded = Base64.encode(raw, false);
    request.headers().add(HttpHeaders.Names.AUTHORIZATION, "Basic " + encoded.toString(CHARSET));
    encoded.release();
    raw.release();
}

From source file:com.couchbase.client.core.endpoint.binary.BinaryHandler.java

License:Open Source License

/**
 * Encodes a {@link ObserveRequest} into its lower level representation.
 *
 * @return a ready {@link BinaryMemcacheRequest}.
 *//*from  w  w  w .ja v a2s.c om*/
private static BinaryMemcacheRequest handleObserveRequest(final ChannelHandlerContext ctx,
        final ObserveRequest msg) {
    String key = msg.key();
    ByteBuf content = ctx.alloc().buffer();
    content.writeShort(msg.partition());
    content.writeShort(key.length());
    content.writeBytes(key.getBytes(CHARSET));

    BinaryMemcacheRequest request = new DefaultFullBinaryMemcacheRequest("", Unpooled.EMPTY_BUFFER, content);
    request.setOpcode(OP_OBSERVE);
    request.setTotalBodyLength(content.readableBytes());
    return request;
}