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.cloudhopper.smpp.util.ChannelBufferUtil.java

License:Apache License

/**
 * Writes a C-String (null terminated) to a buffer.  If the String is null
 * this method will only write out the NULL byte (0x00) to the buffer.
 * @param buffer//www  . j  a v  a  2  s  . co  m
 * @param value
 * @throws UnsupportedEncodingException
 */
static public void writeNullTerminatedString(ByteBuf buffer, String value) throws UnrecoverablePduException {
    if (value != null) {
        try {
            byte[] bytes = value.getBytes("ISO-8859-1");
            buffer.writeBytes(bytes);
        } catch (UnsupportedEncodingException e) {
            throw new UnrecoverablePduException(e.getMessage(), e);
        }
    }
    // always write null byte
    buffer.writeByte((byte) 0x00);
}

From source file:com.codebullets.external.party.simulator.connections.websocket.inbound.NettyWebSocketServerHandler.java

License:Apache License

private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) {

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
    } else if (frame instanceof PingWebSocketFrame) {
        ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
    } else if (frame instanceof TextWebSocketFrame) {
        String request = ((TextWebSocketFrame) frame).text();
        LOG.debug("{} received {}", ctx.channel(), request);
        connectionMonitor.messageReceived(MessageReceivedEvent.create(getContext(ctx), request));
    } else if (frame instanceof BinaryWebSocketFrame) {
        ByteBuf buffer = Unpooled.buffer(frame.content().capacity());
        buffer.writeBytes(frame.content());
        byte[] data = buffer.array();
        LOG.debug("{} received {} bytes of data.", ctx.channel(), data.length);
        connectionMonitor.messageReceived(MessageReceivedEvent.create(getContext(ctx), data));
    } else {/*from  w  ww . j a v a  2 s.  co  m*/
        throw new UnsupportedOperationException(
                String.format("%s frame types not supported", frame.getClass().getName()));
    }
}

From source file:com.codebullets.external.party.simulator.connections.websocket.outbound.NettyWebSocketClientHandler.java

License:Apache License

@Override
public void messageReceived(final ChannelHandlerContext ctx, final Object msg) throws Exception {
    Channel ch = ctx.channel();//from ww w  .ja va2 s .c om
    if (!handshaker.isHandshakeComplete()) {
        handshaker.finishHandshake(ch, (FullHttpResponse) msg);
        LOG.info("WebSocket client {} connected.", connectionName);
        connectionMonitor.connectionEstablished(getContext(ctx));
        handshakeFuture.setSuccess();
        return;
    }

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

    WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
        TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
        LOG.debug("WebSocket client {} received message: " + textFrame.text(), connectionName);
        connectionMonitor.messageReceived(MessageReceivedEvent.create(getContext(ctx), textFrame.text()));
    } else if (frame instanceof BinaryWebSocketFrame) {
        ByteBuf buffer = Unpooled.buffer(frame.content().capacity());
        buffer.writeBytes(frame.content());
        byte[] data = buffer.array();
        LOG.debug("WebSocket client {} received buffer with length " + data.length, connectionName);
        connectionMonitor.messageReceived(MessageReceivedEvent.create(getContext(ctx), buffer));
    } else if (frame instanceof PingWebSocketFrame) {
        LOG.trace("WebSocket client {} received ping.", connectionName);
        ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
    } else if (frame instanceof CloseWebSocketFrame) {
        LOG.debug("WebSocket client {} received closing frame.", connectionName);
        ch.close();
    }
}

From source file:com.codnos.dbgp.internal.handlers.DBGpCommandEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
    Command command = (Command) msg;/*from w ww  . j a  v  a2  s  . c  o m*/
    String commandMessage = command.getMessage();
    LOGGER.fine("sending command: " + commandMessage);
    out.writeBytes(commandMessage.getBytes(UTF_8));
    out.writeByte(NULL_BYTE);
}

From source file:com.codnos.dbgp.internal.handlers.DBGpInitHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) {
    byte[] initBytes = initMessage.asString().getBytes(UTF_8);
    String size = String.valueOf(initBytes.length);
    byte[] sizeBytes = size.getBytes(UTF_8);
    final ByteBuf initMessageBuffer = ctx.alloc().buffer(sizeBytes.length + 1 + initBytes.length + 1);
    initMessageBuffer.writeBytes(sizeBytes);
    initMessageBuffer.writeZero(1);//from  w  w w .  j  a va2 s  .c  om
    initMessageBuffer.writeBytes(initBytes);
    initMessageBuffer.writeZero(1);
    ctx.writeAndFlush(initMessageBuffer);
}

From source file:com.codnos.dbgp.internal.handlers.DBGpResponseEncoder.java

License:Apache License

@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf byteBuf) throws Exception {
    String message = (String) msg;
    byte[] initBytes = message.getBytes(UTF_8);
    String size = String.valueOf(initBytes.length);
    byte[] sizeBytes = size.getBytes(UTF_8);
    final ByteBuf initMessageBuffer = ctx.alloc().buffer(sizeBytes.length + 1 + initBytes.length + 1);
    initMessageBuffer.writeBytes(sizeBytes);
    initMessageBuffer.writeZero(1);/*  www .  j av a  2 s  . c om*/
    initMessageBuffer.writeBytes(initBytes);
    initMessageBuffer.writeZero(1);
    LOGGER.fine("sending response=" + initMessageBuffer.toString(UTF_8));
    ctx.writeAndFlush(initMessageBuffer);
}

From source file:com.comphenix.protocol.compat.netty.independent.NettyChannelInjector.java

License:Open Source License

/**
 * Encode a packet to a byte buffer, taking over for the standard Minecraft encoder.
 * @param ctx - the current context.//w ww. j ava  2s  .  com
 * @param packet - the packet to encode to a byte array.
 * @param output - the output byte array.
 * @throws Exception If anything went wrong.
 */
protected void encode(ChannelHandlerContext ctx, Object packet, ByteBuf output) throws Exception {
    NetworkMarker marker = null;
    PacketEvent event = currentEvent;

    try {
        // Skip every kind of non-filtered packet
        if (!scheduleProcessPackets.get()) {
            return;
        }

        // This packet has not been seen by the main thread
        if (event == null) {
            Class<?> clazz = packet.getClass();

            // Schedule the transmission on the main thread instead
            if (channelListener.hasMainThreadListener(clazz)) {
                // Delay the packet
                scheduleMainThread(packet);
                packet = null;

            } else {
                event = processSending(packet);

                // Handle the output
                if (event != null) {
                    packet = !event.isCancelled() ? event.getPacket().getHandle() : null;
                }
            }
        }
        if (event != null) {
            // Retrieve marker without accidentally constructing it
            marker = NetworkMarker.getNetworkMarker(event);
        }

        // Process output handler
        if (packet != null && event != null && NetworkMarker.hasOutputHandlers(marker)) {
            ByteBuf packetBuffer = ctx.alloc().buffer();
            ENCODE_BUFFER.invoke(vanillaEncoder, ctx, packet, packetBuffer);

            // Let each handler prepare the actual output
            byte[] data = processor.processOutput(event, marker, getBytes(packetBuffer));

            // Write the result
            output.writeBytes(data);
            packet = null;

            // Sent listeners?
            finalEvent = event;
            return;
        }
    } catch (Exception e) {
        channelListener.getReporter().reportDetailed(this,
                Report.newBuilder(REPORT_CANNOT_INTERCEPT_SERVER_PACKET).callerParam(packet).error(e).build());
    } finally {
        // Attempt to handle the packet nevertheless
        if (packet != null) {
            ENCODE_BUFFER.invoke(vanillaEncoder, ctx, packet, output);
            finalEvent = event;
        }
    }
}

From source file:com.comphenix.protocol.injector.netty.WirePacket.java

License:Open Source License

/**
 * Writes the contents of this packet to a given output
 * @param output Output to write to//  w  ww .ja va2  s.co  m
 */
public void writeBytes(ByteBuf output) {
    checkNotNull(output, "output cannot be null!");
    output.writeBytes(bytes);
}

From source file:com.comphenix.protocol.injector.netty.WirePacket.java

License:Open Source License

/**
 * Creates a byte array from an existing PacketContainer containing all the
 * bytes from that packet/* ww  w. ja v  a 2 s.c  o m*/
 * 
 * @param packet Existing packet
 * @return The ByteBuf
 */
public static byte[] bytesFromPacket(PacketContainer packet) {
    checkNotNull(packet, "packet cannot be null!");

    ByteBuf buffer = PacketContainer.createPacketBuffer();
    ByteBuf store = PacketContainer.createPacketBuffer();

    // Read the bytes once
    Method write = MinecraftMethods.getPacketWriteByteBufMethod();

    try {
        write.invoke(packet.getHandle(), buffer);
    } catch (ReflectiveOperationException ex) {
        throw new RuntimeException("Failed to read packet contents.", ex);
    }

    byte[] bytes = getBytes(buffer);

    // Rewrite them to the packet to avoid issues with certain packets
    if (packet.getType() == PacketType.Play.Server.CUSTOM_PAYLOAD
            || packet.getType() == PacketType.Play.Client.CUSTOM_PAYLOAD) {
        // Make a copy of the array before writing
        byte[] ret = Arrays.copyOf(bytes, bytes.length);
        store.writeBytes(bytes);

        Method read = MinecraftMethods.getPacketReadByteBufMethod();

        try {
            read.invoke(packet.getHandle(), store);
        } catch (ReflectiveOperationException ex) {
            throw new RuntimeException("Failed to rewrite packet contents.", ex);
        }

        return ret;
    }

    return bytes;
}

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

License:Apache License

private void write(XHRPostMessage msg, ChannelHandlerContext ctx) {
    ByteBuf out = encoder.allocateBuffer(ctx.alloc());
    out.writeBytes(OK);
    sendMessage(msg, ctx.channel(), out, "text/html");
}