use of com.swiftmq.amqp.v100.messaging.AMQPMessage in project swiftmq-client by iitsoftware.
the class Producer method send.
/**
* Send a message to the target. For transactional sends the method returns after settlement has been finished, otherwise when the message has been sent.
*
* @param msg message
* @param persistent whether the message should send/stored durable
* @param priority message priority (default is 5)
* @param ttl time to live (expiration) in milliseconds, default no expiration
* @return delivery state of the message
* @throws AMQPException on error
*/
public DeliveryStateIF send(AMQPMessage msg, boolean persistent, int priority, long ttl) throws AMQPException {
verifyState();
Header header = msg.getHeader();
if (header == null) {
header = new Header();
msg.setHeader(header);
}
header.setDurable(new AMQPBoolean(persistent));
header.setPriority(new AMQPUnsignedByte(priority));
if (ttl >= 0)
header.setTtl(new Milliseconds(ttl));
Properties props = msg.getProperties();
if (props == null) {
props = new Properties();
msg.setProperties(props);
}
if (props.getMessageId() == null)
props.setMessageId(new MessageIdString(nextMsgId()));
props.setTo(new AddressString(target));
String userName = mySession.myConnection.getUserName();
if (userName != null)
props.setUserId(new AMQPBinary(userName.getBytes()));
Semaphore sem = new Semaphore();
try {
POSendMessage po = new POSendMessage(sem, this, msg, msg.getTxnIdIF(), msg.getDeliveryTag());
mySession.dispatch(po);
sem.waitHere();
if (!po.isSuccess())
throw new AMQPException(po.getException());
return po.getDeliveryState();
} catch (Exception e) {
e.printStackTrace();
throw new AMQPException(e.toString());
}
}
use of com.swiftmq.amqp.v100.messaging.AMQPMessage in project swiftmq-client by iitsoftware.
the class Producer method recover.
protected void recover(AMQPMap remoteUnsettled) {
try {
if (remoteUnsettled != null) {
Map<AMQPType, AMQPType> map = remoteUnsettled.getValue();
for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
final DeliveryTag deliveryTag = new DeliveryTag(((AMQPBinary) entry.getKey()).getValue());
final AMQPList deliveryState = (AMQPList) entry.getValue();
if (deliveryState != null) {
try {
DeliveryStateFactory.create(deliveryState).accept(new DeliveryStateVisitorAdapter() {
public void visit(Accepted impl) {
deliveryMemory.deliverySettled(deliveryTag);
mySession.dispatch(new POSendResumedTransfer(Producer.this, deliveryTag));
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
if (deliveryMemory.getNumberUnsettled() > 0) {
Collection<UnsettledDelivery> unsettled = deliveryMemory.getUnsettled();
for (Iterator<UnsettledDelivery> iter = unsettled.iterator(); iter.hasNext(); ) {
UnsettledDelivery unsettledDelivery = iter.next();
if (unsettledDelivery.getMessage() != null) {
AMQPMessage msg = unsettledDelivery.getMessage();
if (msg.getTxnIdIF() == null) {
POSendMessage po = new POSendMessage(null, this, msg, null, unsettledDelivery.getDeliveryTag());
po.setRecovery(true);
mySession.dispatch(po);
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
use of com.swiftmq.amqp.v100.messaging.AMQPMessage in project rabbitmq-stream-java-client by rabbitmq.
the class SwiftMqCodec method encode.
@Override
public EncodedMessage encode(Message message) {
AMQPMessage outboundMessage;
if (message instanceof SwiftMqAmqpMessageWrapper) {
outboundMessage = ((SwiftMqAmqpMessageWrapper) message).message;
} else {
outboundMessage = new AMQPMessage();
if (message.getProperties() != null) {
com.rabbitmq.stream.Properties headers = message.getProperties();
com.swiftmq.amqp.v100.generated.messaging.message_format.Properties properties = new com.swiftmq.amqp.v100.generated.messaging.message_format.Properties();
boolean propertiesSet = false;
if (headers.getMessageId() != null) {
if (headers.getMessageId() instanceof String) {
properties.setMessageId(new MessageIdString(headers.getMessageIdAsString()));
} else if (headers.getMessageId().getClass().isPrimitive() || headers.getMessageId() instanceof Long) {
properties.setMessageId(new MessageIdUlong(headers.getMessageIdAsLong()));
} else if (headers.getMessageId().getClass().isArray()) {
properties.setMessageId(new MessageIdBinary(headers.getMessageIdAsBinary()));
} else if (headers.getMessageId() instanceof UUID) {
properties.setMessageId(new MessageIdUuid(headers.getMessageIdAsUuid()));
} else {
throw new IllegalStateException("Type not supported for message ID:" + properties.getMessageId().getClass());
}
propertiesSet = true;
}
if (headers.getUserId() != null) {
properties.setUserId(new AMQPBinary(headers.getUserId()));
propertiesSet = true;
}
if (headers.getTo() != null) {
properties.setTo(new AddressString(headers.getTo()));
propertiesSet = true;
}
if (headers.getSubject() != null) {
properties.setSubject(new AMQPString(headers.getSubject()));
propertiesSet = true;
}
if (headers.getReplyTo() != null) {
properties.setReplyTo(new AddressString(headers.getReplyTo()));
propertiesSet = true;
}
if (headers.getCorrelationId() != null) {
if (headers.getCorrelationId() instanceof String) {
properties.setCorrelationId(new MessageIdString(headers.getCorrelationIdAsString()));
} else if (headers.getCorrelationId().getClass().isPrimitive() || headers.getCorrelationId() instanceof Long) {
properties.setCorrelationId(new MessageIdUlong(headers.getCorrelationIdAsLong()));
} else if (headers.getCorrelationId().getClass().isArray()) {
properties.setCorrelationId(new MessageIdBinary(headers.getCorrelationIdAsBinary()));
} else if (headers.getCorrelationId() instanceof UUID) {
properties.setCorrelationId(new MessageIdUuid(headers.getCorrelationIdAsUuid()));
} else {
throw new IllegalStateException("Type not supported for correlation ID:" + properties.getCorrelationId().getClass());
}
propertiesSet = true;
}
if (headers.getContentType() != null) {
properties.setContentType(new AMQPSymbol(headers.getContentType()));
propertiesSet = true;
}
if (headers.getContentEncoding() != null) {
properties.setContentEncoding(new AMQPSymbol(headers.getContentEncoding()));
propertiesSet = true;
}
if (headers.getAbsoluteExpiryTime() > 0) {
properties.setAbsoluteExpiryTime(new AMQPTimestamp(headers.getAbsoluteExpiryTime()));
propertiesSet = true;
}
if (headers.getCreationTime() > 0) {
properties.setCreationTime(new AMQPTimestamp(headers.getCreationTime()));
propertiesSet = true;
}
if (headers.getGroupId() != null) {
properties.setGroupId(new AMQPString(headers.getGroupId()));
propertiesSet = true;
}
if (headers.getGroupSequence() >= 0) {
properties.setGroupSequence(new SequenceNo(headers.getGroupSequence()));
propertiesSet = true;
}
if (headers.getReplyToGroupId() != null) {
properties.setReplyToGroupId(new AMQPString(headers.getReplyToGroupId()));
propertiesSet = true;
}
if (propertiesSet) {
outboundMessage.setProperties(properties);
}
}
if (message.getApplicationProperties() != null && !message.getApplicationProperties().isEmpty()) {
Map<AMQPType, AMQPType> applicationProperties = new LinkedHashMap<>(message.getApplicationProperties().size());
for (Map.Entry<String, Object> entry : message.getApplicationProperties().entrySet()) {
applicationProperties.put(new AMQPString(entry.getKey()), convertToSwiftMqType(entry.getValue()));
}
try {
outboundMessage.setApplicationProperties(new ApplicationProperties(applicationProperties));
} catch (IOException e) {
throw new StreamException("Error while setting application properties", e);
}
}
if (message.getMessageAnnotations() != null && !message.getMessageAnnotations().isEmpty()) {
Map<AMQPType, AMQPType> messageAnnotations = new LinkedHashMap<>(message.getMessageAnnotations().size());
for (Map.Entry<String, Object> entry : message.getMessageAnnotations().entrySet()) {
messageAnnotations.put(new AMQPSymbol(entry.getKey()), convertToSwiftMqType(entry.getValue()));
}
try {
outboundMessage.setMessageAnnotations(new MessageAnnotations(messageAnnotations));
} catch (IOException e) {
throw new StreamException("Error while setting message annotations", e);
}
}
if (message.getBodyAsBinary() != null) {
outboundMessage.addData(new Data(message.getBodyAsBinary()));
}
}
try {
int bufferSize;
// FIXME estimate the size with all message data
if (outboundMessage.getData() != null && !outboundMessage.getData().isEmpty()) {
bufferSize = outboundMessage.getData().get(0).getPredictedSize();
} else {
bufferSize = 8192;
}
DataByteArrayOutputStream output = new DataByteArrayOutputStream(bufferSize);
outboundMessage.writeContent(output);
return new EncodedMessage(output.getCount(), output.getBuffer());
} catch (IOException e) {
throw new StreamException("Error while writing AMQP 1.0 message to output stream");
}
}
use of com.swiftmq.amqp.v100.messaging.AMQPMessage in project activemq by apache.
the class SwiftMQClientTest method testSendReceive.
@Test
public void testSendReceive() throws Exception {
String queue = "testqueue";
int nMsgs = 100;
final String dataFormat = "%01024d";
int qos = QoS.AT_MOST_ONCE;
AMQPContext ctx = new AMQPContext(AMQPContext.CLIENT);
try {
Connection connection = new Connection(ctx, "127.0.0.1", port, false);
connection.setContainerId("client");
connection.setIdleTimeout(-1);
connection.setMaxFrameSize(1024 * 4);
connection.setExceptionListener(new ExceptionListener() {
public void onException(Exception e) {
e.printStackTrace();
}
});
connection.connect();
{
Session session = connection.createSession(10, 10);
Producer p = session.createProducer(queue, qos);
for (int i = 0; i < nMsgs; i++) {
AMQPMessage msg = new AMQPMessage();
System.out.println("Sending " + i);
msg.setAmqpValue(new AmqpValue(new AMQPString(String.format(dataFormat, i))));
p.send(msg);
}
p.close();
session.close();
}
System.out.println("=======================================================================================");
System.out.println(" receiving ");
System.out.println("=======================================================================================");
{
Session session = connection.createSession(10, 10);
Consumer c = session.createConsumer(queue, 100, qos, true, null);
// Receive messages non-transacted
int i = 0;
while (i < nMsgs) {
AMQPMessage msg = c.receive();
if (msg != null) {
final AMQPType value = msg.getAmqpValue().getValue();
if (value instanceof AMQPString) {
String s = ((AMQPString) value).getValue();
assertEquals(String.format(dataFormat, i), s);
System.out.println("Received: " + i);
}
if (!msg.isSettled())
msg.accept();
i++;
}
}
c.close();
session.close();
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
use of com.swiftmq.amqp.v100.messaging.AMQPMessage in project swiftmq-ce by iitsoftware.
the class SessionHandler method doSendOneMessage.
private void doSendOneMessage(SourceMessageProcessor sourceMessageProcessor, SourceLink sourceLink, Delivery delivery, boolean restart) throws EndWithErrorException {
try {
if (remoteIncomingWindow > 0 && outgoingWindow > 0) {
do {
boolean wasFirstPacket = false;
delivery.setMaxFrameSize(amqpHandler.getMaxFrameSize());
TransferFrame frame = new TransferFrame(channel);
frame.setHandle(new Handle(sourceLink.getHandle()));
frame.setSettled(new AMQPBoolean(sourceLink.getSndSettleMode() == SenderSettleMode.SETTLED.getValue()));
if (delivery.getCurrentPacketNumber() == 0) {
if (ctx.traceSpace.enabled)
ctx.traceSpace.trace(ctx.amqpSwiftlet.getName(), toString() + ", doSendOneMessage, amqpMessage=" + delivery.getAmqpMessage());
long totalSize = delivery.getSize();
wasFirstPacket = true;
sourceLink.incDeliveryCountSnd();
long dId = nextDeliveryId();
frame.setDeliveryId(new DeliveryNumber(dId));
frame.setDeliveryTag(createDeliveryTag(delivery));
TxnIdIF currentTx = sourceLink.getCurrentTx();
if (currentTx != null) {
TransactionalState tState = new TransactionalState();
tState.setTxnId(currentTx);
frame.setState(tState);
transactionRegistry.addToTransaction(currentTx, sourceLink, dId, delivery.getMessageIndex(), totalSize);
totalSize = 0;
}
if (!frame.getSettled().getValue()) {
unsettledOutgoingDeliveries.put(dId, sourceLink);
if (totalSize > 0)
sourceLink.addUnsettled(dId, delivery.getMessageIndex(), totalSize);
else
sourceLink.addUnsettled(dId, delivery.getMessageIndex());
} else {
sourceLink.autoack(delivery.getMessageIndex());
}
incMsgsSent(1);
}
delivery.getNextPacket(frame);
// We may increase the outgoing window and send a flow before
if (wasFirstPacket && outgoingWindow - delivery.getPredictedNumberPackets() < 0) {
outgoingWindow += delivery.getPredictedNumberPackets();
sendFlow();
windowChanged = true;
}
if (ctx.traceSpace.enabled)
ctx.traceSpace.trace(ctx.amqpSwiftlet.getName(), toString() + ", doSendOneMessage, remoteIncomingWindows=" + remoteIncomingWindow + ", outgoingWindow=" + outgoingWindow + ", sending message, wasFirstPacket=" + wasFirstPacket + ", maxSize=" + delivery.getMaxPayloadLength() + ", packetSize=" + frame.getPayload().length + ", predictedNumberPackets=" + delivery.getPredictedNumberPackets() + ", currentPacket=" + delivery.getCurrentPacketNumber() + ", hasMore=" + delivery.hasMore());
versionedConnection.send(frame);
if (!frame.getSettled().getValue())
outgoingWindow--;
nextOutgoingId++;
remoteIncomingWindow--;
if (!delivery.hasMore()) {
if (restart) {
if (sourceLink.getLinkCredit() > 0)
sourceLink.startMessageProcessor(sourceMessageProcessor);
else
sourceLink.clearMessageProcessor();
}
// If that was the last packet and outgoing window was increased for this message, we need to reset it and send another flow
if (windowChanged) {
outgoingWindow = initialOutgoingWindow;
sendFlow();
}
break;
}
} while (remoteIncomingWindow > 0 && outgoingWindow > 0);
if (delivery.hasMore()) {
if (ctx.traceSpace.enabled)
ctx.traceSpace.trace(ctx.amqpSwiftlet.getName(), toString() + ", doSendOneMessage, remoteIncomingWindows=" + remoteIncomingWindow + ", outgoingWindow=" + outgoingWindow + ", has more but no window, storing message");
outboundDeliveries.add(new OutboundDelivery(sourceMessageProcessor, sourceLink, delivery, restart));
}
} else {
if (ctx.traceSpace.enabled)
ctx.traceSpace.trace(ctx.amqpSwiftlet.getName(), toString() + ", doSendOneMessage, no remote incoming window = " + remoteIncomingWindow + ", outgoingWindow=" + outgoingWindow + ", store for later transfer");
outboundDeliveries.add(new OutboundDelivery(sourceMessageProcessor, sourceLink, delivery, restart));
}
} catch (IOException e) {
throw new ConnectionEndException(AmqpError.INTERNAL_ERROR, new AMQPString("IOException during outbound send: " + e.getMessage()));
} catch (QueueException e) {
throw new ConnectionEndException(AmqpError.INTERNAL_ERROR, new AMQPString("QueueException during outbound send: " + e.getMessage()));
}
}
Aggregations