Search in sources :

Example 1 with AutoCommitTransaction

use of org.apache.qpid.server.txn.AutoCommitTransaction in project qpid-broker-j by apache.

the class AbstractVirtualHost method publishMessage.

@Override
public int publishMessage(@Param(name = "message") final ManageableMessage message) {
    final String address = message.getAddress();
    MessageDestination destination = address == null ? getDefaultDestination() : getAttainedMessageDestination(address);
    if (destination == null) {
        destination = getDefaultDestination();
    }
    final AMQMessageHeader header = new MessageHeaderImpl(message);
    Serializable body = null;
    Object messageContent = message.getContent();
    if (messageContent != null) {
        if (messageContent instanceof Map || messageContent instanceof List) {
            if (message.getMimeType() != null || message.getEncoding() != null) {
                throw new IllegalArgumentException("If the message content is provided as map or list, the mime type and encoding must be left unset");
            }
            body = (Serializable) messageContent;
        } else if (messageContent instanceof String) {
            String contentTransferEncoding = message.getContentTransferEncoding();
            if ("base64".equalsIgnoreCase(contentTransferEncoding)) {
                body = Strings.decodeBase64((String) messageContent);
            } else if (contentTransferEncoding == null || contentTransferEncoding.trim().equals("") || contentTransferEncoding.trim().equalsIgnoreCase("identity")) {
                String mimeType = message.getMimeType();
                if (mimeType != null && !(mimeType = mimeType.trim().toLowerCase()).equals("")) {
                    if (!(mimeType.startsWith("text/") || Arrays.asList("application/json", "application/xml").contains(mimeType))) {
                        throw new IllegalArgumentException(message.getMimeType() + " is invalid as a MIME type for this message. " + "Only MIME types of the text type can be used if a string is supplied as the content");
                    } else if (mimeType.matches(".*;\\s*charset\\s*=.*")) {
                        throw new IllegalArgumentException(message.getMimeType() + " is invalid as a MIME type for this message. " + "If a string is supplied as the content, the MIME type must not include a charset parameter");
                    }
                }
                body = (String) messageContent;
            } else {
                throw new IllegalArgumentException("contentTransferEncoding value '" + contentTransferEncoding + "' is invalid.  The only valid values are base64 and identity");
            }
        } else {
            throw new IllegalArgumentException("The message content (if present) can only be a string, map or list");
        }
    }
    InternalMessage internalMessage = InternalMessage.createMessage(getMessageStore(), header, body, message.isPersistent(), address);
    AutoCommitTransaction txn = new AutoCommitTransaction(getMessageStore());
    final InstanceProperties instanceProperties = new InstanceProperties() {

        @Override
        public Object getProperty(final Property prop) {
            switch(prop) {
                case EXPIRATION:
                    Date expiration = message.getExpiration();
                    return expiration == null ? 0 : expiration.getTime();
                case IMMEDIATE:
                    return false;
                case PERSISTENT:
                    return message.isPersistent();
                case MANDATORY:
                    return false;
                case REDELIVERED:
                    return false;
                default:
                    return null;
            }
        }
    };
    final RoutingResult<InternalMessage> result = destination.route(internalMessage, address, instanceProperties);
    return result.send(txn, null);
}
Also used : AutoCommitTransaction(org.apache.qpid.server.txn.AutoCommitTransaction) Serializable(java.io.Serializable) MessageDestination(org.apache.qpid.server.message.MessageDestination) InternalMessage(org.apache.qpid.server.message.internal.InternalMessage) InstanceProperties(org.apache.qpid.server.message.InstanceProperties) AMQMessageHeader(org.apache.qpid.server.message.AMQMessageHeader) Date(java.util.Date) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Collections.newSetFromMap(java.util.Collections.newSetFromMap)

Example 2 with AutoCommitTransaction

use of org.apache.qpid.server.txn.AutoCommitTransaction in project qpid-broker-j by apache.

the class LastValueQueueList method discardEntry.

private void discardEntry(final QueueEntry entry) {
    if (entry.acquire()) {
        ServerTransaction txn = new AutoCommitTransaction(getQueue().getVirtualHost().getMessageStore());
        txn.dequeue(entry.getEnqueueRecord(), new ServerTransaction.Action() {

            @Override
            public void postCommit() {
                entry.delete();
            }

            @Override
            public void onRollback() {
            }
        });
    }
}
Also used : AutoCommitTransaction(org.apache.qpid.server.txn.AutoCommitTransaction) ServerTransaction(org.apache.qpid.server.txn.ServerTransaction)

Example 3 with AutoCommitTransaction

use of org.apache.qpid.server.txn.AutoCommitTransaction 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) {
            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().getAMQPConnection().registerMessageReceived(serverMessage.getSize());
                if (transactionId != null) {
                    getSession().getAMQPConnection().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;
}
Also used : AsyncAutoCommitTransaction(org.apache.qpid.server.txn.AsyncAutoCommitTransaction) AutoCommitTransaction(org.apache.qpid.server.txn.AutoCommitTransaction) AsyncAutoCommitTransaction(org.apache.qpid.server.txn.AsyncAutoCommitTransaction) LocalTransaction(org.apache.qpid.server.txn.LocalTransaction) Rejected(org.apache.qpid.server.protocol.v1_0.type.messaging.Rejected) ReceiverSettleMode(org.apache.qpid.server.protocol.v1_0.type.transport.ReceiverSettleMode) ServerTransaction(org.apache.qpid.server.txn.ServerTransaction) AmqpErrorRuntimeException(org.apache.qpid.server.protocol.v1_0.type.AmqpErrorRuntimeException) MessageFormat(org.apache.qpid.server.plugin.MessageFormat) TransactionError(org.apache.qpid.server.protocol.v1_0.type.transaction.TransactionError) Error(org.apache.qpid.server.protocol.v1_0.type.transport.Error) AmqpError(org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError) AccessControlException(java.security.AccessControlException) TransactionalState(org.apache.qpid.server.protocol.v1_0.type.transaction.TransactionalState) DeliveryState(org.apache.qpid.server.protocol.v1_0.type.DeliveryState) Outcome(org.apache.qpid.server.protocol.v1_0.type.Outcome) QpidByteBuffer(org.apache.qpid.server.bytebuffer.QpidByteBuffer) Binary(org.apache.qpid.server.protocol.v1_0.type.Binary) UnsignedInteger(org.apache.qpid.server.protocol.v1_0.type.UnsignedInteger)

Example 4 with AutoCommitTransaction

use of org.apache.qpid.server.txn.AutoCommitTransaction in project qpid-broker-j by apache.

the class ManagementNode method sendResponse.

private void sendResponse(final InternalMessage message, final InternalMessage response) {
    String replyTo = message.getMessageHeader().getReplyTo();
    response.setInitialRoutingAddress(replyTo);
    final MessageDestination responseDestination = getResponseDestination(replyTo);
    RoutingResult<InternalMessage> result = responseDestination.route(response, replyTo, InstanceProperties.EMPTY);
    result.send(new AutoCommitTransaction(_addressSpace.getMessageStore()), null);
}
Also used : AutoCommitTransaction(org.apache.qpid.server.txn.AutoCommitTransaction) MessageDestination(org.apache.qpid.server.message.MessageDestination) InternalMessage(org.apache.qpid.server.message.internal.InternalMessage)

Example 5 with AutoCommitTransaction

use of org.apache.qpid.server.txn.AutoCommitTransaction in project qpid-broker-j by apache.

the class SendingLinkEndpoint method attachReceived.

@Override
public void attachReceived(final Attach attach) throws AmqpErrorException {
    super.attachReceived(attach);
    Target target = (Target) attach.getTarget();
    Source source = getSource();
    if (source == null) {
        source = new Source();
        Source attachSource = (Source) attach.getSource();
        final Modified defaultOutcome = new Modified();
        defaultOutcome.setDeliveryFailed(true);
        source.setDefaultOutcome(defaultOutcome);
        source.setOutcomes(Accepted.ACCEPTED_SYMBOL, Released.RELEASED_SYMBOL, Rejected.REJECTED_SYMBOL);
        source.setAddress(attachSource.getAddress());
        source.setDynamic(attachSource.getDynamic());
        if (Boolean.TRUE.equals(attachSource.getDynamic()) && attachSource.getDynamicNodeProperties() != null) {
            Map<Symbol, Object> dynamicNodeProperties = new HashMap<>();
            if (attachSource.getDynamicNodeProperties().containsKey(Session_1_0.LIFETIME_POLICY)) {
                dynamicNodeProperties.put(Session_1_0.LIFETIME_POLICY, attachSource.getDynamicNodeProperties().get(Session_1_0.LIFETIME_POLICY));
            }
            source.setDynamicNodeProperties(dynamicNodeProperties);
        }
        source.setDurable(TerminusDurability.min(attachSource.getDurable(), getLink().getHighestSupportedTerminusDurability()));
        source.setExpiryPolicy(attachSource.getExpiryPolicy());
        source.setDistributionMode(attachSource.getDistributionMode());
        source.setFilter(attachSource.getFilter());
        source.setCapabilities(attachSource.getCapabilities());
        final SendingDestination destination = getSession().getSendingDestination(getLink(), source);
        source.setCapabilities(destination.getCapabilities());
        getLink().setSource(source);
        prepareConsumerOptionsAndFilters(destination);
    }
    getLink().setTarget(target);
    final MessageInstanceConsumer oldConsumer = getConsumer();
    createConsumerTarget();
    _resumeAcceptedTransfers.clear();
    _resumeFullTransfers.clear();
    final NamedAddressSpace addressSpace = getSession().getConnection().getAddressSpace();
    // TODO: QPID-7845 : Resuming links is unsupported at the moment. Thus, cleaning up unsettled deliveries unconditionally.
    cleanUpUnsettledDeliveries();
    getSession().addDeleteTask(_cleanUpUnsettledDeliveryTask);
    Map<Binary, OutgoingDelivery> unsettledCopy = new HashMap<>(_unsettled);
    Map<Binary, DeliveryState> remoteUnsettled = attach.getUnsettled() == null ? Collections.emptyMap() : new HashMap<>(attach.getUnsettled());
    final boolean isUnsettledComplete = !Boolean.TRUE.equals(attach.getIncompleteUnsettled());
    for (Map.Entry<Binary, OutgoingDelivery> entry : unsettledCopy.entrySet()) {
        Binary deliveryTag = entry.getKey();
        final MessageInstance queueEntry = entry.getValue().getMessageInstance();
        if (!remoteUnsettled.containsKey(deliveryTag) && isUnsettledComplete) {
            queueEntry.setRedelivered();
            queueEntry.release(oldConsumer);
            _unsettled.remove(deliveryTag);
        } else if (remoteUnsettled.get(deliveryTag) instanceof Outcome) {
            Outcome outcome = (Outcome) remoteUnsettled.get(deliveryTag);
            if (outcome instanceof Accepted) {
                if (oldConsumer.acquires()) {
                    AutoCommitTransaction txn = new AutoCommitTransaction(addressSpace.getMessageStore());
                    if (queueEntry.acquire() || queueEntry.isAcquired()) {
                        txn.dequeue(Collections.singleton(queueEntry), new ServerTransaction.Action() {

                            @Override
                            public void postCommit() {
                                queueEntry.delete();
                            }

                            @Override
                            public void onRollback() {
                            }
                        });
                    }
                }
            } else if (outcome instanceof Released) {
                if (oldConsumer.acquires()) {
                    AutoCommitTransaction txn = new AutoCommitTransaction(addressSpace.getMessageStore());
                    txn.dequeue(Collections.singleton(queueEntry), new ServerTransaction.Action() {

                        @Override
                        public void postCommit() {
                            queueEntry.release(oldConsumer);
                        }

                        @Override
                        public void onRollback() {
                        }
                    });
                }
            }
            // TODO: QPID-7845: Handle rejected and modified outcome
            remoteUnsettled.remove(deliveryTag);
            _resumeAcceptedTransfers.add(deliveryTag);
        } else {
            _resumeFullTransfers.add(queueEntry);
        // TODO:QPID-7845: exists in receivers map, but not yet got an outcome ... should resend with resume = true
        }
    }
    getConsumerTarget().updateNotifyWorkDesired();
}
Also used : AsyncAutoCommitTransaction(org.apache.qpid.server.txn.AsyncAutoCommitTransaction) AutoCommitTransaction(org.apache.qpid.server.txn.AutoCommitTransaction) Action(org.apache.qpid.server.util.Action) Modified(org.apache.qpid.server.protocol.v1_0.type.messaging.Modified) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Symbol(org.apache.qpid.server.protocol.v1_0.type.Symbol) MessageInstanceConsumer(org.apache.qpid.server.message.MessageInstanceConsumer) MessageSource(org.apache.qpid.server.message.MessageSource) BaseSource(org.apache.qpid.server.protocol.v1_0.type.BaseSource) Source(org.apache.qpid.server.protocol.v1_0.type.messaging.Source) MessageInstance(org.apache.qpid.server.message.MessageInstance) BaseTarget(org.apache.qpid.server.protocol.v1_0.type.BaseTarget) Target(org.apache.qpid.server.protocol.v1_0.type.messaging.Target) ServerTransaction(org.apache.qpid.server.txn.ServerTransaction) Released(org.apache.qpid.server.protocol.v1_0.type.messaging.Released) NamedAddressSpace(org.apache.qpid.server.model.NamedAddressSpace) Accepted(org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted) DeliveryState(org.apache.qpid.server.protocol.v1_0.type.DeliveryState) Outcome(org.apache.qpid.server.protocol.v1_0.type.Outcome) Binary(org.apache.qpid.server.protocol.v1_0.type.Binary) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Aggregations

AutoCommitTransaction (org.apache.qpid.server.txn.AutoCommitTransaction)8 ServerTransaction (org.apache.qpid.server.txn.ServerTransaction)6 HashMap (java.util.HashMap)2 Map (java.util.Map)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 MessageDestination (org.apache.qpid.server.message.MessageDestination)2 InternalMessage (org.apache.qpid.server.message.internal.InternalMessage)2 Binary (org.apache.qpid.server.protocol.v1_0.type.Binary)2 DeliveryState (org.apache.qpid.server.protocol.v1_0.type.DeliveryState)2 Outcome (org.apache.qpid.server.protocol.v1_0.type.Outcome)2 AsyncAutoCommitTransaction (org.apache.qpid.server.txn.AsyncAutoCommitTransaction)2 LocalTransaction (org.apache.qpid.server.txn.LocalTransaction)2 Serializable (java.io.Serializable)1 AccessControlException (java.security.AccessControlException)1 PrivilegedAction (java.security.PrivilegedAction)1 ArrayList (java.util.ArrayList)1 Collections.newSetFromMap (java.util.Collections.newSetFromMap)1 Date (java.util.Date)1 List (java.util.List)1 QpidByteBuffer (org.apache.qpid.server.bytebuffer.QpidByteBuffer)1