Example usage for io.netty.buffer ByteBuf arrayOffset

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

Introduction

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

Prototype

public abstract int arrayOffset();

Source Link

Document

Returns the offset of the first byte within the backing byte array of this buffer.

Usage

From source file:org.hornetq.amqp.dealer.protonimpl.AbstractProtonSender.java

License:Apache License

protected int performSend(ProtonJMessage serverMessage, Object context) {
    if (!creditsSemaphore.tryAcquire()) {
        try {//from   w  w  w  .j  ava2  s .c o m
            creditsSemaphore.acquire();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            // nothing to be done here.. we just keep going
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    //presettle means we can ack the message on the dealer side before we send it, i.e. for browsers
    boolean preSettle = sender.getRemoteSenderSettleMode() == SenderSettleMode.SETTLED;

    //we only need a tag if we are going to ack later
    byte[] tag = preSettle ? new byte[0] : protonSession.getTag();

    ByteBuf nettyBuffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024);
    try {
        serverMessage.encode(new NettyWritable(nettyBuffer));

        int size = nettyBuffer.writerIndex();

        synchronized (connection.getTrio().getLock()) {
            final Delivery delivery;
            delivery = sender.delivery(tag, 0, tag.length);
            delivery.setContext(context);

            // this will avoid a copy.. patch provided by Norman using buffer.array()
            sender.send(nettyBuffer.array(), nettyBuffer.arrayOffset() + nettyBuffer.readerIndex(),
                    nettyBuffer.readableBytes());

            if (preSettle) {
                delivery.settle();
            } else {
                sender.advance();
            }
        }

        connection.flush();

        return size;
    } finally {
        nettyBuffer.release();
    }
}

From source file:org.hornetq.amqp.dealer.util.DeliveryUtil.java

License:Apache License

public static int readDelivery(Receiver receiver, ByteBuf buffer) {
    int initial = buffer.writerIndex();
    // optimization by norman
    int count;//from   ww  w .ja  v a 2  s.c  om
    while ((count = receiver.recv(buffer.array(), buffer.arrayOffset() + buffer.writerIndex(),
            buffer.writableBytes())) > 0) {
        // Increment the writer index by the number of bytes written into it while calling recv.
        buffer.writerIndex(buffer.writerIndex() + count);
    }
    return buffer.writerIndex() - initial;
}

From source file:org.hornetq.amqp.test.SimpleTest.java

License:Apache License

@Test
public void testMeasureMessageImpl() {

    long time = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++) {

        if (i % 10000 == 0) {
            System.out.println("Decoded " + i);
        }//from w ww .  j a va 2s .  co  m
        ByteBuf buf = PooledByteBufAllocator.DEFAULT.heapBuffer(1024 * 1024);
        MessageImpl message = (MessageImpl) Message.Factory.create();
        message.setBody(new Data(new Binary(new byte[5])));

        Properties props = new Properties();
        props.setMessageId("Some String");
        props.setAbsoluteExpiryTime(new Date(System.currentTimeMillis()));
        message.setProperties(props);

        message.encode(new NettyWritable(buf));

        MessageImpl readMessage = (MessageImpl) Message.Factory.create();
        readMessage.decode(buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes());
        buf.release();
    }

    long total = System.currentTimeMillis() - time;

    System.out.println("Took " + total);

}

From source file:org.mashupbots.socko.netty.HttpChunkedFile.java

License:Apache License

@Override
public HttpContent readChunk(ChannelHandlerContext ctx) throws Exception {
    long offset = this.offset;
    if (offset >= endOffset) {
        if (sentLastChunk) {
            return null;
        } else {/*from   w  w w .j  av a2s.co  m*/
            // Send last chunk for this file
            sentLastChunk = true;
            return new DefaultLastHttpContent();
        }
    }

    int chunkSize = (int) Math.min(this.chunkSize, endOffset - offset);
    // Check if the buffer is backed by an byte array. If so we can optimize it a bit an safe a copy

    ByteBuf buf = ctx.alloc().heapBuffer(chunkSize);
    boolean release = true;
    try {
        file.readFully(buf.array(), buf.arrayOffset(), chunkSize);
        buf.writerIndex(chunkSize);
        this.offset = offset + chunkSize;
        release = false;
        return new DefaultHttpContent(buf);
    } finally {
        if (release) {
            buf.release();
        }
    }

}

From source file:org.proton.plug.context.AbstractProtonContextSender.java

License:Apache License

protected int performSend(ProtonJMessage serverMessage, Object context) {
    if (!creditsSemaphore.tryAcquire()) {
        try {//w  ww. j  a va  2s  .c o m
            creditsSemaphore.acquire();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            // nothing to be done here.. we just keep going
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    //presettle means we can ack the message on the dealer side before we send it, i.e. for browsers
    boolean preSettle = sender.getRemoteSenderSettleMode() == SenderSettleMode.SETTLED;

    //we only need a tag if we are going to ack later
    byte[] tag = preSettle ? new byte[0] : protonSession.getTag();

    ByteBuf nettyBuffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024);
    try {
        serverMessage.encode(new NettyWritable(nettyBuffer));

        int size = nettyBuffer.writerIndex();

        synchronized (connection.getLock()) {
            final Delivery delivery;
            delivery = sender.delivery(tag, 0, tag.length);
            delivery.setContext(context);

            // this will avoid a copy.. patch provided by Norman using buffer.array()
            sender.send(nettyBuffer.array(), nettyBuffer.arrayOffset() + nettyBuffer.readerIndex(),
                    nettyBuffer.readableBytes());

            if (preSettle) {
                delivery.settle();
            } else {
                sender.advance();
            }
        }

        connection.flush();

        return size;
    } finally {
        nettyBuffer.release();
    }
}

From source file:org.restcomm.media.rtp.netty.RtpDemultiplexer.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
    // Differentiate between RTP, STUN and DTLS packets in the pipeline
    // https://tools.ietf.org/html/rfc5764#section-5.1.2
    final int offset = msg.arrayOffset();
    final byte b0 = msg.getByte(offset);
    final int b0Int = b0 & 0xff;

    if (b0Int < 2) {
        handleStunPacket(ctx, msg);/*from   w ww .  j  a va 2s  .c  o m*/
    } else if (b0Int > 19 && b0Int < 64) {
        handleDtlsPacket(ctx, msg);
    } else if (b0Int > 127 && b0Int < 192) {
        handleRtpPacket(ctx, msg);
    } else {
        // Unsupported packet type. Drop it.
        ReferenceCountUtil.release(msg);
        if (log.isDebugEnabled()) {
            log.debug("Channel " + ctx.channel().localAddress() + " dropped unsupported packet type " + b0Int);
        }
    }
}

From source file:org.restcomm.media.rtp.netty.RtpDemultiplexer.java

License:Open Source License

private void handleStunPacket(ChannelHandlerContext ctx, ByteBuf buffer) {
    // Retrieve data from network
    final byte[] data = buffer.array();
    final int length = buffer.readableBytes();
    final int offset = buffer.arrayOffset();

    // Wrap data into an STUN packet
    try {//w w w  . j  a  v a  2  s.  co m
        StunMessage stunPacket = StunMessage.decode(data, (char) offset, (char) length);
        ctx.fireChannelRead(stunPacket);
    } catch (StunException e) {
        // Drop packet as we could not decode it
        ReferenceCountUtil.release(buffer);
        log.warn("Channel " + ctx.channel().localAddress() + "could not decode incoming STUN packet", e);
    }
}

From source file:org.restcomm.media.rtp.netty.RtpDemultiplexer.java

License:Open Source License

private void handleDtlsPacket(ChannelHandlerContext ctx, ByteBuf buffer) {
    // Retrieve data from network
    final int length = buffer.readableBytes();
    final int offset = buffer.arrayOffset();

    // Wrap data into a DTLS packet
    byte[] data = new byte[length - offset];
    buffer.getBytes(offset, data);//w w w.j a v a2s. co m
    DtlsPacket dtlsPacket = new DtlsPacket(data);

    ctx.fireChannelRead(dtlsPacket);
}

From source file:org.restcomm.media.rtp.netty.RtpDemultiplexer.java

License:Open Source License

private void handleRtpPacket(ChannelHandlerContext ctx, ByteBuf buffer) {
    // Retrieve data from network
    final int offset = buffer.arrayOffset();

    /*/*from   w ww . j  av a  2 s.  com*/
     * When RTP and RTCP packets are multiplexed onto a single port, the RTCP packet type field occupies the same position
     * in the packet as the combination of the RTP marker (M) bit and the RTP payload type (PT). This field can be used to
     * distinguish RTP and RTCP packets when two restrictions are observed:
     * 
     * 1) the RTP payload type values used are distinct from the RTCP packet types used.
     * 
     * 2) for each RTP payload type (PT), PT+128 is distinct from the RTCP packet types used. The first constraint precludes
     * a direct conflict between RTP payload type and RTCP packet type; the second constraint precludes a conflict between
     * an RTP data packet with the marker bit set and an RTCP packet.
     */
    int type = buffer.getByte(offset + 1) & 0xff & 0x7f;
    int rtcpType = type + 128;

    // RTP payload types 72-76 conflict with the RTCP SR, RR, SDES, BYE and APP packets defined in the RTP specification
    switch (rtcpType) {
    case RtcpHeader.RTCP_SR:
    case RtcpHeader.RTCP_RR:
    case RtcpHeader.RTCP_SDES:
    case RtcpHeader.RTCP_BYE:
    case RtcpHeader.RTCP_APP:
        RtcpPacket rtcpPacket = buildRtcpPacket(buffer);
        ctx.fireChannelRead(rtcpPacket);
    default:
        RtpPacket rtpPacket = buildRtpPacket(buffer);
        ctx.fireChannelRead(rtpPacket);
        break;
    }
}

From source file:org.restcomm.media.rtp.netty.RtpDemultiplexer.java

License:Open Source License

private RtpPacket buildRtpPacket(ByteBuf msg) {
    // Retrieve data from network
    final byte[] data = msg.array();
    final int length = msg.readableBytes();
    final int offset = msg.arrayOffset();

    // Wrap data into an RTP packet
    final RtpPacket rtpPacket = new RtpPacket(length - offset, false);
    rtpPacket.getBuffer().put(data, offset, length).flip();
    return rtpPacket;
}