List of usage examples for io.netty.buffer PooledByteBufAllocator DEFAULT
PooledByteBufAllocator DEFAULT
To view the source code for io.netty.buffer PooledByteBufAllocator DEFAULT.
Click Source Link
From source file:org.apache.activemq.artemis.protocol.amqp.broker.AMQPMessage.java
License:Apache License
private ReadableBuffer createCopyWithoutDeliveryAnnotations() { assert headerEnds != messagePaylodStart; // The original message had delivery annotations and so we must copy into a new // buffer skipping the delivery annotations section as that is not meant to survive // beyond this hop. ReadableBuffer duplicate = data.duplicate(); final ByteBuf result = PooledByteBufAllocator.DEFAULT.heapBuffer(getEncodeSize()); result.writeBytes(duplicate.limit(headerEnds).byteBuffer()); duplicate.clear();/* www . j av a2 s. c o m*/ duplicate.position(messagePaylodStart); result.writeBytes(duplicate.byteBuffer()); return new NettyReadable(result); }
From source file:org.apache.activemq.artemis.protocol.amqp.broker.AMQPMessage.java
License:Apache License
private ReadableBuffer createCopyWithNewDeliveryCount(int deliveryCount) { assert deliveryCount > 1; final int amqpDeliveryCount = deliveryCount - 1; // If the re-delivering the message then the header must be re-encoded // (or created if not previously present). Any delivery annotations should // be skipped as well in the resulting buffer. final ByteBuf result = PooledByteBufAllocator.DEFAULT.heapBuffer(getEncodeSize()); Header header = getHeader();/* w ww . j a va2 s. c o m*/ if (header == null) { header = new Header(); header.setDurable(durable); } synchronized (header) { // Updates or adds a Header section with the correct delivery count header.setDeliveryCount(UnsignedInteger.valueOf(amqpDeliveryCount)); TLSEncode.getEncoder().setByteBuffer(new NettyWritable(result)); TLSEncode.getEncoder().writeObject(header); TLSEncode.getEncoder().setByteBuffer((WritableBuffer) null); } // This will skip any existing delivery annotations that might have been present // in the original message. data.position(messagePaylodStart); result.writeBytes(data.byteBuffer()); data.position(0); return new NettyReadable(result); }
From source file:org.apache.activemq.artemis.protocol.amqp.converter.AmqpCoreConverter.java
License:Apache License
@SuppressWarnings("unchecked") public static ICoreMessage toCore(AMQPMessage message, CoreMessageObjectPools coreMessageObjectPools) throws Exception { Section body = message.getProtonMessage().getBody(); ServerJMSMessage result;/*from w ww. java 2s .c om*/ if (body == null) { if (isContentType(SERIALIZED_JAVA_OBJECT_CONTENT_TYPE.toString(), message.getProtonMessage())) { result = createObjectMessage(message.getMessageID(), coreMessageObjectPools); } else if (isContentType(OCTET_STREAM_CONTENT_TYPE, message.getProtonMessage()) || isContentType(null, message.getProtonMessage())) { result = createBytesMessage(message.getMessageID(), coreMessageObjectPools); } else { Charset charset = getCharsetForTextualContent(message.getProtonMessage().getContentType()); if (charset != null) { result = createTextMessage(message.getMessageID(), coreMessageObjectPools); } else { result = createMessage(message.getMessageID(), coreMessageObjectPools); } } result.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, AMQP_NULL); } else if (body instanceof Data) { Binary payload = ((Data) body).getValue(); if (isContentType(SERIALIZED_JAVA_OBJECT_CONTENT_TYPE.toString(), message.getProtonMessage())) { result = createObjectMessage(message.getMessageID(), payload.getArray(), payload.getArrayOffset(), payload.getLength(), coreMessageObjectPools); } else if (isContentType(OCTET_STREAM_CONTENT_TYPE, message.getProtonMessage())) { result = createBytesMessage(message.getMessageID(), payload.getArray(), payload.getArrayOffset(), payload.getLength(), coreMessageObjectPools); } else { Charset charset = getCharsetForTextualContent(message.getProtonMessage().getContentType()); if (StandardCharsets.UTF_8.equals(charset)) { ByteBuffer buf = ByteBuffer.wrap(payload.getArray(), payload.getArrayOffset(), payload.getLength()); try { CharBuffer chars = charset.newDecoder().decode(buf); result = createTextMessage(message.getMessageID(), String.valueOf(chars), coreMessageObjectPools); } catch (CharacterCodingException e) { result = createBytesMessage(message.getMessageID(), payload.getArray(), payload.getArrayOffset(), payload.getLength(), coreMessageObjectPools); } } else { result = createBytesMessage(message.getMessageID(), payload.getArray(), payload.getArrayOffset(), payload.getLength(), coreMessageObjectPools); } } result.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, AMQP_DATA); } else if (body instanceof AmqpSequence) { AmqpSequence sequence = (AmqpSequence) body; ServerJMSStreamMessage m = createStreamMessage(message.getMessageID(), coreMessageObjectPools); for (Object item : sequence.getValue()) { m.writeObject(item); } result = m; result.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, AMQP_SEQUENCE); } else if (body instanceof AmqpValue) { Object value = ((AmqpValue) body).getValue(); if (value == null || value instanceof String) { result = createTextMessage(message.getMessageID(), (String) value, coreMessageObjectPools); result.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, value == null ? AMQP_VALUE_NULL : AMQP_VALUE_STRING); } else if (value instanceof Binary) { Binary payload = (Binary) value; if (isContentType(SERIALIZED_JAVA_OBJECT_CONTENT_TYPE.toString(), message.getProtonMessage())) { result = createObjectMessage(message.getMessageID(), payload, coreMessageObjectPools); } else { result = createBytesMessage(message.getMessageID(), payload.getArray(), payload.getArrayOffset(), payload.getLength(), coreMessageObjectPools); } result.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, AMQP_VALUE_BINARY); } else if (value instanceof List) { ServerJMSStreamMessage m = createStreamMessage(message.getMessageID(), coreMessageObjectPools); for (Object item : (List<Object>) value) { m.writeObject(item); } result = m; result.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, AMQP_VALUE_LIST); } else if (value instanceof Map) { result = createMapMessage(message.getMessageID(), (Map<String, Object>) value, coreMessageObjectPools); result.setShortProperty(JMS_AMQP_ORIGINAL_ENCODING, AMQP_VALUE_MAP); } else { ByteBuf buf = PooledByteBufAllocator.DEFAULT.heapBuffer(1024); try { TLSEncode.getEncoder().setByteBuffer(new NettyWritable(buf)); TLSEncode.getEncoder().writeObject(body); result = createBytesMessage(message.getMessageID(), buf.array(), 0, buf.writerIndex(), coreMessageObjectPools); } finally { buf.release(); TLSEncode.getEncoder().setByteBuffer((WritableBuffer) null); } } } else { throw new RuntimeException("Unexpected body type: " + body.getClass()); } TypedProperties properties = message.getExtraProperties(); if (properties != null) { for (SimpleString str : properties.getPropertyNames()) { if (str.equals(AMQPMessage.ADDRESS_PROPERTY)) { continue; } result.getInnerMessage().putBytesProperty(str, properties.getBytesProperty(str)); } } populateMessage(result, message.getProtonMessage()); result.getInnerMessage().setReplyTo(message.getReplyTo()); result.getInnerMessage().setDurable(message.isDurable()); result.getInnerMessage().setPriority(message.getPriority()); result.getInnerMessage().setAddress(message.getAddressSimpleString()); result.encode(); return result != null ? result.getInnerMessage() : null; }
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 w w 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.converter.message.JMSTransformationSpeedComparisonTest.java
License:Apache License
private void encode(AMQPMessage target) { ByteBuf buf = PooledByteBufAllocator.DEFAULT.heapBuffer(1024); try {/*from www .java 2 s . c om*/ target.sendBuffer(buf, 1); } finally { buf.release(); } }
From source file:org.apache.activemq.artemis.protocol.amqp.proton.handler.ProtonHandler.java
License:Apache License
public void flushBytes() { for (EventHandler handler : handlers) { if (!handler.flowControl(readyListener)) { return; }/*from w ww . j av a 2 s .c o m*/ } lock.lock(); try { while (true) { ByteBuffer head = transport.head(); int pending = head.remaining(); if (pending <= 0) { break; } // We allocated a Pooled Direct Buffer, that will be sent down the stream ByteBuf buffer = PooledByteBufAllocator.DEFAULT.directBuffer(pending); buffer.writeBytes(head); for (EventHandler handler : handlers) { handler.pushBytes(buffer); } transport.pop(pending); } } finally { lock.unlock(); } }
From source file:org.apache.activemq.artemis.protocol.amqp.proton.ProtonServerReceiverContext.java
License:Apache License
@Override public void onMessage(Delivery delivery) throws ActiveMQAMQPException { Receiver receiver;//www . ja v a2 s . c o m try { receiver = ((Receiver) delivery.getLink()); if (!delivery.isReadable()) { return; } if (delivery.isPartial()) { return; } ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(10 * 1024); try { synchronized (connection.getLock()) { DeliveryUtil.readDelivery(receiver, buffer); receiver.advance(); Transaction tx = null; if (delivery.getRemoteState() instanceof TransactionalState) { TransactionalState txState = (TransactionalState) delivery.getRemoteState(); tx = this.sessionSPI.getTransaction(txState.getTxnId()); } sessionSPI.serverSend(tx, receiver, delivery, address, delivery.getMessageFormat(), buffer); flow(maxCreditAllocation, minCreditRefresh); } } finally { buffer.release(); } } catch (Exception e) { log.warn(e.getMessage(), e); Rejected rejected = new Rejected(); ErrorCondition condition = new ErrorCondition(); condition.setCondition(Symbol.valueOf("failed")); condition.setDescription(e.getMessage()); rejected.setError(condition); delivery.disposition(rejected); } }
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 w w w.j a v a 2 s . c om 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.proton.ProtonTransactionHandler.java
License:Apache License
@Override public void onMessage(Delivery delivery) throws ActiveMQAMQPException { ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024); final Receiver receiver; try {//ww w. j a v a 2 s. c o m receiver = ((Receiver) delivery.getLink()); if (!delivery.isReadable()) { return; } DeliveryUtil.readDelivery(receiver, buffer); receiver.advance(); MessageImpl msg = DeliveryUtil.decodeMessageImpl(buffer); Object action = ((AmqpValue) msg.getBody()).getValue(); if (action instanceof Declare) { Binary txID = sessionSPI.newTransaction(); Declared declared = new Declared(); declared.setTxnId(txID); delivery.disposition(declared); delivery.settle(); } else if (action instanceof Discharge) { Discharge discharge = (Discharge) action; Binary txID = discharge.getTxnId(); if (discharge.getFail()) { try { sessionSPI.rollbackTX(txID, true); delivery.disposition(new Accepted()); } catch (Exception e) { throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.errorRollingbackCoordinator(e.getMessage()); } } else { try { sessionSPI.commitTX(txID); delivery.disposition(new Accepted()); } catch (ActiveMQAMQPException amqpE) { throw amqpE; } catch (Exception e) { throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.errorCommittingCoordinator(e.getMessage()); } } } } catch (ActiveMQAMQPException amqpE) { delivery.disposition(createRejected(amqpE.getAmqpError(), amqpE.getMessage())); } catch (Exception e) { log.warn(e.getMessage(), e); delivery.disposition(createRejected(Symbol.getSymbol("failed"), e.getMessage())); } finally { delivery.settle(); buffer.release(); } }
From source file:org.apache.activemq.artemis.protocol.amqp.proton.transaction.ProtonTransactionHandler.java
License:Apache License
@Override public void onMessage(Delivery delivery) throws ActiveMQAMQPException { ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(1024); final Receiver receiver; try {//w w w . ja v a 2s . com receiver = ((Receiver) delivery.getLink()); if (!delivery.isReadable()) { return; } receiver.recv(new NettyWritable(buffer)); receiver.advance(); MessageImpl msg = DeliveryUtil.decodeMessageImpl(buffer); Object action = ((AmqpValue) msg.getBody()).getValue(); if (action instanceof Declare) { Binary txID = sessionSPI.newTransaction(); Declared declared = new Declared(); declared.setTxnId(txID); delivery.disposition(declared); } else if (action instanceof Discharge) { Discharge discharge = (Discharge) action; Binary txID = discharge.getTxnId(); sessionSPI.dischargeTx(txID); if (discharge.getFail()) { try { sessionSPI.rollbackTX(txID, true); delivery.disposition(new Accepted()); } catch (Exception e) { throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.errorRollingbackCoordinator(e.getMessage()); } } else { try { sessionSPI.commitTX(txID); delivery.disposition(new Accepted()); } catch (ActiveMQAMQPException amqpE) { throw amqpE; } catch (Exception e) { throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.errorCommittingCoordinator(e.getMessage()); } } } } catch (ActiveMQAMQPException amqpE) { delivery.disposition(createRejected(amqpE.getAmqpError(), amqpE.getMessage())); } catch (Exception e) { log.warn(e.getMessage(), e); delivery.disposition(createRejected(Symbol.getSymbol("failed"), e.getMessage())); } finally { delivery.settle(); buffer.release(); } }