Esempio n. 1
0
        public async Task SendMessageAsync(IMessage inputMessage)
        {
            Preconditions.CheckNotNull(inputMessage, nameof(inputMessage));
            IMessageConverter <Message> converter = this.messageConverterProvider.Get <Message>();
            Message message = converter.FromMessage(inputMessage);

            await this.ResetTimerAsync();

            try
            {
                string outputRoute = inputMessage.GetOutput();
                using (Metrics.TimeMessageSend(this.clientId, outputRoute))
                {
                    Metrics.MessageProcessingLatency(this.clientId, inputMessage);
                    await this.client.SendEventAsync(message);

                    Events.SendMessage(this);
                    Metrics.AddSentMessages(this.clientId, 1, outputRoute, inputMessage.ProcessedPriority);
                }
            }
            catch (Exception ex)
            {
                Events.ErrorSendingMessage(this, ex);
                await this.HandleException(ex);

                throw;
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Convert from a NMS Message to a .NET object.
        /// </summary>
        /// <param name="messageToConvert">the message to convert</param>
        /// <returns>the converted .NET object</returns>
        /// <throws>MessageConversionException in case of conversion failure </throws>
        public object FromMessage(IMessage messageToConvert)
        {
            if (messageToConvert == null)
            {
                throw new MessageConversionException("Can't convert null message");
            }
            try
            {
                string converterId = messageToConvert.Properties.GetString(typeMapper.TypeIdFieldName);
                if (converterId == null)
                {
                    return(defaultMessageConverter.FromMessage(messageToConvert));
                }
                ITextMessage textMessage = messageToConvert as ITextMessage;
                if (textMessage == null)
                {
                    throw new MessageConversionException("Can't convert message of type " +
                                                         messageToConvert.GetType());
                }

                using (MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(textMessage.Text)))
                {
                    XmlSerializer xs            = new XmlSerializer(GetTargetType(textMessage));
                    XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
                    return(xs.Deserialize(memoryStream));
                }
            } catch (Exception e)
            {
                throw new MessageConversionException("Can't convert message of type " + messageToConvert.GetType(), e);
            }
        }
Esempio n. 3
0
        public async Task SendMessageBatchAsync(IEnumerable <IMessage> inputMessages)
        {
            IMessageConverter <Message> converter = this.messageConverterProvider.Get <Message>();
            string          metricOutputRoute     = null;
            IList <Message> messages = Preconditions.CheckNotNull(inputMessages, nameof(inputMessages))
                                       .Select(inputMessage =>
            {
                metricOutputRoute = metricOutputRoute ?? inputMessage.GetOutput();
                Metrics.MessageProcessingLatency(this.clientId, inputMessage);
                return(converter.FromMessage(inputMessage));
            })
                                       .ToList();

            this.timer.Reset();
            try
            {
                using (Metrics.TimeMessageSend(this.clientId))
                {
                    await this.client.SendEventBatchAsync(messages);

                    Events.SendMessage(this);
                    Metrics.AddSentMessages(this.clientId, messages.Count, metricOutputRoute);
                }
            }
            catch (Exception ex)
            {
                Events.ErrorSendingBatchMessage(this, ex);
                await this.HandleException(ex);

                throw;
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Convert from a NMS Message to a .NET object.
        /// </summary>
        /// <param name="nmsMessage">the message to convert</param>
        /// <returns>the converted .NET object</returns>
        /// <throws>MessageConversionException in case of conversion failure </throws>
        public object FromMessage(Apache.NMS.IMessage nmsMessage)
        {
            MessageBuilder builder = null;

            if (extractNmsMessageBody)
            {
                object conversionResult = converter.FromMessage(nmsMessage);
                if (conversionResult == null)
                {
                    return(null);
                }
                if (conversionResult is Spring.Integration.Core.IMessage)
                {
                    builder = MessageBuilder.FromMessage((Spring.Integration.Core.IMessage)conversionResult);
                }
                else
                {
                    builder = MessageBuilder.WithPayload(conversionResult);
                }
            }
            else
            {
                builder = MessageBuilder.WithPayload(nmsMessage);
            }
            IDictionary <string, object> headers = headerMapper.ToHeaders(nmsMessage);

            Spring.Integration.Core.IMessage message = builder.CopyHeadersIfAbsent(headers).Build();
            if (logger.IsDebugEnabled)
            {
                logger.Debug("Converted NMS Message [" + nmsMessage + "] to integration message [" + message + "]");
            }
            return(message);
        }
Esempio n. 5
0
        protected virtual IMessage BuildReturnedMessage(IMessage message, int replyCode, string replyText, string exchange, string returnedRoutingKey, IMessageConverter converter)
        {
            var returnedObject = converter.FromMessage(message, null);
            var builder        = PrepareMessageBuilder(returnedObject);

            // TODO: Map < String, ?> headers = getHeaderMapper().toHeadersFromReply(message.getMessageProperties());
            if (ErrorMessageStrategy == null)
            {
                builder.CopyHeadersIfAbsent(message.Headers)
                .SetHeader(RabbitMessageHeaders.RETURN_REPLY_CODE, replyCode)
                .SetHeader(RabbitMessageHeaders.RETURN_REPLY_TEXT, replyText)
                .SetHeader(RabbitMessageHeaders.RETURN_EXCHANGE, exchange)
                .SetHeader(RabbitMessageHeaders.RETURN_ROUTING_KEY, returnedRoutingKey);
            }

            var returnedMessage = builder.Build();

            if (ErrorMessageStrategy != null)
            {
                returnedMessage = ErrorMessageStrategy.BuildErrorMessage(
                    new ReturnedRabbitMessageException(returnedMessage, replyCode, replyText, exchange, returnedRoutingKey),
                    null);
            }

            return(returnedMessage);
        }
        private object ConvertPayload(IMessage message, ParameterInfo parameter, Type targetPayloadType)
        {
            object result = null;

            if (_converter is ISmartMessageConverter)
            {
                var smartConverter = (ISmartMessageConverter)_converter;
                result = smartConverter.FromMessage(message, targetPayloadType, parameter);
            }
            else if (_converter != null)
            {
                result = _converter.FromMessage(message, targetPayloadType);
            }

            if (result == null)
            {
                var payloadType = message.Payload != null?message.Payload.GetType().ToString() : "null";

                throw new MessageConversionException(
                          message,
                          "No converter found from actual payload type '" + payloadType + "' to expected payload type '" + targetPayloadType.ToString() + "'");
            }

            return(result);
        }
Esempio n. 7
0
        protected virtual IMessageBuilder BuildReply(IMessageConverter converter, IMessage amqpReplyMessage)
        {
            var replyObject = converter.FromMessage(amqpReplyMessage, null);
            var builder     = PrepareMessageBuilder(replyObject);

            // var headers = getHeaderMapper().toHeadersFromReply(amqpReplyMessage.getMessageProperties());
            builder.CopyHeadersIfAbsent(amqpReplyMessage.Headers);
            return(builder);
        }
Esempio n. 8
0
        /// <summary>
        /// Extract the message body from the given message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns>the content of the message, to be passed into the
        /// listener method as argument</returns>
        /// <exception cref="EMSException">if thrown by EMS API methods</exception>
        private object ExtractMessage(Message message)
        {
            IMessageConverter converter = MessageConverter;

            if (converter != null)
            {
                return(converter.FromMessage(message));
            }
            return(message);
        }
        /// <summary>
        /// Extracts the message body from the given message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns>the content of the message, to be passed into the
        /// listener method as argument</returns>
        protected virtual object ExtractMessage(Message message)
        {
            IMessageConverter converter = MessageConverter;

            if (converter != null)
            {
                return(converter.FromMessage(message));
            }
            return(message);
        }
        public virtual object ResolveArgument(ParameterInfo parameter, IMessage message)
        {
            var ann = parameter.GetCustomAttribute <PayloadAttribute>();

            if (ann != null && !string.IsNullOrEmpty(ann.Expression))
            {
                throw new InvalidOperationException("Payload expressions not supported by this resolver");
            }

            var payload = message.Payload;

            if (IsEmptyPayload(payload))
            {
                if (ann == null || ann.Required)
                {
                    var paramName = GetParameterName(parameter);
                    throw new MethodArgumentNotValidException(message, parameter, "Payload value must not be empty when binding to: " + paramName);
                }
                else
                {
                    return(null);
                }
            }

            var targetClass  = ResolveTargetClass(parameter, message);
            var payloadClass = payload.GetType();

            if (targetClass.IsAssignableFrom(payloadClass))
            {
                Validate(message, parameter, payload);
                return(payload);
            }
            else
            {
                if (_converter is ISmartMessageConverter)
                {
                    var smartConverter = (ISmartMessageConverter)_converter;
                    payload = smartConverter.FromMessage(message, targetClass, parameter);
                }
                else
                {
                    payload = _converter.FromMessage(message, targetClass);
                }

                if (payload == null)
                {
                    throw new MessageConversionException(message, "Cannot convert from [" + payloadClass.Name + "] to [" + targetClass.Name + "] for " + message);
                }

                Validate(message, parameter, payload);

                return(payload);
            }
        }
Esempio n. 11
0
        public async Task SendMessageAsync(IMessage inputMessage)
        {
            Preconditions.CheckNotNull(inputMessage, nameof(inputMessage));
            IMessageConverter <Message> converter = this.messageConverterProvider.Get <Message>();
            Message message = converter.FromMessage(inputMessage);

            try
            {
                await this.client.SendEventAsync(message);

                Events.SendMessage(this);
            }
            catch (Exception ex)
            {
                Events.ErrorSendingMessage(this, ex);
                await this.HandleException(ex);

                throw;
            }
        }
Esempio n. 12
0
        public async Task SendMessageBatchAsync(IEnumerable <IMessage> inputMessages)
        {
            IMessageConverter <Message> converter = this.messageConverterProvider.Get <Message>();
            IEnumerable <Message>       messages  = Preconditions.CheckNotNull(inputMessages, nameof(inputMessages))
                                                    .Select(inputMessage => converter.FromMessage(inputMessage));

            try
            {
                await this.client.SendEventBatchAsync(messages);

                Events.SendMessage(this);
            }
            catch (Exception ex)
            {
                Events.ErrorSendingBatchMessage(this, ex);
                await this.HandleException(ex);

                throw;
            }
        }
Esempio n. 13
0
        public async Task SendMessageBatchAsync(IEnumerable <IMessage> inputMessages)
        {
            IMessageConverter <Message> converter = this.messageConverterProvider.Get <Message>();
            string          metricOutputRoute     = null;
            IList <Message> messages = Preconditions.CheckNotNull(inputMessages, nameof(inputMessages))
                                       .Select(inputMessage =>
            {
                metricOutputRoute = metricOutputRoute ?? inputMessage.GetOutput();
                Metrics.MessageProcessingLatency(this.clientId, inputMessage);
                return(converter.FromMessage(inputMessage));
            })
                                       .ToList();

            await this.ResetTimerAsync();

            try
            {
                using (Metrics.TimeMessageSend(this.clientId, metricOutputRoute))
                {
                    await this.client.SendEventBatchAsync(messages);

                    Events.SendMessage(this);

                    if (messages.Count > 0)
                    {
                        // Priority for messages in any given batch is the same, so we can
                        // just use the priority from the first message in the collection
                        Metrics.AddSentMessages(this.clientId, messages.Count, metricOutputRoute, inputMessages.First().ProcessedPriority);
                    }
                }
            }
            catch (Exception ex)
            {
                Events.ErrorSendingBatchMessage(this, ex);
                await this.HandleException(ex);

                throw;
            }
        }
Esempio n. 14
0
        public object FromMessage(IMessage messageToConvert)
        {
            if (messageToConvert == null)
            {
                throw new MessageConversionException("Can't convert null message");
            }
            string converterId = messageToConvert.Properties.GetString(converterIdFieldName);

            if (converterId == null)
            {
                return(defaultMessageConverter.FromMessage(messageToConvert));
            }
            else
            {
                IMessageConverter converter = GetConverterForId(converterId);
                if (converter != null)
                {
                    return(converter.FromMessage(messageToConvert));
                }
                throw new MessageConversionException("Can't convert message with ConverterId = " + converterId + ".  Message = " + messageToConvert);
            }
        }