Search in sources :

Example 71 with QpidByteBuffer

use of org.apache.qpid.server.bytebuffer.QpidByteBuffer 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 72 with QpidByteBuffer

use of org.apache.qpid.server.bytebuffer.QpidByteBuffer 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;
}
Also used : EncodingRetainingSection(org.apache.qpid.server.protocol.v1_0.type.messaging.EncodingRetainingSection) Error(org.apache.qpid.server.protocol.v1_0.type.transport.Error) AmqpError(org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError) TransactionError(org.apache.qpid.server.protocol.v1_0.type.transaction.TransactionError) AmqpErrorException(org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException) Rejected(org.apache.qpid.server.protocol.v1_0.type.messaging.Rejected) Declare(org.apache.qpid.server.protocol.v1_0.type.transaction.Declare) Declared(org.apache.qpid.server.protocol.v1_0.type.transaction.Declared) Discharge(org.apache.qpid.server.protocol.v1_0.type.transaction.Discharge) Accepted(org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted) DeliveryState(org.apache.qpid.server.protocol.v1_0.type.DeliveryState) ConnectionScopedRuntimeException(org.apache.qpid.server.util.ConnectionScopedRuntimeException) QpidByteBuffer(org.apache.qpid.server.bytebuffer.QpidByteBuffer) AmqpValueSection(org.apache.qpid.server.protocol.v1_0.type.messaging.AmqpValueSection)

Example 73 with QpidByteBuffer

use of org.apache.qpid.server.bytebuffer.QpidByteBuffer in project qpid-broker-j by apache.

the class FrameWriter method send.

public <T> int send(AMQFrame<T> frame) {
    final QpidByteBuffer payload = frame.getPayload();
    final int payloadLength = payload == null ? 0 : payload.remaining();
    final T frameBody = frame.getFrameBody();
    final ValueWriter<T> typeWriter = frameBody == null ? null : _registry.getValueWriter(frameBody);
    int bodySize;
    if (typeWriter == null) {
        bodySize = 8;
    } else {
        bodySize = 8 + typeWriter.getEncodedSize();
    }
    final int totalSize;
    try (QpidByteBuffer body = QpidByteBuffer.allocate(_sender.isDirectBufferPreferred(), bodySize)) {
        totalSize = bodySize + payloadLength;
        body.putInt(totalSize);
        // DOFF
        body.put((byte) 2);
        // AMQP Frame Type
        body.put(frame.getFrameType());
        body.putShort(UnsignedShort.valueOf(frame.getChannel()).shortValue());
        if (typeWriter != null) {
            typeWriter.writeToBuffer(body);
        }
        body.flip();
        _sender.send(body);
    }
    if (payload != null) {
        _sender.send(payload);
    }
    return totalSize;
}
Also used : QpidByteBuffer(org.apache.qpid.server.bytebuffer.QpidByteBuffer)

Example 74 with QpidByteBuffer

use of org.apache.qpid.server.bytebuffer.QpidByteBuffer in project qpid-broker-j by apache.

the class FrameHandler method parse.

@Override
public ProtocolHandler parse(QpidByteBuffer in) {
    try {
        LOGGER.debug("RECV {} bytes", in.remaining());
        Error frameParsingError = null;
        int size;
        int remaining;
        List<ChannelFrameBody> channelFrameBodies = new ArrayList<>();
        while ((remaining = in.remaining()) >= 8 && frameParsingError == null) {
            size = in.getInt();
            if (size < 8) {
                frameParsingError = createFramingError("specified frame size %d smaller than minimum frame header size %d", size, 8);
                break;
            }
            if (size > _connectionHandler.getMaxFrameSize()) {
                frameParsingError = createFramingError("specified frame size %d larger than maximum frame header size %d", size, _connectionHandler.getMaxFrameSize());
                break;
            }
            if (remaining < size) {
                in.position(in.position() - 4);
                break;
            }
            int dataOffset = (in.get() << 2) & 0x3FF;
            if (dataOffset < 8) {
                frameParsingError = createFramingError("specified frame data offset %d smaller than minimum frame header size %d", dataOffset, 8);
                break;
            }
            if (dataOffset > size) {
                frameParsingError = createFramingError("specified frame data offset %d larger than the frame size %d", dataOffset, size);
                break;
            }
            byte type = in.get();
            switch(type) {
                case 0:
                    if (_isSasl) {
                        frameParsingError = createFramingError("received an AMQP frame type when expecting an SASL frame");
                    }
                    break;
                case 1:
                    if (!_isSasl) {
                        frameParsingError = createFramingError("received a SASL frame type when expecting an AMQP frame");
                    }
                    break;
                default:
                    frameParsingError = createFramingError("unknown frame type: %d", type);
            }
            if (frameParsingError != null) {
                break;
            }
            int channel = in.getUnsignedShort();
            if (dataOffset != 8) {
                in.position(in.position() + dataOffset - 8);
            }
            try (QpidByteBuffer dup = in.slice()) {
                dup.limit(size - dataOffset);
                in.position(in.position() + size - dataOffset);
                final boolean hasFrameBody = dup.hasRemaining();
                Object frameBody;
                if (hasFrameBody) {
                    frameBody = _valueHandler.parse(dup);
                    if (dup.hasRemaining()) {
                        if (frameBody instanceof Transfer) {
                            try (QpidByteBuffer payload = dup.slice()) {
                                ((Transfer) frameBody).setPayload(payload);
                            }
                        } else {
                            frameParsingError = createFramingError("Frame length %d larger than contained frame body %s.", size, frameBody);
                            break;
                        }
                    }
                } else {
                    frameBody = null;
                    if (_isSasl) {
                        frameParsingError = createFramingError("Empty (heartbeat) frames are not permitted during SASL negotiation");
                        break;
                    }
                }
                channelFrameBodies.add(new ChannelFrameBody() {

                    @Override
                    public int getChannel() {
                        return channel;
                    }

                    @Override
                    public Object getFrameBody() {
                        return frameBody;
                    }
                });
                if (_isSasl) {
                    break;
                }
            } catch (AmqpErrorException ex) {
                frameParsingError = ex.getError();
            }
        }
        if (frameParsingError != null) {
            _connectionHandler.handleError(frameParsingError);
            _errored = true;
        } else {
            _connectionHandler.receive(channelFrameBodies);
        }
    } catch (RuntimeException e) {
        if (e instanceof ServerScopedRuntimeException) {
            throw e;
        }
        LOGGER.warn("Unexpected exception handling frame", e);
        // This exception is unexpected. The up layer should handle error condition gracefully
        _connectionHandler.handleError(this.createError(AmqpError.INTERNAL_ERROR, e.toString()));
    }
    return this;
}
Also used : ArrayList(java.util.ArrayList) Error(org.apache.qpid.server.protocol.v1_0.type.transport.Error) AmqpError(org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError) ConnectionError(org.apache.qpid.server.protocol.v1_0.type.transport.ConnectionError) AmqpErrorException(org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) ChannelFrameBody(org.apache.qpid.server.protocol.v1_0.type.transport.ChannelFrameBody) Transfer(org.apache.qpid.server.protocol.v1_0.type.transport.Transfer) QpidByteBuffer(org.apache.qpid.server.bytebuffer.QpidByteBuffer)

Example 75 with QpidByteBuffer

use of org.apache.qpid.server.bytebuffer.QpidByteBuffer in project qpid-broker-j by apache.

the class LinkStoreUtils method objectToAmqpBytes.

public static byte[] objectToAmqpBytes(final Object object) {
    ValueWriter valueWriter = DESCRIBED_TYPE_REGISTRY.getValueWriter(object);
    int encodedSize = valueWriter.getEncodedSize();
    try (QpidByteBuffer qpidByteBuffer = QpidByteBuffer.allocate(encodedSize)) {
        valueWriter.writeToBuffer(qpidByteBuffer);
        return qpidByteBuffer.array();
    }
}
Also used : ValueWriter(org.apache.qpid.server.protocol.v1_0.codec.ValueWriter) QpidByteBuffer(org.apache.qpid.server.bytebuffer.QpidByteBuffer)

Aggregations

QpidByteBuffer (org.apache.qpid.server.bytebuffer.QpidByteBuffer)185 NamedAddressSpace (org.apache.qpid.server.model.NamedAddressSpace)61 Message_1_0 (org.apache.qpid.server.protocol.v1_0.Message_1_0)61 Binary (org.apache.qpid.server.protocol.v1_0.type.Binary)42 Data (org.apache.qpid.server.protocol.v1_0.type.messaging.Data)30 MessageTransferMessage (org.apache.qpid.server.protocol.v0_10.MessageTransferMessage)29 AMQMessage (org.apache.qpid.server.protocol.v0_8.AMQMessage)29 ApplicationProperties (org.apache.qpid.server.protocol.v1_0.type.messaging.ApplicationProperties)29 Properties (org.apache.qpid.server.protocol.v1_0.type.messaging.Properties)28 ArrayList (java.util.ArrayList)22 AmqpValue (org.apache.qpid.server.protocol.v1_0.type.messaging.AmqpValue)20 Test (org.junit.Test)13 MapToJmsMapMessage (org.apache.qpid.server.typedmessage.mimecontentconverter.MapToJmsMapMessage)12 EncodingRetainingSection (org.apache.qpid.server.protocol.v1_0.type.messaging.EncodingRetainingSection)10 UnsignedInteger (org.apache.qpid.server.protocol.v1_0.type.UnsignedInteger)9 Transfer (org.apache.qpid.server.protocol.v1_0.type.transport.Transfer)9 SpecificationTest (org.apache.qpid.tests.protocol.SpecificationTest)9 ByteBuffer (java.nio.ByteBuffer)8 LinkedHashMap (java.util.LinkedHashMap)8 JmsMapMessageToMap (org.apache.qpid.server.typedmessage.mimecontentconverter.JmsMapMessageToMap)8