Search in sources :

Example 1 with AxisRabbitMQException

use of org.apache.axis2.transport.rabbitmq.utils.AxisRabbitMQException in project wso2-axis2-transports by wso2.

the class RabbitMQMessageSender method publish.

/**
 * Perform the creation of exchange/queue and the Outputstream
 *
 * @param message    the RabbitMQ AMQP message
 * @param msgContext the Axis2 MessageContext
 */
public void publish(RabbitMQMessage message, MessageContext msgContext) throws AxisRabbitMQException, IOException {
    String exchangeName = null;
    AMQP.BasicProperties basicProperties = null;
    byte[] messageBody = null;
    if (rmqChannel.isOpen()) {
        String queueName = properties.get(RabbitMQConstants.QUEUE_NAME);
        String routeKey = properties.get(RabbitMQConstants.QUEUE_ROUTING_KEY);
        exchangeName = properties.get(RabbitMQConstants.EXCHANGE_NAME);
        String exchangeType = properties.get(RabbitMQConstants.EXCHANGE_TYPE);
        String replyTo = properties.get(RabbitMQConstants.REPLY_TO_NAME);
        String correlationID = properties.get(RabbitMQConstants.CORRELATION_ID);
        String queueAutoDeclareStr = properties.get(RabbitMQConstants.QUEUE_AUTODECLARE);
        String exchangeAutoDeclareStr = properties.get(RabbitMQConstants.EXCHANGE_AUTODECLARE);
        boolean queueAutoDeclare = true;
        boolean exchangeAutoDeclare = true;
        if (!StringUtils.isEmpty(queueAutoDeclareStr)) {
            queueAutoDeclare = Boolean.parseBoolean(queueAutoDeclareStr);
        }
        if (!StringUtils.isEmpty(exchangeAutoDeclareStr)) {
            exchangeAutoDeclare = Boolean.parseBoolean(exchangeAutoDeclareStr);
        }
        message.setReplyTo(replyTo);
        if (StringUtils.isEmpty(correlationID)) {
            // if reply-to is enabled a correlationID must be available. If not specified, use messageID
            correlationID = message.getMessageId();
        }
        if (!StringUtils.isEmpty(correlationID)) {
            message.setCorrelationId(correlationID);
        }
        if (queueName == null || queueName.equals("")) {
            log.debug("No queue name is specified");
        }
        if (routeKey == null && !"x-consistent-hash".equals(exchangeType)) {
            if (queueName == null || queueName.equals("")) {
                log.debug("Routing key is not specified");
            } else {
                log.debug("Routing key is not specified. Using queue name as the routing key.");
                routeKey = queueName;
            }
        }
        // read publish properties corr id and route key from message context
        Object prRouteKey = msgContext.getProperty(RabbitMQConstants.QUEUE_ROUTING_KEY);
        Object prCorrId = msgContext.getProperty(RabbitMQConstants.CORRELATION_ID).toString();
        if (prRouteKey != null) {
            routeKey = prRouteKey.toString();
            log.debug("Specifying routing key from axis2 properties");
        }
        if (prCorrId != null) {
            message.setCorrelationId(prCorrId.toString());
            log.debug("Specifying correlation id from axis2 properties");
        }
        // Declaring the queue
        if (queueAutoDeclare && queueName != null && !queueName.equals("")) {
            RabbitMQUtils.declareQueue(rmqChannel, queueName, properties);
        }
        // Declaring the exchange
        if (exchangeAutoDeclare && exchangeName != null && !exchangeName.equals("")) {
            RabbitMQUtils.declareExchange(rmqChannel, exchangeName, properties);
            if (queueName != null && !"x-consistent-hash".equals(exchangeType)) {
                // Create bind between the queue and exchange with the routeKey
                try {
                    rmqChannel.getChannel().queueBind(queueName, exchangeName, routeKey);
                } catch (IOException e) {
                    handleException("Error occurred while creating the bind between the queue: " + queueName + " & exchange: " + exchangeName + " with route-key " + routeKey, e);
                }
            }
        }
        AMQP.BasicProperties.Builder builder = buildBasicProperties(message);
        String deliveryModeString = properties.get(RabbitMQConstants.QUEUE_DELIVERY_MODE);
        int deliveryMode = RabbitMQConstants.DEFAULT_DELIVERY_MODE;
        if (deliveryModeString != null) {
            deliveryMode = Integer.parseInt(deliveryModeString);
        }
        builder.deliveryMode(deliveryMode);
        if (!StringUtils.isEmpty(replyTo)) {
            builder.replyTo(replyTo);
        }
        basicProperties = builder.build();
        OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
        MessageFormatter messageFormatter = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            messageFormatter = MessageProcessorSelector.getMessageFormatter(msgContext);
        } catch (AxisFault axisFault) {
            throw new AxisRabbitMQException("Unable to get the message formatter to use", axisFault);
        }
        // given. Queue/exchange creation, bindings should be done at the broker
        try {
            // x-consistent-hash type
            if (exchangeType != null && exchangeType.equals("x-consistent-hash")) {
                routeKey = UUID.randomUUID().toString();
            }
        } catch (UnsupportedCharsetException ex) {
            handleException("Unsupported encoding " + format.getCharSetEncoding(), ex);
        }
        try {
            messageFormatter.writeTo(msgContext, format, out, false);
            messageBody = out.toByteArray();
        } catch (IOException e) {
            handleException("IO Error while creating BytesMessage", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
        try {
            /**
             * Check for parameter on confirmed delivery in RabbitMq to ensure reliable delivery.
             * Can be enabled by setting the parameter "rabbitmq.confirm.delivery" to "true" in broker URL.
             */
            boolean isConfirmedDeliveryEnabled = Boolean.parseBoolean(properties.get(RabbitMQConstants.CONFIRMED_DELIVERY));
            if (isConfirmedDeliveryEnabled) {
                rmqChannel.getChannel().confirmSelect();
            }
            if (exchangeName != null && exchangeName != "") {
                rmqChannel.getChannel().basicPublish(exchangeName, routeKey, basicProperties, messageBody);
            } else {
                rmqChannel.getChannel().basicPublish("", routeKey, basicProperties, messageBody);
            }
            if (isConfirmedDeliveryEnabled) {
                rmqChannel.getChannel().waitForConfirmsOrDie();
            }
        } catch (IOException e) {
            handleException("Error while publishing the message", e);
        } catch (InterruptedException e) {
            handleException("InterruptedException while waiting for AMQP message confirm :", e);
        }
    } else {
        handleException("Channel cannot be created");
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) AxisRabbitMQException(org.apache.axis2.transport.rabbitmq.utils.AxisRabbitMQException) IOException(java.io.IOException) MessageFormatter(org.apache.axis2.transport.MessageFormatter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AMQP(com.rabbitmq.client.AMQP) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) OMOutputFormat(org.apache.axiom.om.OMOutputFormat)

Example 2 with AxisRabbitMQException

use of org.apache.axis2.transport.rabbitmq.utils.AxisRabbitMQException in project wso2-axis2-transports by wso2.

the class RabbitMQRPCMessageSender method publish.

/**
 * Perform the creation of exchange/queue and the Outputstream
 *
 * @param message    the RabbitMQ AMQP message
 * @param msgContext the Axis2 MessageContext
 */
private void publish(RabbitMQMessage message, MessageContext msgContext) throws AxisRabbitMQException, IOException {
    String exchangeName = null;
    AMQP.BasicProperties basicProperties = null;
    byte[] messageBody = null;
    if (dualChannel.isOpen()) {
        String queueName = epProperties.get(RabbitMQConstants.QUEUE_NAME);
        String routeKey = epProperties.get(RabbitMQConstants.QUEUE_ROUTING_KEY);
        exchangeName = epProperties.get(RabbitMQConstants.EXCHANGE_NAME);
        String exchangeType = epProperties.get(RabbitMQConstants.EXCHANGE_TYPE);
        String correlationID = epProperties.get(RabbitMQConstants.CORRELATION_ID);
        String replyTo = dualChannel.getReplyToQueue();
        String queueAutoDeclareStr = epProperties.get(RabbitMQConstants.QUEUE_AUTODECLARE);
        String exchangeAutoDeclareStr = epProperties.get(RabbitMQConstants.EXCHANGE_AUTODECLARE);
        boolean queueAutoDeclare = true;
        boolean exchangeAutoDeclare = true;
        if (!StringUtils.isEmpty(queueAutoDeclareStr)) {
            queueAutoDeclare = Boolean.parseBoolean(queueAutoDeclareStr);
        }
        if (!StringUtils.isEmpty(exchangeAutoDeclareStr)) {
            exchangeAutoDeclare = Boolean.parseBoolean(exchangeAutoDeclareStr);
        }
        message.setReplyTo(replyTo);
        if ((!StringUtils.isEmpty(replyTo)) && (StringUtils.isEmpty(correlationID))) {
            // if reply-to is enabled a correlationID must be available. If not specified, use messageID
            correlationID = message.getMessageId();
        }
        if (!StringUtils.isEmpty(correlationID)) {
            message.setCorrelationId(correlationID);
        }
        if (queueName == null || queueName.equals("")) {
            log.info("No queue name is specified");
        }
        if (routeKey == null && !"x-consistent-hash".equals(exchangeType)) {
            if (queueName == null || queueName.equals("")) {
                log.info("Routing key is not specified");
            } else {
                log.info("Routing key is not specified. Using queue name as the routing key.");
                routeKey = queueName;
            }
        }
        // Declaring the queue
        if (queueAutoDeclare && queueName != null && !queueName.equals("")) {
            // get channel with dualChannel.getChannel() since it will create a new channel if channel is closed
            RabbitMQUtils.declareQueue(dualChannel, queueName, epProperties);
        }
        // Declaring the exchange
        if (exchangeAutoDeclare && exchangeName != null && !exchangeName.equals("")) {
            RabbitMQUtils.declareExchange(dualChannel, exchangeName, epProperties);
            if (queueName != null && !"x-consistent-hash".equals(exchangeType)) {
                // Create bind between the queue and exchange with the routeKey
                try {
                    dualChannel.getChannel().queueBind(queueName, exchangeName, routeKey);
                } catch (IOException e) {
                    handleException("Error occurred while creating the bind between the queue: " + queueName + " & exchange: " + exchangeName + " with route-key " + routeKey, e);
                }
            }
        }
        // build basic properties from message
        AMQP.BasicProperties.Builder builder = buildBasicProperties(message);
        String deliveryModeString = epProperties.get(RabbitMQConstants.QUEUE_DELIVERY_MODE);
        int deliveryMode = RabbitMQConstants.DEFAULT_DELIVERY_MODE;
        if (deliveryModeString != null) {
            deliveryMode = Integer.parseInt(deliveryModeString);
        }
        // TODO : override properties from message with ones from transport properties
        // set builder properties from transport properties (overrides current properties)
        builder.deliveryMode(deliveryMode);
        builder.replyTo(replyTo);
        basicProperties = builder.build();
        OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
        MessageFormatter messageFormatter = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            messageFormatter = MessageProcessorSelector.getMessageFormatter(msgContext);
        } catch (AxisFault axisFault) {
            throw new AxisRabbitMQException("Unable to get the message formatter to use", axisFault);
        }
        // given. Queue/exchange creation, bindings should be done at the broker
        try {
            // x-consistent-hash type
            if (exchangeType != null && exchangeType.equals("x-consistent-hash")) {
                routeKey = UUID.randomUUID().toString();
            }
        } catch (UnsupportedCharsetException ex) {
            handleException("Unsupported encoding " + format.getCharSetEncoding(), ex);
        }
        try {
            messageFormatter.writeTo(msgContext, format, out, false);
            messageBody = out.toByteArray();
        } catch (IOException e) {
            handleException("IO Error while creating BytesMessage", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
        try {
            if (exchangeName != null && exchangeName != "") {
                if (log.isDebugEnabled()) {
                    log.debug("Publishing message to exchange " + exchangeName + " with route key " + routeKey);
                }
                dualChannel.getChannel().basicPublish(exchangeName, routeKey, basicProperties, messageBody);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Publishing message with route key " + routeKey);
                }
                dualChannel.getChannel().basicPublish("", routeKey, basicProperties, messageBody);
            }
        } catch (IOException e) {
            handleException("Error while publishing the message", e);
        }
    } else {
        handleException("Channel cannot be created");
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) AxisRabbitMQException(org.apache.axis2.transport.rabbitmq.utils.AxisRabbitMQException) IOException(java.io.IOException) MessageFormatter(org.apache.axis2.transport.MessageFormatter) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AMQP(com.rabbitmq.client.AMQP) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) OMOutputFormat(org.apache.axiom.om.OMOutputFormat)

Example 3 with AxisRabbitMQException

use of org.apache.axis2.transport.rabbitmq.utils.AxisRabbitMQException in project wso2-axis2-transports by wso2.

the class RabbitMQListener method doInit.

/**
 * Initialize the rabbitmq listener reading the transport configurations
 *
 * @throws AxisFault
 */
@Override
protected void doInit() throws AxisFault {
    try {
        SecretResolver secretResolver = getConfigurationContext().getAxisConfiguration().getSecretResolver();
        rabbitMQConnectionFactory = new RabbitMQConnectionFactory();
        int poolSize = RabbitMQUtils.resolveTransportDescription(getTransportInDescription(), secretResolver, rabbitMQConnectionFactory);
        rabbitMQConnectionPool = new RabbitMQConnectionPool(rabbitMQConnectionFactory, poolSize);
        log.info("RabbitMQ AMQP Transport Receiver initialized...");
    } catch (AxisRabbitMQException e) {
        throw new AxisFault("Error occurred while initializing the RabbitMQ AMQP Transport Receiver. ", e);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) SecretResolver(org.wso2.securevault.SecretResolver)

Example 4 with AxisRabbitMQException

use of org.apache.axis2.transport.rabbitmq.utils.AxisRabbitMQException in project wso2-axis2-transports by wso2.

the class RabbitMQUtils method resolveTransportDescription.

/**
 * Resolve transport parameters
 *
 * @param trpDesc                   axis2 transport parameters
 * @param secretResolver            secure vault encryption resolver
 * @param rabbitMQConnectionFactory a rabbitmq connection factory
 * @return pool size for connection and channel pooling
 */
public static int resolveTransportDescription(ParameterInclude trpDesc, SecretResolver secretResolver, RabbitMQConnectionFactory rabbitMQConnectionFactory) throws AxisRabbitMQException {
    int poolSize = RabbitMQConstants.DEFAULT_POOL_SIZE;
    for (Parameter parameter : trpDesc.getParameters()) {
        String name = parameter.getName();
        if (StringUtils.equals(name, RabbitMQConstants.PARAM_POOL_SIZE)) {
            try {
                poolSize = Integer.parseInt((String) parameter.getValue());
            } catch (NumberFormatException e) {
                throw new AxisRabbitMQException("Pool size must be an integer value.");
            }
        } else {
            Map<String, String> parameters = new HashMap<>();
            ParameterIncludeImpl pi = new ParameterIncludeImpl();
            try {
                pi.deserializeParameters((OMElement) parameter.getValue());
            } catch (AxisFault axisFault) {
                throw new AxisRabbitMQException("Error reading parameters for RabbitMQ connection factory " + name, axisFault);
            }
            for (Parameter p : pi.getParameters()) {
                OMElement paramElement = p.getParameterElement();
                String propertyValue = p.getValue().toString();
                if (paramElement != null) {
                    OMAttribute attribute = paramElement.getAttribute(new QName(RabbitMQConstants.SECURE_VAULT_NAMESPACE, RabbitMQConstants.SECRET_ALIAS_ATTRIBUTE));
                    if (attribute != null && attribute.getAttributeValue() != null && !attribute.getAttributeValue().isEmpty()) {
                        if (secretResolver == null) {
                            throw new SecureVaultException("Axis2 Secret Resolver is null. Cannot resolve " + "encrypted entry for " + p.getName());
                        }
                        if (secretResolver.isTokenProtected(attribute.getAttributeValue())) {
                            propertyValue = secretResolver.resolve(attribute.getAttributeValue());
                        }
                    }
                }
                parameters.put(p.getName(), propertyValue);
            }
            rabbitMQConnectionFactory.addConnectionFactoryConfiguration(name, parameters);
        }
    }
    return poolSize;
}
Also used : AxisFault(org.apache.axis2.AxisFault) HashMap(java.util.HashMap) ParameterIncludeImpl(org.apache.axis2.description.ParameterIncludeImpl) QName(javax.xml.namespace.QName) OMElement(org.apache.axiom.om.OMElement) SecureVaultException(org.wso2.securevault.SecureVaultException) Parameter(org.apache.axis2.description.Parameter) OMAttribute(org.apache.axiom.om.OMAttribute)

Example 5 with AxisRabbitMQException

use of org.apache.axis2.transport.rabbitmq.utils.AxisRabbitMQException in project wso2-axis2-transports by wso2.

the class RabbitMQUtils method getMessageBody.

/**
 * Get the message body from the message context
 *
 * @param msgContext the message context
 * @return the message as the byte array
 * @throws IOException
 */
public static byte[] getMessageBody(MessageContext msgContext) throws IOException, AxisRabbitMQException {
    OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
    byte[] messageBody;
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        MessageFormatter messageFormatter = MessageProcessorSelector.getMessageFormatter(msgContext);
        messageFormatter.writeTo(msgContext, format, out, false);
        messageBody = out.toByteArray();
    } catch (AxisFault axisFault) {
        throw new AxisRabbitMQException("Unable to get the message formatter to use", axisFault);
    }
    return messageBody;
}
Also used : AxisFault(org.apache.axis2.AxisFault) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MessageFormatter(org.apache.axis2.transport.MessageFormatter) OMOutputFormat(org.apache.axiom.om.OMOutputFormat)

Aggregations

AxisFault (org.apache.axis2.AxisFault)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 IOException (java.io.IOException)3 OMOutputFormat (org.apache.axiom.om.OMOutputFormat)3 MessageFormatter (org.apache.axis2.transport.MessageFormatter)3 AxisRabbitMQException (org.apache.axis2.transport.rabbitmq.utils.AxisRabbitMQException)3 AMQP (com.rabbitmq.client.AMQP)2 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)2 SecretResolver (org.wso2.securevault.SecretResolver)2 HashMap (java.util.HashMap)1 QName (javax.xml.namespace.QName)1 OMAttribute (org.apache.axiom.om.OMAttribute)1 OMElement (org.apache.axiom.om.OMElement)1 MessageContext (org.apache.axis2.context.MessageContext)1 Parameter (org.apache.axis2.description.Parameter)1 ParameterIncludeImpl (org.apache.axis2.description.ParameterIncludeImpl)1 RabbitMQMessage (org.apache.axis2.transport.rabbitmq.RabbitMQMessage)1 RabbitMQRPCMessageSender (org.apache.axis2.transport.rabbitmq.rpc.RabbitMQRPCMessageSender)1 SecureVaultException (org.wso2.securevault.SecureVaultException)1