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.apache.distributedlog.common.util.ByteBufUtils.java

License:Apache License

public static byte[] getArray(ByteBuf buffer) {
    if (buffer.hasArray() && buffer.arrayOffset() == 0 && buffer.writableBytes() == 0) {
        return buffer.array();
    }/* www . j a  v  a2  s . c o m*/
    byte[] data = new byte[buffer.readableBytes()];
    buffer.getBytes(buffer.readerIndex(), data);
    return data;
}

From source file:org.apache.pulsar.broker.admin.impl.PersistentTopicsBase.java

License:Apache License

protected Response internalPeekNthMessage(String subName, int messagePosition, boolean authoritative) {
    if (topicName.isGlobal()) {
        validateGlobalNamespaceOwnership(namespaceName);
    }//from  w  w  w  .j  a va2  s .co  m
    PartitionedTopicMetadata partitionMetadata = getPartitionedTopicMetadata(topicName, authoritative);
    if (partitionMetadata.partitions > 0) {
        throw new RestException(Status.METHOD_NOT_ALLOWED,
                "Peek messages on a partitioned topic is not allowed");
    }
    validateAdminAccessForSubscriber(subName, authoritative);
    if (!(getTopicReference(topicName) instanceof PersistentTopic)) {
        log.error("[{}] Not supported operation of non-persistent topic {} {}", clientAppId(), topicName,
                subName);
        throw new RestException(Status.METHOD_NOT_ALLOWED,
                "Skip messages on a non-persistent topic is not allowed");
    }
    PersistentTopic topic = (PersistentTopic) getTopicReference(topicName);
    PersistentReplicator repl = null;
    PersistentSubscription sub = null;
    Entry entry = null;
    if (subName.startsWith(topic.replicatorPrefix)) {
        repl = getReplicatorReference(subName, topic);
    } else {
        sub = (PersistentSubscription) getSubscriptionReference(subName, topic);
    }
    try {
        if (subName.startsWith(topic.replicatorPrefix)) {
            entry = repl.peekNthMessage(messagePosition).get();
        } else {
            entry = sub.peekNthMessage(messagePosition).get();
        }
        checkNotNull(entry);
        PositionImpl pos = (PositionImpl) entry.getPosition();
        ByteBuf metadataAndPayload = entry.getDataBuffer();

        // moves the readerIndex to the payload
        MessageMetadata metadata = Commands.parseMessageMetadata(metadataAndPayload);

        ResponseBuilder responseBuilder = Response.ok();
        responseBuilder.header("X-Pulsar-Message-ID", pos.toString());
        for (KeyValue keyValue : metadata.getPropertiesList()) {
            responseBuilder.header("X-Pulsar-PROPERTY-" + keyValue.getKey(), keyValue.getValue());
        }
        if (metadata.hasPublishTime()) {
            responseBuilder.header("X-Pulsar-publish-time", DateFormatter.format(metadata.getPublishTime()));
        }
        if (metadata.hasEventTime()) {
            responseBuilder.header("X-Pulsar-event-time", DateFormatter.format(metadata.getEventTime()));
        }
        if (metadata.hasNumMessagesInBatch()) {
            responseBuilder.header("X-Pulsar-num-batch-message", metadata.getNumMessagesInBatch());
        }

        // Decode if needed
        CompressionCodec codec = CompressionCodecProvider.getCompressionCodec(metadata.getCompression());
        ByteBuf uncompressedPayload = codec.decode(metadataAndPayload, metadata.getUncompressedSize());

        // Copy into a heap buffer for output stream compatibility
        ByteBuf data = PooledByteBufAllocator.DEFAULT.heapBuffer(uncompressedPayload.readableBytes(),
                uncompressedPayload.readableBytes());
        data.writeBytes(uncompressedPayload);
        uncompressedPayload.release();

        StreamingOutput stream = new StreamingOutput() {

            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException {
                output.write(data.array(), data.arrayOffset(), data.readableBytes());
                data.release();
            }
        };

        return responseBuilder.entity(stream).build();
    } catch (NullPointerException npe) {
        throw new RestException(Status.NOT_FOUND, "Message not found");
    } catch (Exception exception) {
        log.error("[{}] Failed to get message at position {} from {} {}", clientAppId(), messagePosition,
                topicName, subName, exception);
        throw new RestException(exception);
    } finally {
        if (entry != null) {
            entry.release();
        }
    }
}

From source file:org.apache.pulsar.broker.stats.prometheus.PrometheusMetricsGenerator.java

License:Apache License

public static void generate(PulsarService pulsar, OutputStream out) throws IOException {
    ByteBuf buf = ByteBufAllocator.DEFAULT.heapBuffer();
    try {/* w ww  .ja  va2 s.co m*/
        SimpleTextOutputStream stream = new SimpleTextOutputStream(buf);

        generateSystemMetrics(stream, pulsar.getConfiguration().getClusterName());

        NamespaceStatsAggregator.generate(pulsar, stream);

        out.write(buf.array(), buf.arrayOffset(), buf.readableBytes());
    } finally {
        buf.release();
    }
}

From source file:org.apache.pulsar.functions.worker.rest.api.FunctionsMetricsResource.java

License:Apache License

@Path("metrics")
@GET/*ww w . ja  v a2  s. c o  m*/
@Produces(MediaType.TEXT_PLAIN)
public Response getMetrics() {

    WorkerService workerService = get();

    ByteBuf buf = ByteBufAllocator.DEFAULT.heapBuffer();
    try {
        SimpleTextOutputStream stream = new SimpleTextOutputStream(buf);
        FunctionsStatsGenerator.generate(workerService, "default", stream);
        byte[] payload = buf.array();
        int arrayOffset = buf.arrayOffset();
        int readableBytes = buf.readableBytes();
        StreamingOutput streamOut = out -> {
            out.write(payload, arrayOffset, readableBytes);
            out.flush();
        };
        return Response.ok(streamOut).type(MediaType.TEXT_PLAIN_TYPE).build();
    } finally {
        buf.release();
    }
}

From source file:org.apache.qpid.jms.provider.amqp.AmqpFixedProducer.java

License:Apache License

private void doSend(JmsOutboundMessageDispatch envelope, AsyncResult request) throws IOException, JMSException {
    // If the transaction has failed due to remote termination etc then we just indicate
    // the send has succeeded until the a new transaction is started.
    if (session.isTransacted() && session.isTransactionFailed()) {
        request.onSuccess();/* w  ww  .j ava  2s  .  c  o m*/
        return;
    }

    LOG.trace("Producer sending message: {}", envelope);

    boolean presettle = envelope.isPresettle() || isPresettle();
    Delivery delivery = null;

    if (presettle) {
        delivery = getEndpoint().delivery(EMPTY_BYTE_ARRAY, 0, 0);
    } else {
        byte[] tag = tagGenerator.getNextTag();
        delivery = getEndpoint().delivery(tag, 0, tag.length);
    }

    if (session.isTransacted()) {
        AmqpTransactionContext context = session.getTransactionContext();
        delivery.disposition(context.getTxnEnrolledState());
        context.registerTxProducer(this);
    }

    // Write the already encoded AMQP message into the Sender
    ByteBuf encoded = (ByteBuf) envelope.getPayload();
    getEndpoint().send(encoded.array(), encoded.arrayOffset() + encoded.readerIndex(), encoded.readableBytes());

    AmqpProvider provider = getParent().getProvider();

    InFlightSend send = null;
    if (request instanceof InFlightSend) {
        send = (InFlightSend) request;
    } else {
        send = new InFlightSend(envelope, request);

        if (!presettle && getSendTimeout() != JmsConnectionInfo.INFINITE) {
            send.requestTimeout = getParent().getProvider().scheduleRequestTimeout(send, getSendTimeout(),
                    send);
        }
    }

    if (presettle) {
        delivery.settle();
    } else {
        sent.put(envelope.getMessageId(), send);
        getEndpoint().advance();
    }

    send.setDelivery(delivery);
    delivery.setContext(send);

    // Put it on the wire and let it fail if the connection is broken, if it does
    // get written then continue on to determine when we should complete it.
    if (provider.pumpToProtonTransport(request)) {
        // For presettled messages we can just mark as successful and we are done, but
        // for any other message we still track it until the remote settles.  If the send
        // was tagged as asynchronous we must mark the original request as complete but
        // we still need to wait for the disposition before we can consider the send as
        // having been successful.
        if (presettle) {
            send.onSuccess();
        } else if (envelope.isSendAsync()) {
            send.getOriginalRequest().onSuccess();
        }
    }
}

From source file:org.apache.qpid.jms.provider.amqp.message.AmqpJmsBytesMessageFacade.java

License:Apache License

@Override
public void reset() {
    if (bytesOut != null) {
        ByteBuf writeBuf = bytesOut.buffer();
        Binary body = new Binary(writeBuf.array(), writeBuf.arrayOffset(), writeBuf.readableBytes());
        setBody(new Data(body));
        try {//from  ww  w  . jav  a  2  s . c o  m
            bytesOut.close();
        } catch (IOException e) {
        }
        bytesOut = null;
    } else if (bytesIn != null) {
        try {
            bytesIn.close();
        } catch (IOException e) {
        }
        bytesIn = null;
    }
}

From source file:org.apache.qpid.jms.provider.amqp.message.AmqpReadableBufferTest.java

License:Apache License

@Test
public void testArrayAccess() {
    ByteBuf byteBuffer = Unpooled.buffer(100, 100);
    AmqpReadableBuffer buffer = new AmqpReadableBuffer(byteBuffer);

    assertTrue(buffer.hasArray());// ww  w  .  j a  v a 2  s  . co  m
    assertSame(buffer.array(), byteBuffer.array());
    assertEquals(buffer.arrayOffset(), byteBuffer.arrayOffset());
}

From source file:org.asynchttpclient.providers.netty4.util.ByteBufUtil.java

License:Apache License

public static byte[] byteBuf2bytes(ByteBuf b) {
    int readable = b.readableBytes();
    int readerIndex = b.readerIndex();
    if (b.hasArray()) {
        byte[] array = b.array();
        if (b.arrayOffset() == 0 && readerIndex == 0 && array.length == readable) {
            return array;
        }/* w ww .j a  va 2 s .  c  om*/
    }
    byte[] array = new byte[readable];
    b.getBytes(readerIndex, array);
    return array;
}

From source file:org.enderstone.server.packet.NetworkEncrypter.java

License:Open Source License

protected ByteBuf decrypt(ChannelHandlerContext ctx, ByteBuf inbytes) throws ShortBufferException {
    int readableBytes = inbytes.readableBytes();
    byte[] byteArray = fillInBuffer(inbytes);
    ByteBuf localByteBuf = ctx.alloc().heapBuffer(this.cipher.getOutputSize(readableBytes));
    localByteBuf.writerIndex(/*from  w w w  .  j  ava 2s.  c  o m*/
            this.cipher.update(byteArray, 0, readableBytes, localByteBuf.array(), localByteBuf.arrayOffset()));
    return localByteBuf;
}

From source file:org.fiware.kiara.netty.Buffers.java

License:Open Source License

public static ByteBuffer toByteBuffer(ByteBuf msg) {
    final byte[] array;
    final int offset;
    final int length = msg.readableBytes();
    if (msg.hasArray()) {
        array = msg.array();/* ww w .j a v  a  2 s. c o m*/
        offset = msg.arrayOffset() + msg.readerIndex();
    } else {
        array = new byte[length];
        msg.getBytes(msg.readerIndex(), array, 0, length);
        offset = 0;
    }

    return ByteBuffer.wrap(array, offset, length);
}