Example usage for io.netty.buffer ByteBuf writerIndex

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

Introduction

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

Prototype

public abstract int writerIndex();

Source Link

Document

Returns the writerIndex of this buffer.

Usage

From source file:org.apache.activemq.artemis.core.protocol.proton.TestConversions.java

License:Apache License

private EncodedMessage encodeMessage(MessageImpl message) {
    ByteBuf buf = PooledByteBufAllocator.DEFAULT.heapBuffer(1024 * 1024);
    message.encode(new NettyWritable(buf));
    byte[] bytesConvert = new byte[buf.writerIndex()];
    buf.readBytes(bytesConvert);/*from  w  ww  .j av a2s. c  o m*/
    return new EncodedMessage(0, bytesConvert, 0, bytesConvert.length);
}

From source file:org.apache.activemq.artemis.protocol.amqp.broker.AMQPMessage.java

License:Apache License

private void encodeProtonMessage() {
    int estimated = Math.max(1500, data != null ? data.capacity() + 1000 : 0);
    ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(estimated);
    try {/*from  w w  w .  j av  a 2s. co  m*/
        getProtonMessage().encode(new NettyWritable(buffer));
        byte[] bytes = new byte[buffer.writerIndex()];
        buffer.readBytes(bytes);
        this.data = ReadableBuffer.ByteBufferReader.wrap(ByteBuffer.wrap(bytes));
    } finally {
        buffer.release();
    }
}

From source file:org.apache.activemq.artemis.protocol.amqp.broker.AMQPMessageTest.java

License:Apache License

private ActiveMQBuffer encodeMessageAsPersistedBuffer(MessageImpl message) {
    ByteBuf nettyBuffer = Unpooled.buffer(1500);

    message.encode(new NettyWritable(nettyBuffer));
    byte[] bytes = new byte[nettyBuffer.writerIndex() + Integer.BYTES];
    nettyBuffer.readBytes(bytes, Integer.BYTES, nettyBuffer.readableBytes());

    ActiveMQBuffer buffer = ActiveMQBuffers.wrappedBuffer(bytes);
    buffer.writerIndex(0);//from  w w  w . j av  a  2s .c o  m
    buffer.writeInt(bytes.length - Integer.BYTES);
    buffer.setIndex(0, bytes.length);

    return buffer;
}

From source file:org.apache.activemq.artemis.protocol.amqp.broker.AMQPMessageTest.java

License:Apache License

private byte[] encodeMessage(MessageImpl message) {
    ByteBuf nettyBuffer = Unpooled.buffer(1500);

    message.encode(new NettyWritable(nettyBuffer));
    byte[] bytes = new byte[nettyBuffer.writerIndex()];
    nettyBuffer.readBytes(bytes);/*from ww w  . ja  v  a 2 s .  co m*/

    return bytes;
}

From source file:org.apache.activemq.artemis.protocol.amqp.broker.AMQPMessageTest.java

License:Apache License

private AMQPMessage encodeAndDecodeMessage(MessageImpl message) {
    ByteBuf nettyBuffer = Unpooled.buffer(1500);

    message.encode(new NettyWritable(nettyBuffer));
    byte[] bytes = new byte[nettyBuffer.writerIndex()];
    nettyBuffer.readBytes(bytes);/*w w w .  j  a v a2 s .  co  m*/

    return new AMQPMessage(0, bytes, null);
}

From source file:org.apache.activemq.artemis.protocol.amqp.broker.AMQPSessionCallback.java

License:Apache License

public void serverSend(final Transaction transaction, final Receiver receiver, final Delivery delivery,
        String address, int messageFormat, ByteBuf messageEncoded) throws Exception {
    EncodedMessage encodedMessage = new EncodedMessage(messageFormat, messageEncoded.array(),
            messageEncoded.arrayOffset(), messageEncoded.writerIndex());

    ServerMessage message = manager.getConverter().inbound(encodedMessage);
    //use the address on the receiver if not null, if null let's hope it was set correctly on the message
    if (address != null) {
        message.setAddress(new SimpleString(address));
    }//from w w  w.ja v  a  2 s .co  m

    recoverContext();

    PagingStore store = manager.getServer().getPagingManager().getPageStore(message.getAddress());
    if (store.isRejectingMessages()) {
        // We drop pre-settled messages (and abort any associated Tx)
        if (delivery.remotelySettled()) {
            if (transaction != null) {
                String amqpAddress = delivery.getLink().getTarget().getAddress();
                ActiveMQException e = new ActiveMQAMQPResourceLimitExceededException(
                        "Address is full: " + amqpAddress);
                transaction.markAsRollbackOnly(e);
            }
        } else {
            rejectMessage(delivery);
        }
    } else {
        serverSend(transaction, message, delivery, receiver);
    }
}

From source file:org.apache.activemq.artemis.protocol.amqp.converter.CoreAmqpConverter.java

License:Apache License

public static AMQPMessage fromCore(ICoreMessage coreMessage) throws Exception {
    if (coreMessage == null) {
        return null;
    }/*from   ww  w.  j a v a  2 s  .c  o m*/

    ServerJMSMessage message = ServerJMSMessage.wrapCoreMessage(coreMessage);
    message.decode();

    long messageFormat = 0;
    Header header = null;
    final Properties properties = new Properties();
    Map<Symbol, Object> daMap = null;
    final Map<Symbol, Object> maMap = new HashMap<>();
    Map<String, Object> apMap = null;
    Map<Object, Object> footerMap = null;

    Section body = convertBody(message, maMap, properties);

    if (message.getInnerMessage().isDurable()) {
        if (header == null) {
            header = new Header();
        }
        header.setDurable(true);
    }
    byte priority = (byte) message.getJMSPriority();
    if (priority != javax.jms.Message.DEFAULT_PRIORITY) {
        if (header == null) {
            header = new Header();
        }
        header.setPriority(UnsignedByte.valueOf(priority));
    }
    String type = message.getJMSType();
    if (type != null) {
        properties.setSubject(type);
    }
    String messageId = message.getJMSMessageID();
    if (messageId != null) {
        try {
            properties.setMessageId(AMQPMessageIdHelper.INSTANCE.toIdObject(messageId));
        } catch (ActiveMQAMQPIllegalStateException e) {
            properties.setMessageId(messageId);
        }
    }
    Destination destination = message.getJMSDestination();
    if (destination != null) {
        properties.setTo(toAddress(destination));
        maMap.put(JMS_DEST_TYPE_MSG_ANNOTATION, destinationType(destination));
    }
    Destination replyTo = message.getJMSReplyTo();
    if (replyTo != null) {
        properties.setReplyTo(toAddress(replyTo));
        maMap.put(JMS_REPLY_TO_TYPE_MSG_ANNOTATION, destinationType(replyTo));
    }
    String correlationId = message.getJMSCorrelationID();
    if (correlationId != null) {
        try {
            properties.setCorrelationId(AMQPMessageIdHelper.INSTANCE.toIdObject(correlationId));
        } catch (ActiveMQAMQPIllegalStateException e) {
            properties.setCorrelationId(correlationId);
        }
    }
    long expiration = message.getJMSExpiration();
    if (expiration != 0) {
        long ttl = expiration - System.currentTimeMillis();
        if (ttl < 0) {
            ttl = 1;
        }

        if (header == null) {
            header = new Header();
        }
        header.setTtl(new UnsignedInteger((int) ttl));

        properties.setAbsoluteExpiryTime(new Date(expiration));
    }
    long timeStamp = message.getJMSTimestamp();
    if (timeStamp != 0) {
        properties.setCreationTime(new Date(timeStamp));
    }

    final Set<String> keySet = MessageUtil.getPropertyNames(message.getInnerMessage());
    for (String key : keySet) {
        if (key.startsWith("JMSX")) {
            if (key.equals("JMSXUserID")) {
                String value = message.getStringProperty(key);
                properties.setUserId(new Binary(value.getBytes(StandardCharsets.UTF_8)));
                continue;
            } else if (key.equals("JMSXGroupID")) {
                String value = message.getStringProperty(key);
                properties.setGroupId(value);
                continue;
            } else if (key.equals("JMSXGroupSeq")) {
                UnsignedInteger value = new UnsignedInteger(message.getIntProperty(key));
                properties.setGroupSequence(value);
                continue;
            }
        } else if (key.startsWith(JMS_AMQP_PREFIX)) {
            // AMQP Message Information stored from a conversion to the Core Message
            if (key.equals(JMS_AMQP_NATIVE)) {
                // skip..internal use only
                continue;
            } else if (key.equals(JMS_AMQP_FIRST_ACQUIRER)) {
                if (header == null) {
                    header = new Header();
                }
                header.setFirstAcquirer(message.getBooleanProperty(key));
                continue;
            } else if (key.equals(JMS_AMQP_HEADER)) {
                if (header == null) {
                    header = new Header();
                }
                continue;
            } else if (key.equals(JMS_AMQP_HEADER_DURABLE)) {
                if (header == null) {
                    header = new Header();
                }
                header.setDurable(message.getInnerMessage().isDurable());
                continue;
            } else if (key.equals(JMS_AMQP_HEADER_PRIORITY)) {
                if (header == null) {
                    header = new Header();
                }
                header.setPriority(UnsignedByte.valueOf(priority));
                continue;
            } else if (key.startsWith(JMS_AMQP_PROPERTIES)) {
                continue;
            } else if (key.startsWith(JMS_AMQP_DELIVERY_ANNOTATION_PREFIX)) {
                if (daMap == null) {
                    daMap = new HashMap<>();
                }
                String name = key.substring(JMS_AMQP_DELIVERY_ANNOTATION_PREFIX.length());
                daMap.put(Symbol.valueOf(name), message.getObjectProperty(key));
                continue;
            } else if (key.startsWith(JMS_AMQP_MESSAGE_ANNOTATION_PREFIX)) {
                String name = key.substring(JMS_AMQP_MESSAGE_ANNOTATION_PREFIX.length());
                maMap.put(Symbol.valueOf(name), message.getObjectProperty(key));
                continue;
            } else if (key.equals(JMS_AMQP_CONTENT_TYPE)) {
                properties.setContentType(Symbol.getSymbol(message.getStringProperty(key)));
                continue;
            } else if (key.equals(JMS_AMQP_CONTENT_ENCODING)) {
                properties.setContentEncoding(Symbol.getSymbol(message.getStringProperty(key)));
                continue;
            } else if (key.equals(JMS_AMQP_REPLYTO_GROUP_ID)) {
                properties.setReplyToGroupId(message.getStringProperty(key));
                continue;
            } else if (key.equals(JMS_AMQP_ORIGINAL_ENCODING)) {
                // skip..remove annotation from previous inbound transformation
                continue;
            } else if (key.startsWith(JMS_AMQP_FOOTER_PREFIX)) {
                if (footerMap == null) {
                    footerMap = new HashMap<>();
                }
                String name = key.substring(JMS_AMQP_FOOTER_PREFIX.length());
                footerMap.put(name, message.getObjectProperty(key));
                continue;
            }
        } else if (key.equals("_AMQ_GROUP_ID")) {
            String value = message.getStringProperty(key);
            properties.setGroupId(value);
            continue;
        } else if (key.equals(NATIVE_MESSAGE_ID)) {
            // skip..internal use only
            continue;
        } else if (key.endsWith(HDR_SCHEDULED_DELIVERY_TIME.toString())) {
            // skip..remove annotation from previous inbound transformation
            continue;
        }

        if (apMap == null) {
            apMap = new HashMap<>();
        }

        Object objectProperty = message.getObjectProperty(key);
        if (objectProperty instanceof byte[]) {
            objectProperty = new Binary((byte[]) objectProperty);
        }

        apMap.put(key, objectProperty);
    }

    ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024);

    try {
        EncoderImpl encoder = TLSEncode.getEncoder();
        encoder.setByteBuffer(new NettyWritable(buffer));

        if (header != null) {
            encoder.writeObject(header);
        }
        if (daMap != null) {
            encoder.writeObject(new DeliveryAnnotations(daMap));
        }
        if (maMap != null) {
            encoder.writeObject(new MessageAnnotations(maMap));
        }
        if (properties != null) {
            encoder.writeObject(properties);
        }
        if (apMap != null) {
            encoder.writeObject(new ApplicationProperties(apMap));
        }
        if (body != null) {
            encoder.writeObject(body);
        }
        if (footerMap != null) {
            encoder.writeObject(new Footer(footerMap));
        }

        byte[] data = new byte[buffer.writerIndex()];
        buffer.readBytes(data);

        AMQPMessage amqpMessage = new AMQPMessage(messageFormat, data, null);
        amqpMessage.setMessageID(message.getInnerMessage().getMessageID());
        amqpMessage.setReplyTo(coreMessage.getReplyTo());
        return amqpMessage;

    } finally {
        TLSEncode.getEncoder().setByteBuffer((WritableBuffer) null);
        buffer.release();
    }
}

From source file:org.apache.activemq.artemis.protocol.amqp.message.AMQPMessageTest.java

License:Apache License

private AMQPMessage encodeDelivery(AMQPMessage message, int deliveryCount) {
    ByteBuf nettyBuffer = Unpooled.buffer(1500);

    message.sendBuffer(nettyBuffer, deliveryCount);

    byte[] bytes = new byte[nettyBuffer.writerIndex()];
    nettyBuffer.readBytes(bytes);//  w ww.  ja v  a 2  s .c om

    return new AMQPMessage(0, bytes, null);
}

From source file:org.apache.activemq.artemis.protocol.amqp.proton.ProtonServerSenderContext.java

License:Apache License

/**
 * handle an out going message from ActiveMQ Artemis, send via the Proton Sender
 *///from   www. j  av  a  2  s. co  m
public int deliverMessage(MessageReference messageReference, int deliveryCount, Connection transportConnection)
        throws Exception {

    if (closed) {
        return 0;
    }

    AMQPMessage message = CoreAmqpConverter.checkAMQP(messageReference.getMessage());
    sessionSPI.invokeOutgoing(message,
            (ActiveMQProtonRemotingConnection) transportConnection.getProtocolConnection());

    // presettle means we can settle 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 settle later
    byte[] tag = preSettle ? new byte[0] : protonSession.getTag();

    ByteBuf nettyBuffer = PooledByteBufAllocator.DEFAULT.heapBuffer(message.getEncodeSize());
    try {
        message.sendBuffer(nettyBuffer, deliveryCount);

        int size = nettyBuffer.writerIndex();

        while (!connection.tryLock(1, TimeUnit.SECONDS)) {
            if (closed || sender.getLocalState() == EndpointState.CLOSED) {
                // If we're waiting on the connection lock, the link might be in the process of closing.  If this happens
                // we return.
                return 0;
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Couldn't get lock on deliverMessage " + this);
                }
            }
        }

        try {
            final Delivery delivery;
            delivery = sender.delivery(tag, 0, tag.length);
            delivery.setMessageFormat((int) message.getMessageFormat());
            delivery.setContext(messageReference);

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

            if (preSettle) {
                // Presettled means the client implicitly accepts any delivery we send it.
                sessionSPI.ack(null, brokerConsumer, messageReference.getMessage());
                delivery.settle();
            } else {
                sender.advance();
            }
            connection.flush();
        } finally {
            connection.unlock();
        }

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

From source file:org.apache.activemq.artemis.protocol.amqp.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 a2s .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);
        buffer.ensureWritable(count);
    }
    return buffer.writerIndex() - initial;
}