Ejemplo n.º 1
0
        internal static HttpResponsePacket ToHttpResponse(HttpResponse response, ServiceMessage msg)
        {
            var rsp = new HttpResponsePacket();

            foreach (var hdr in response.Headers)
            {
                // TODO: Fix adding response headers
                //AddHttpHeader(hdr);
            }

            //TODO: Decide if to read mostly from ServiceMessage or from response.

            //rsp.Version = response.... //TODO: Add a default version here
            rsp.StatusCode = (int)response.StatusCode;
            rsp.StatusDescription = ((IHttpResponseFeature)msg).ReasonPhrase;

            if (response.Body != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    response.Body.Position = 0;
                    response.Body.CopyTo(ms);
                    rsp.Content = ms.ToArray();
                }
            }

            return rsp;
        }
Ejemplo n.º 2
0
        internal static HttpResponsePacket ToHttpResponsePacket(this ServiceMessage message)
        {
            if (message == null) throw new ArgumentNullException("message");

            var response = new HttpResponsePacket();

            var respFeature = message as IHttpResponseFeature;
            if (respFeature.Headers != null)
            {
                foreach (var hdr in respFeature.Headers)
                {
                    response.Headers.Add(hdr.Key, hdr.Value);
                }
            }

            response.Version = HTTP_RESPONSE_VERSION;
            response.StatusCode = respFeature.StatusCode;
            response.StatusDescription = respFeature.ReasonPhrase;

            if (respFeature.Body != null)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    respFeature.Body.Position = 0;
                    respFeature.Body.CopyTo(ms);
                    response.Content = ms.ToArray();
                }
            }

            return response;
        }
Ejemplo n.º 3
0
        private HttpResponsePacket CreateResponsePacketFromMessage(HttpResponseMessage responseMsg, IRestBusSubscriber subscriber)
        {
            //TODO: Confirm that commas in response headers are merged iproperly into packet header
            var responsePkt = new HttpResponsePacket(responseMsg);

            //Add/Update Subscriber-Id header
            responsePkt.Headers[Common.Shared.SUBSCRIBER_ID_HEADER] = new string[] { subscriber == null ? String.Empty : subscriber.Id ?? String.Empty };

            return responsePkt;
        }
Ejemplo n.º 4
0
        public static HttpResponsePacket Deserialize(byte[] data)
        {
            if (data == null) throw new ArgumentNullException("data");

            //if (SerializeAsBson)
            //{
            //    return CommonUtils.DeserializeFromBson<HttpResponsePacket>(data);
            //}

            HttpMessageReader reader = new HttpMessageReader(data);

            HttpResponsePacket response = new HttpResponsePacket();

            bool isFirstLine = true;
            string text;
            while ((text = reader.NextLine()) != null)
            {
                if (isFirstLine)
                {
                    isFirstLine = false;
                    string[] components = text.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries);

                    if (components.Length < 2)
                    {
                        throw new InvalidOperationException("Unable to deserialize data into HttpPacket");
                    }

                    if (!components[0].ToUpperInvariant().StartsWith("HTTP/") || components[0].Length <= 5 )
                    {
                        throw new InvalidOperationException("Unable to deserialize data into HttpPacket");
                    }

                    response.Version = components[0].Substring(5).Trim();
                    int statusCode = 0;
                    Int32.TryParse(components[1], out statusCode);
                    response.StatusCode = statusCode;

                    if (components.Length > 2)
                    {
                        string statusDescription = components[2].Trim();

                        for (int i = 3; i < components.Length; i++)
                        {
                            //TODO: Should I convert this to a string builder. Is it worth it?
                            statusDescription += (" " + components[i]);
                        }
                        response.StatusDescription = statusDescription;

                    }
                    else
                    {
                        response.StatusDescription = String.Empty;
                    }
                }
                else
                {
                    ParseLineIntoHeaders(text, response.Headers);
                }
            }

            if (isFirstLine || !reader.IsContentReady)
            {
                throw new InvalidOperationException("Unable to deserialize data into HttpPacket");
            }

            response.Content = reader.GetContent();

            return response;
        }
Ejemplo n.º 5
0
        public void SendResponse(MessageContext context, HttpResponsePacket response )
        {
            if (disposed) throw new ObjectDisposedException("Subscriber has been disposed");
            if (String.IsNullOrEmpty(context.ReplyToQueue)) return;

            if (conn == null)
            {
                //TODO: Log this -- it technically shouldn't happen. Also translate to a HTTP Unreachable because it means StartCallbackQueueConsumer didn't create a connection
                throw new ApplicationException("This is Bad");
            }

            //TODO: Channel Pool this connection
            using (IModel channel = conn.CreateModel())
            {

                BasicProperties basicProperties = new BasicProperties { CorrelationId = context.CorrelationId };

                try
                {
                    channel.BasicPublish(String.Empty,
                                    context.ReplyToQueue,
                                    basicProperties,
                                    response.Serialize());
                }
                catch {
                    //TODO: Log execption
                }
            }
        }
Ejemplo n.º 6
0
        public static HttpResponsePacket Deserialize(byte[] data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            //if (SerializeAsBson)
            //{
            //    return CommonUtils.DeserializeFromBson<HttpResponsePacket>(data);
            //}

            HttpMessageReader reader = new HttpMessageReader(data);

            HttpResponsePacket response = new HttpResponsePacket();

            bool   isFirstLine = true;
            string text;

            while ((text = reader.NextLine()) != null)
            {
                if (isFirstLine)
                {
                    isFirstLine = false;
                    string[] components = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    if (components.Length < 2)
                    {
                        throw new InvalidOperationException("Unable to deserialize data into HttpPacket");
                    }

                    if (!components[0].StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase) || components[0].Length <= 5)
                    {
                        throw new InvalidOperationException("Unable to deserialize data into HttpPacket");
                    }

                    response.Version = components[0].Substring(5).Trim();
                    int statusCode = 0;
                    Int32.TryParse(components[1], out statusCode);
                    response.StatusCode = statusCode;

                    if (components.Length > 2)
                    {
                        string statusDescription = components[2].Trim();

                        for (int i = 3; i < components.Length; i++)
                        {
                            //TODO: Convert to a string builder? Is it worth it?
                            statusDescription += (" " + components[i]);
                        }
                        response.StatusDescription = statusDescription;
                    }
                    else
                    {
                        response.StatusDescription = String.Empty;
                    }
                }
                else
                {
                    ParseLineIntoHeaders(text, response.Headers);
                }
            }

            if (isFirstLine || !reader.IsContentReady)
            {
                throw new InvalidOperationException("Unable to deserialize data into HttpPacket");
            }

            response.Content = reader.GetContent();

            return(response);
        }
Ejemplo n.º 7
0
        public void SendResponse(MessageContext context, HttpResponsePacket response )
        {
            if (disposed) throw new ObjectDisposedException(GetType().FullName);

            var dispatch = context.Dispatch as MessageDispatch;
            if (dispatch != null)
            {
                //Ack request
                if(Settings.AckBehavior != SubscriberAckBehavior.Automatic && dispatch.Consumer.Model.IsOpen)
                {
                    dispatch.Consumer.Model.BasicAck(dispatch.Delivery.DeliveryTag, false);

                    //NOTE: The call above takes place in different threads silmultaneously
                    //In which case multiple threads will be using the same channel at the same time.
                    //It's okay in this case, because transmissions within a channel are synchronized, as seen in:
                    //https://github.com/rabbitmq/rabbitmq-dotnet-client/blob/f16c093f6409e11d9d77115038cb224eb39468ec/projects/client/RabbitMQ.Client/src/client/impl/ModelBase.cs#L459
                    //and
                    //https://github.com/rabbitmq/rabbitmq-dotnet-client/blob/f16c093f6409e11d9d77115038cb224eb39468ec/projects/client/RabbitMQ.Client/src/client/impl/SessionBase.cs#L177
                }
            }

            //Exit method if no replyToQueue was specified.
            if (String.IsNullOrEmpty(context.ReplyToQueue)) return;

            if (_subscriberPool.Connection == null)
            {
                //TODO: Log this -- it technically shouldn't happen. Also translate to a HTTP Unreachable because it means StartCallbackQueueConsumer didn't create a connection
                throw new ApplicationException("This is Bad");
            }

            //Add/Update Subscriber-Id header
            response.Headers[Common.Shared.SUBSCRIBER_ID_HEADER] = subscriberIdHeader;

            //Send response
            var pooler = _subscriberPool;
            AmqpModelContainer model = null;
            try
            {
                model = pooler.GetModel(ChannelFlags.None);
                BasicProperties basicProperties = new BasicProperties { CorrelationId = context.CorrelationId };

                model.Channel.BasicPublish(String.Empty,
                                context.ReplyToQueue,
                                basicProperties,
                                response.Serialize());
            }
            finally
            {
                if(model != null)
                {
                    model.Close();
                }
            }
        }
Ejemplo n.º 8
0
        private static bool TryGetHttpResponseMessage(HttpResponsePacket packet, out HttpResponseMessage response)
        {
            try
            {
                response = new HttpResponseMessage
                {
                    Content = packet.Content == null ? RestBusClient._emptyByteArrayContent : new ByteArrayContent(packet.Content),
                    Version = packet.Version == "1.1" ? VERSION_1_1 : new Version(packet.Version),
                    ReasonPhrase = packet.StatusDescription,
                    StatusCode = (System.Net.HttpStatusCode)packet.StatusCode
                };

                packet.PopulateHeaders(response.Content.Headers, response.Headers);
            }
            catch
            {
                response = null;
                return false;
            }

            return true;
        }
Ejemplo n.º 9
0
        internal static HttpResponsePacket ToHttpResponsePacket(this ServiceMessage message)
        {
            if (message == null) throw new ArgumentNullException("message");

            var response = new HttpResponsePacket();

            var respFeature = message as IHttpResponseFeature;
            if (respFeature.Headers != null)
            {
                foreach (var hdr in respFeature.Headers)
                {
                    response.Headers.Add(hdr.Key, hdr.Value);
                }
            }

            response.Version = HTTP_RESPONSE_VERSION;
            response.StatusCode = respFeature.StatusCode;
            if(String.IsNullOrEmpty(respFeature.ReasonPhrase))
            {
                response.StatusDescription = ReasonPhrases.ToReasonPhrase(response.StatusCode) ?? "Unknown";
            }
            else
            {
                response.StatusDescription = respFeature.ReasonPhrase;
            }
            
            if (message.OriginalResponseBody != null && message.OriginalResponseBody.CanRead)
            {
                //NOTE: OriginalResponseBody.CanRead will be false if the stream was disposed.

                response.Content = message.OriginalResponseBody.ToArray();
            }

            //Add/Update Server header
            response.Headers["Server"] = HTTP_RESPONSE_SERVER_HEADER;

            return response;
        }