Search in sources :

Example 1 with MessageFormatter

use of org.apache.axis2.transport.MessageFormatter in project wso2-axis2-transports by wso2.

the class MqttSender method createMqttMessage.

private MqttMessage createMqttMessage(MessageContext messageContext) {
    OMOutputFormat format = BaseUtils.getOMOutputFormat(messageContext);
    MessageFormatter messageFormatter;
    try {
        messageFormatter = MessageProcessorSelector.getMessageFormatter(messageContext);
    } catch (AxisFault axisFault) {
        throw new AxisMqttException("Unable to get the message formatter to use");
    }
    OutputStream out;
    StringWriter sw = new StringWriter();
    try {
        out = new WriterOutputStream(sw, format.getCharSetEncoding());
    } catch (UnsupportedCharsetException ex) {
        throw new AxisMqttException("Unsupported encoding " + format.getCharSetEncoding(), ex);
    }
    try {
        messageFormatter.writeTo(messageContext, format, out, true);
        out.close();
    } catch (IOException e) {
        throw new AxisMqttException("IO Error while creating BytesMessage", e);
    }
    MqttMessage mqttMessage = new MqttMessage();
    mqttMessage.setPayload(sw.toString().getBytes());
    return mqttMessage;
}
Also used : AxisFault(org.apache.axis2.AxisFault) StringWriter(java.io.StringWriter) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) OutputStream(java.io.OutputStream) WriterOutputStream(org.apache.commons.io.output.WriterOutputStream) MessageFormatter(org.apache.axis2.transport.MessageFormatter) IOException(java.io.IOException) OMOutputFormat(org.apache.axiom.om.OMOutputFormat) WriterOutputStream(org.apache.commons.io.output.WriterOutputStream)

Example 2 with MessageFormatter

use of org.apache.axis2.transport.MessageFormatter 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 3 with MessageFormatter

use of org.apache.axis2.transport.MessageFormatter in project wso2-axis2-transports by wso2.

the class UDPSender method sendMessage.

@Override
public void sendMessage(MessageContext msgContext, String targetEPR, OutTransportInfo outTransportInfo) throws AxisFault {
    UDPOutTransportInfo udpOutInfo;
    if ((targetEPR == null) && (outTransportInfo != null)) {
        // this can happen only at the server side and send the message using back chanel
        udpOutInfo = (UDPOutTransportInfo) outTransportInfo;
    } else {
        udpOutInfo = new UDPOutTransportInfo(targetEPR);
    }
    MessageFormatter messageFormatter = MessageProcessorSelector.getMessageFormatter(msgContext);
    OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
    format.setContentType(udpOutInfo.getContentType());
    byte[] payload = messageFormatter.getBytes(msgContext, format);
    try {
        DatagramSocket socket = new DatagramSocket();
        if (log.isDebugEnabled()) {
            log.debug("Sending " + payload.length + " bytes to " + udpOutInfo.getAddress());
        }
        try {
            socket.send(new DatagramPacket(payload, payload.length, udpOutInfo.getAddress()));
            if (!msgContext.getOptions().isUseSeparateListener() && !msgContext.isServerSide()) {
                waitForReply(msgContext, socket, udpOutInfo.getContentType());
            }
        } finally {
            socket.close();
        }
    } catch (IOException ex) {
        throw new AxisFault("Unable to send packet", ex);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket) MessageFormatter(org.apache.axis2.transport.MessageFormatter) IOException(java.io.IOException) OMOutputFormat(org.apache.axiom.om.OMOutputFormat)

Example 4 with MessageFormatter

use of org.apache.axis2.transport.MessageFormatter in project wso2-axis2-transports by wso2.

the class MSMQSender method createMSMQMessage.

/**
 * Generating MSMQ message wrapper in order to communicate with JNI
 * @param msgCtx
 * @param contentTypeProperty
 * @param queuName
 * @return
 * @throws AxisFault
 */
private Message createMSMQMessage(MessageContext msgCtx, String messageContentType, String queuName) throws AxisFault {
    String msgBody = null;
    byte[] msgByteBody = null;
    String msgType = getProperty(msgCtx, MSMQConstants.MSMQ_MESSAGE_TYPE);
    // String msgLable = "L:" + queuName+"["+contentType+"]"; // TODO
    // check the first element of the SOAP body, do we have content wrapped
    // using the
    // default wrapper elements for binary
    // (BaseConstants.DEFAULT_BINARY_WRAPPER) or
    // text (BaseConstants.DEFAULT_TEXT_WRAPPER) ? If so, do not create SOAP
    // messages
    // for MSMQ but just get the payload in its native format
    String msmqMessageType = guessMessageType(msgCtx);
    if (msmqMessageType == null) {
        OMOutputFormat format = BaseUtils.getOMOutputFormat(msgCtx);
        MessageFormatter messageFormatter = null;
        try {
            messageFormatter = MessageProcessorSelector.getMessageFormatter(msgCtx);
        } catch (AxisFault axisFault) {
            handleException("Unable to get the message formatter to use", axisFault);
        }
        String contentType = messageFormatter != null ? messageFormatter.getContentType(msgCtx, format, msgCtx.getSoapAction()) : "";
        boolean useBytesMessage = msgType != null && MSMQConstants.MSMQ_BYTE_MESSAGE.equals(msgType) || contentType.indexOf(HTTPConstants.HEADER_ACCEPT_MULTIPART_RELATED) > -1;
        OutputStream out = null;
        StringWriter sw = null;
        if (useBytesMessage) {
        // TODO: handle MSMQ byte message here
        } else {
            sw = new StringWriter();
            try {
                out = new WriterOutputStream(sw, format.getCharSetEncoding());
            } catch (UnsupportedCharsetException ex) {
                handleException("Unsupported encoding " + format.getCharSetEncoding(), ex);
            }
        }
        try {
            if (out != null) {
                messageFormatter.writeTo(msgCtx, format, out, true);
                out.close();
            }
        } catch (IOException e) {
            handleException("IO Error while creating BytesMessage", e);
        }
        if (!useBytesMessage) {
            msgBody = sw.toString();
        }
    } else if (MSMQConstants.MSMQ_BYTE_MESSAGE.equals(msmqMessageType)) {
    // TODO. handle .net byte messages here.
    } else if (MSMQConstants.MSMQ_TEXT_MESSAGE.equals(msmqMessageType)) {
        msgBody = msgCtx.getEnvelope().getBody().getFirstChildWithName(BaseConstants.DEFAULT_TEXT_WRAPPER).getText();
    }
    try {
        // Keep message correlation empty will be deciding later on the process
        Message message = new Message(msgBody != null ? msgBody : "", "", "");
        return message;
    } catch (UnsupportedEncodingException e) {
        log.error("Unsported message has been received: ", e);
        handleEexception("Unsported message has been received: ", e);
    }
    return null;
}
Also used : AxisFault(org.apache.axis2.AxisFault) Message(org.apache.axis2.transport.msmq.util.Message) OutputStream(java.io.OutputStream) WriterOutputStream(org.apache.commons.io.output.WriterOutputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MessageFormatter(org.apache.axis2.transport.MessageFormatter) IOException(java.io.IOException) WriterOutputStream(org.apache.commons.io.output.WriterOutputStream) StringWriter(java.io.StringWriter) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) OMOutputFormat(org.apache.axiom.om.OMOutputFormat)

Example 5 with MessageFormatter

use of org.apache.axis2.transport.MessageFormatter 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)

Aggregations

OMOutputFormat (org.apache.axiom.om.OMOutputFormat)8 MessageFormatter (org.apache.axis2.transport.MessageFormatter)8 AxisFault (org.apache.axis2.AxisFault)7 IOException (java.io.IOException)6 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)5 OutputStream (java.io.OutputStream)3 StringWriter (java.io.StringWriter)3 WriterOutputStream (org.apache.commons.io.output.WriterOutputStream)3 AMQP (com.rabbitmq.client.AMQP)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 DataHandler (javax.activation.DataHandler)2 AxisRabbitMQException (org.apache.axis2.transport.rabbitmq.utils.AxisRabbitMQException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 DatagramPacket (java.net.DatagramPacket)1 DatagramSocket (java.net.DatagramSocket)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 SystemException (javax.transaction.SystemException)1 Transaction (javax.transaction.Transaction)1 TransactionManager (javax.transaction.TransactionManager)1 OMElement (org.apache.axiom.om.OMElement)1