use of org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted in project qpid-broker-j by apache.
the class StandardReceivingLinkEndpoint method receiveDelivery.
@Override
protected Error receiveDelivery(Delivery delivery) {
ReceiverSettleMode transferReceiverSettleMode = delivery.getReceiverSettleMode();
if (delivery.getResume()) {
DeliveryState deliveryState = _unsettled.get(delivery.getDeliveryTag());
if (deliveryState instanceof Outcome) {
boolean settled = shouldReceiverSettleFirst(transferReceiverSettleMode);
updateDisposition(delivery.getDeliveryTag(), deliveryState, settled);
return null;
} else {
// TODO: QPID-7845: create message ?
}
} else {
ServerMessage<?> serverMessage;
UnsignedInteger messageFormat = delivery.getMessageFormat();
DeliveryState xfrState = delivery.getState();
MessageFormat format = MessageFormatRegistry.getFormat(messageFormat.intValue());
if (format != null) {
if (delivery.getTotalPayloadSize() == 0) {
return new Error(AmqpError.NOT_IMPLEMENTED, "Delivery without payload is not supported");
}
try (QpidByteBuffer payload = delivery.getPayload()) {
serverMessage = format.createMessage(payload, getAddressSpace().getMessageStore(), getSession().getConnection().getReference());
} catch (AmqpErrorRuntimeException e) {
return e.getCause().getError();
}
} else {
final Error err = new Error();
err.setCondition(AmqpError.NOT_IMPLEMENTED);
err.setDescription("Unknown message format: " + messageFormat);
return err;
}
MessageReference<?> reference = serverMessage.newReference();
try {
Binary transactionId = null;
if (xfrState != null) {
if (xfrState instanceof TransactionalState) {
transactionId = ((TransactionalState) xfrState).getTxnId();
}
}
final ServerTransaction transaction;
boolean setRollbackOnly = true;
if (transactionId != null) {
try {
transaction = getSession().getTransaction(transactionId);
} catch (UnknownTransactionException e) {
return new Error(TransactionError.UNKNOWN_ID, String.format("transaction-id '%s' is unknown.", transactionId));
}
if (!(transaction instanceof AutoCommitTransaction)) {
transaction.addPostTransactionAction(new ServerTransaction.Action() {
@Override
public void postCommit() {
updateDisposition(delivery.getDeliveryTag(), null, true);
}
@Override
public void onRollback() {
updateDisposition(delivery.getDeliveryTag(), null, true);
}
});
}
} else {
transaction = new AsyncAutoCommitTransaction(getAddressSpace().getMessageStore(), this);
}
try {
Session_1_0 session = getSession();
session.getAMQPConnection().checkAuthorizedMessagePrincipal(serverMessage.getMessageHeader().getUserId());
Outcome outcome;
if (serverMessage.isPersistent() && !getAddressSpace().getMessageStore().isPersistent()) {
final Error preconditionFailedError = new Error(AmqpError.PRECONDITION_FAILED, "Non-durable message store cannot accept durable message.");
if (_rejectedOutcomeSupportedBySource) {
final Rejected rejected = new Rejected();
rejected.setError(preconditionFailedError);
outcome = rejected;
} else {
// TODO - disposition not updated for the non-transaction case
return preconditionFailedError;
}
} else {
try {
getReceivingDestination().send(serverMessage, transaction, session.getSecurityToken());
outcome = ACCEPTED;
} catch (UnroutableMessageException e) {
final Error error = new Error();
error.setCondition(e.getErrorCondition());
error.setDescription(e.getMessage());
String targetAddress = getTarget().getAddress();
if (targetAddress == null || "".equals(targetAddress.trim())) {
error.setInfo(Collections.singletonMap(DELIVERY_TAG, delivery.getDeliveryTag()));
}
if (!_rejectedOutcomeSupportedBySource || (delivery.isSettled() && !(transaction instanceof LocalTransaction))) {
return error;
} else {
if (delivery.isSettled() && transaction instanceof LocalTransaction) {
((LocalTransaction) transaction).setRollbackOnly();
}
Rejected rejected = new Rejected();
rejected.setError(error);
outcome = rejected;
}
}
}
Outcome sourceDefaultOutcome = getSource().getDefaultOutcome();
boolean defaultOutcome = sourceDefaultOutcome != null && sourceDefaultOutcome.getSymbol().equals(outcome.getSymbol());
DeliveryState resultantState;
if (transactionId == null) {
resultantState = defaultOutcome ? null : outcome;
} else {
TransactionalState transactionalState = new TransactionalState();
transactionalState.setOutcome(defaultOutcome ? null : outcome);
transactionalState.setTxnId(transactionId);
resultantState = transactionalState;
}
boolean settled = shouldReceiverSettleFirst(transferReceiverSettleMode);
if (transaction instanceof AsyncAutoCommitTransaction) {
_pendingDispositions.add(new PendingDispositionHolder(delivery.getDeliveryTag(), resultantState, settled));
} else {
getSession().receivedComplete();
updateDisposition(delivery.getDeliveryTag(), resultantState, settled);
}
getSession().registerMessageReceived(serverMessage.getSize());
if (transactionId != null) {
getSession().registerTransactedMessageReceived();
}
setRollbackOnly = false;
} catch (AccessControlException e) {
final Error err = new Error();
err.setCondition(AmqpError.NOT_ALLOWED);
err.setDescription(e.getMessage());
return err;
} finally {
if (setRollbackOnly && transaction instanceof LocalTransaction) {
((LocalTransaction) transaction).setRollbackOnly();
}
}
} finally {
reference.release();
}
}
return null;
}
use of org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted in project qpid-broker-j by apache.
the class TxnCoordinatorReceivingLinkEndpoint method receiveDelivery.
@Override
protected Error receiveDelivery(Delivery delivery) {
// Only interested in the amqp-value section that holds the message to the coordinator
try (QpidByteBuffer payload = delivery.getPayload()) {
List<EncodingRetainingSection<?>> sections = getSectionDecoder().parseAll(payload);
boolean amqpValueSectionFound = false;
for (EncodingRetainingSection section : sections) {
try {
if (section instanceof AmqpValueSection) {
if (amqpValueSectionFound) {
throw new ConnectionScopedRuntimeException("Received more than one AmqpValue sections");
}
amqpValueSectionFound = true;
Object command = section.getValue();
Session_1_0 session = getSession();
AMQPConnection_1_0<?> connection = session.getConnection();
connection.receivedComplete();
if (command instanceof Declare) {
final IdentifiedTransaction txn = connection.createIdentifiedTransaction();
_createdTransactions.put(txn.getId(), txn.getServerTransaction());
long notificationRepeatPeriod = getSession().getContextValue(Long.class, Session.TRANSACTION_TIMEOUT_NOTIFICATION_REPEAT_PERIOD);
connection.registerTransactionTickers(txn.getServerTransaction(), this::doTimeoutAction, notificationRepeatPeriod);
Declared state = new Declared();
state.setTxnId(Session_1_0.integerToTransactionId(txn.getId()));
updateDisposition(delivery.getDeliveryTag(), state, true);
} else if (command instanceof Discharge) {
Discharge discharge = (Discharge) command;
Error error = discharge(discharge.getTxnId(), Boolean.TRUE.equals(discharge.getFail()));
final DeliveryState outcome;
if (error == null) {
outcome = new Accepted();
} else if (Arrays.asList(getSource().getOutcomes()).contains(Rejected.REJECTED_SYMBOL)) {
final Rejected rejected = new Rejected();
rejected.setError(error);
outcome = rejected;
error = null;
} else {
outcome = null;
}
if (error == null) {
updateDisposition(delivery.getDeliveryTag(), outcome, true);
}
return error;
} else {
throw new ConnectionScopedRuntimeException(String.format("Received unknown command '%s'", command.getClass().getSimpleName()));
}
}
} finally {
section.dispose();
}
}
if (!amqpValueSectionFound) {
throw new ConnectionScopedRuntimeException("Received no AmqpValue section");
}
} catch (AmqpErrorException e) {
return e.getError();
}
return null;
}
use of org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted in project qpid-broker-j by apache.
the class ConsumerTarget_1_0 method doSend.
@Override
public void doSend(final MessageInstanceConsumer consumer, final MessageInstance entry, boolean batch) {
ServerMessage serverMessage = entry.getMessage();
Message_1_0 message;
final MessageConverter<? super ServerMessage, Message_1_0> converter;
if (serverMessage instanceof Message_1_0) {
converter = null;
message = (Message_1_0) serverMessage;
} else {
if (!serverMessage.checkValid()) {
throw new MessageConversionException(String.format("Cannot convert malformed message '%s'", serverMessage));
}
converter = (MessageConverter<? super ServerMessage, Message_1_0>) MessageConverterRegistry.getConverter(serverMessage.getClass(), Message_1_0.class);
if (converter == null) {
throw new ServerScopedRuntimeException(String.format("Could not find message converter from '%s' to '%s'." + " This is unexpected since we should not try to send if the converter is not present.", serverMessage.getClass(), Message_1_0.class));
}
message = converter.convert(serverMessage, _linkEndpoint.getAddressSpace());
}
Transfer transfer = new Transfer();
try {
QpidByteBuffer bodyContent = message.getContent();
HeaderSection headerSection = message.getHeaderSection();
UnsignedInteger ttl = headerSection == null ? null : headerSection.getValue().getTtl();
if (entry.getDeliveryCount() != 0 || ttl != null) {
Header header = new Header();
if (headerSection != null) {
final Header oldHeader = headerSection.getValue();
header.setDurable(oldHeader.getDurable());
header.setPriority(oldHeader.getPriority());
if (ttl != null) {
long timeSpentOnBroker = System.currentTimeMillis() - message.getArrivalTime();
final long adjustedTtl = Math.max(0L, ttl.longValue() - timeSpentOnBroker);
header.setTtl(UnsignedInteger.valueOf(adjustedTtl));
}
headerSection.dispose();
}
if (entry.getDeliveryCount() != 0) {
header.setDeliveryCount(UnsignedInteger.valueOf(entry.getDeliveryCount()));
}
headerSection = header.createEncodingRetainingSection();
}
List<QpidByteBuffer> payload = new ArrayList<>();
if (headerSection != null) {
payload.add(headerSection.getEncodedForm());
headerSection.dispose();
}
EncodingRetainingSection<?> section;
if ((section = message.getDeliveryAnnotationsSection()) != null) {
payload.add(section.getEncodedForm());
section.dispose();
}
if ((section = message.getMessageAnnotationsSection()) != null) {
payload.add(section.getEncodedForm());
section.dispose();
}
if ((section = message.getPropertiesSection()) != null) {
payload.add(section.getEncodedForm());
section.dispose();
}
if ((section = message.getApplicationPropertiesSection()) != null) {
payload.add(section.getEncodedForm());
section.dispose();
}
payload.add(bodyContent);
if ((section = message.getFooterSection()) != null) {
payload.add(section.getEncodedForm());
section.dispose();
}
try (QpidByteBuffer combined = QpidByteBuffer.concatenate(payload)) {
transfer.setPayload(combined);
}
payload.forEach(QpidByteBuffer::dispose);
byte[] data = new byte[8];
ByteBuffer.wrap(data).putLong(_deliveryTag++);
final Binary tag = new Binary(data);
transfer.setDeliveryTag(tag);
if (_linkEndpoint.isAttached()) {
boolean sendPreSettled = SenderSettleMode.SETTLED.equals(getEndpoint().getSendingSettlementMode());
if (sendPreSettled) {
transfer.setSettled(true);
if (_acquires && _transactionId == null) {
transfer.setState(new Accepted());
}
} else {
final UnsettledAction action;
if (_acquires) {
action = new DispositionAction(tag, entry, consumer);
addUnacknowledgedMessage(entry);
} else {
action = new DoNothingAction();
}
_linkEndpoint.addUnsettled(tag, action, entry);
}
if (_transactionId != null) {
TransactionalState state = new TransactionalState();
state.setTxnId(_transactionId);
transfer.setState(state);
}
if (_acquires && _transactionId != null) {
try {
ServerTransaction txn = _linkEndpoint.getTransaction(_transactionId);
txn.addPostTransactionAction(new ServerTransaction.Action() {
@Override
public void postCommit() {
}
@Override
public void onRollback() {
entry.release(consumer);
_linkEndpoint.updateDisposition(tag, null, true);
}
});
final TransactionLogResource owningResource = entry.getOwningResource();
if (owningResource instanceof TransactionMonitor) {
((TransactionMonitor) owningResource).registerTransaction(txn);
}
} catch (UnknownTransactionException e) {
entry.release(consumer);
getEndpoint().close(new Error(TransactionError.UNKNOWN_ID, e.getMessage()));
return;
}
}
getSession().getAMQPConnection().registerMessageDelivered(message.getSize());
getEndpoint().transfer(transfer, false);
if (sendPreSettled && _acquires && _transactionId == null) {
handleAcquiredEntrySentPareSettledNonTransactional(entry, consumer);
}
} else {
entry.release(consumer);
}
} finally {
transfer.dispose();
if (converter != null) {
converter.dispose(message);
}
}
}
use of org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted in project qpid-broker-j by apache.
the class SendingLinkEndpoint method flowStateChanged.
@Override
public void flowStateChanged() {
if (Boolean.TRUE.equals(getDrain())) {
if (getLinkCredit().compareTo(UnsignedInteger.ZERO) > 0) {
_draining = true;
getSession().notifyWork(getConsumerTarget());
}
} else {
_draining = false;
}
while (!_resumeAcceptedTransfers.isEmpty() && hasCreditToSend()) {
Accepted accepted = new Accepted();
Transfer xfr = new Transfer();
Binary dt = _resumeAcceptedTransfers.remove(0);
xfr.setDeliveryTag(dt);
xfr.setState(accepted);
xfr.setResume(Boolean.TRUE);
transfer(xfr, true);
xfr.dispose();
}
if (_resumeAcceptedTransfers.isEmpty()) {
getConsumerTarget().flowStateChanged();
}
}
use of org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted in project qpid-broker-j by apache.
the class ResumeDeliveriesTest method resumeReceivingLinkWithSingleUnsettledAccepted.
@Ignore("QPID-7845")
@Test
@SpecificationTest(section = "2.6.13", description = "When a suspended link having unsettled deliveries is resumed," + " the unsettled field from the attach frame will carry" + " the delivery-tags and delivery state of all deliveries" + " considered unsettled by the issuing link endpoint.")
public void resumeReceivingLinkWithSingleUnsettledAccepted() throws Exception {
Utils.putMessageOnQueue(getBrokerAdmin(), BrokerAdmin.TEST_QUEUE_NAME, getTestName());
try (FrameTransport transport = new FrameTransport(getBrokerAdmin()).connect()) {
final Interaction interaction = transport.newInteraction().negotiateOpen().begin().consumeResponse().attachRole(Role.RECEIVER).attachSourceAddress(BrokerAdmin.TEST_QUEUE_NAME).attachRcvSettleMode(ReceiverSettleMode.FIRST).attachSndSettleMode(SenderSettleMode.UNSETTLED).attach().consumeResponse();
Attach attach = interaction.getLatestResponse(Attach.class);
assumeThat(attach.getSndSettleMode(), is(equalTo(SenderSettleMode.UNSETTLED)));
interaction.flowIncomingWindow(UnsignedInteger.ONE).flowLinkCredit(UnsignedInteger.ONE).flowHandleFromLinkHandle().flow().receiveDelivery();
List<Transfer> transfers = interaction.getLatestDelivery();
assertThat(transfers, hasSize(1));
Transfer transfer = transfers.get(0);
Binary deliveryTag = transfer.getDeliveryTag();
assertThat(deliveryTag, is(notNullValue()));
assertThat(transfer.getSettled(), is(not(equalTo(true))));
Object data = interaction.decodeLatestDelivery().getDecodedLatestDelivery();
assertThat(data, is(equalTo(getTestName())));
Detach detach = interaction.detach().consumeResponse().getLatestResponse(Detach.class);
assertThat(detach.getClosed(), anyOf(nullValue(), equalTo(false)));
interaction.attachUnsettled(Collections.singletonMap(deliveryTag, new Accepted())).attach().consumeResponse(Attach.class);
Attach resumeAttach = interaction.getLatestResponse(Attach.class);
Map<Binary, DeliveryState> unsettled = resumeAttach.getUnsettled();
assertThat(unsettled, is(notNullValue()));
assertThat(unsettled.entrySet(), hasSize(1));
Map.Entry<Binary, DeliveryState> entry = unsettled.entrySet().iterator().next();
assertThat(entry.getKey(), is(equalTo(deliveryTag)));
interaction.flowNextIncomingId(UnsignedInteger.ONE).flowLinkCredit(UnsignedInteger.ONE).flowHandleFromLinkHandle().flow().receiveDelivery();
transfers = interaction.getLatestDelivery();
assertThat(transfers, hasSize(1));
Transfer resumeTransfer = transfers.get(0);
assertThat(resumeTransfer.getResume(), is(equalTo(true)));
assertThat(resumeTransfer.getDeliveryTag(), is(equalTo(deliveryTag)));
assertThat(resumeTransfer.getPayload(), is(nullValue()));
if (!Boolean.TRUE.equals(resumeTransfer.getSettled())) {
interaction.dispositionSettled(true).dispositionState(new Accepted()).dispositionRole(Role.RECEIVER).disposition();
}
interaction.doCloseConnection();
final String content = getTestName() + "_2";
Utils.putMessageOnQueue(getBrokerAdmin(), BrokerAdmin.TEST_QUEUE_NAME, content);
assertThat(Utils.receiveMessage(getBrokerAdmin(), BrokerAdmin.TEST_QUEUE_NAME), Matchers.is(Matchers.equalTo(content)));
}
}
Aggregations