public async Task <byte[]> Serialize(HttpResponseMessage response, CancellationToken token)
        {
            var request = response.RequestMessage;

            response.RequestMessage = null;

            if (response.Content != null)
            {
                await response.Content.LoadIntoBufferAsync();
            }

            var httpMessageContent = new HttpMessageContent(response);

            token.ThrowIfCancellationRequested();

            var buffer = await httpMessageContent.ReadAsByteArrayAsync();

            response.RequestMessage = request;

            using (var stream = new MemoryStream())
            {
                await stream.WriteAsync(buffer, 0, buffer.Length, token);

                return(stream.ToArray());
            }
        }
        public Task SerializeAsync(HttpRequestMessage request, Stream stream)
        {
            if (request.Content != null)
            {
                return request.Content.LoadIntoBufferAsync()
                    .Then(() =>
                    {
                        var httpMessageContent = new HttpMessageContent(request);
                        // All in-memory and CPU-bound so no need to async
                        httpMessageContent.ReadAsByteArrayAsync().Then(
                            buffer =>
                                {
                                    return Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite,
                                        buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent);
                                });
                    });
            }
            else
            {
                var httpMessageContent = new HttpMessageContent(request);
                // All in-memory and CPU-bound so no need to async
                return httpMessageContent.ReadAsByteArrayAsync().Then(
                    buffer =>
                        {
                            return Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite,
                                  buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent);
                        }
                    );

            }

        }
예제 #3
0
        /// <inheritdoc />
        public async Task <Message <byte[], byte[]> > Convert(HttpRequestMessage request)
        {
            _log.LogTrace("create full HttpRequestMessage to kafka");
            var content   = new HttpMessageContent(request);
            var bytesTask = content.ReadAsByteArrayAsync();

            var message = new Message <byte[], byte[]>
            {
                Key       = null,
                Value     = await bytesTask,
                Timestamp = new Timestamp(DateTimeOffset.Now.ToUnixTimeMilliseconds(), TimestampType.CreateTime),
            };

            if (request.Headers.TryGetValues(KafkaQueueConsts.KafkaKey, out var key))
            {
                var firstKey = key.FirstOrDefault();
                if (string.IsNullOrWhiteSpace(firstKey))
                {
                    throw new ArgumentException($"If header {KafkaQueueConsts.KafkaKey} set, then header cannot be null or empty");
                }
                _log.LogTrace($"Add key", firstKey);

                message.Key = KafkaExtensions.HeaderValue(firstKey);
            }

            return(message);
        }
예제 #4
0
        public async Task <HttpResponseMessage> Send(HttpRequestMessage request, CancellationToken token)
        {
            var options = request.Properties.ContainsKey(NatsQueueClientOption.ConnectionProperty)
                                ? request.Properties[NatsQueueClientOption.ConnectionProperty] as Options
                                : _clientOption.Options;

            if (options == null)
            {
                throw new ArgumentException(
                          $"ConnectionFactory in option or {nameof(request.Properties)} key name {NatsQueueClientOption.ConnectionProperty} must be set");
            }

            var content     = new HttpMessageContent(request);
            var bytesTask   = content.ReadAsByteArrayAsync();
            var correlation = request.Headers.GetCorrelationHeader();
            var connection  = _connection.CreateConnection(options);

            if (correlation != null)
            {
                var responseMsg = await connection.RequestAsync(request.RequestUri.Host, await bytesTask, token);

                var responseMessage = await _responseParser.Parse(responseMsg.Data, token);

                return(responseMessage);
            }

            var bytes = await bytesTask;

            connection.Publish(request.RequestUri.Host, bytes);
            _log.LogTrace("Message to {url} sended", request.RequestUri.Host);

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
        public Task SerializeAsync(Task <HttpResponseMessage> response, Stream stream)
        {
            return(response.Then(r =>
            {
                if (r.Content != null)
                {
                    return r.Content.LoadIntoBufferAsync()
                    .Then(() =>
                    {
                        var httpMessageContent = new HttpMessageContent(r);
                        // All in-memory and CPU-bound so no need to async
                        return httpMessageContent.ReadAsByteArrayAsync();
                    })
                    .Then(buffer =>
                    {
                        return Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite,
                                                      buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent);
                    }
                          );

                    ;
                }
                else
                {
                    var httpMessageContent = new HttpMessageContent(r);
                    // All in-memory and CPU-bound so no need to async
                    var buffer = httpMessageContent.ReadAsByteArrayAsync().Result;
                    return Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite,
                                                  buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent);
                }
            }
                                 ));
        }
        public async Task SerializeAsync(Task <HttpResponseMessage> response, Stream stream)
        {
            var r = await response;

            if (r.Content != null)
            {
                await r.Content.LoadIntoBufferAsync();

                var httpMessageContent = new HttpMessageContent(r);
                // All in-memory and CPU-bound so no need to async
                var buffer = await httpMessageContent.ReadAsByteArrayAsync();

                await Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite,
                                             buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent);
            }
            else
            {
                var httpMessageContent = new HttpMessageContent(r);
                // All in-memory and CPU-bound so no need to async
                var buffer = await httpMessageContent.ReadAsByteArrayAsync();

                await Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite,
                                             buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent);
            }
        }
예제 #7
0
        public async Task <byte[]> Convert(HttpResponse response)
        {
            if (response.Body.CanSeek)
            {
                response.Body.Position = 0;
            }

            var message = new HttpResponseMessage
            {
                StatusCode = (HttpStatusCode)response.StatusCode,
                Content    = new StreamContent(response.Body),
            };

            message.Content.Headers.ContentType   = MediaTypeHeaderValue.Parse(response.ContentType);
            message.Content.Headers.ContentLength = response.Body.Length;

            foreach (var header in response.Headers)
            {
                message.Headers.TryAddWithoutValidation(header.Key, header.Value.AsEnumerable());
            }

            var content = new HttpMessageContent(message);
            var bytes   = await content.ReadAsByteArrayAsync();

            return(bytes);
        }
예제 #8
0
        public async Task SerializeAsync(HttpRequestMessage request, Stream stream)
        {
            if (request.Content != null && _bufferContent)
            {
                await request.Content.LoadIntoBufferAsync();
            }

            var httpMessageContent = new HttpMessageContent(request);
            var buffer             = await httpMessageContent.ReadAsByteArrayAsync();

            stream.Write(buffer, 0, buffer.Length);
        }
        public Task SerializeAsync(Task <HttpResponseMessage> response, Stream stream)
        {
            return(response.Then(r =>
            {
                if (r.Content != null)
                {
                    TraceWriter.WriteLine("SerializeAsync - before load",
                                          TraceLevel.Verbose);

                    return r.Content.LoadIntoBufferAsync()
                    .Then(() =>
                    {
                        TraceWriter.WriteLine("SerializeAsync - after load", TraceLevel.Verbose);
                        var httpMessageContent2 = new HttpMessageContent(r);
                        // All in-memory and CPU-bound so no need to async
                        return httpMessageContent2.ReadAsByteArrayAsync();
                    })
                    .Then(buffer =>
                    {
                        TraceWriter.WriteLine("SerializeAsync - after ReadAsByteArrayAsync",
                                              TraceLevel.Verbose);
                        return Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite,
                                                      buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent);
                    }
                          );

                    ;
                }
                TraceWriter.WriteLine("Content NULL - before load",
                                      TraceLevel.Verbose);

                var httpMessageContent = new HttpMessageContent(r);
                // All in-memory and CPU-bound so no need to async
                var buffer2 = httpMessageContent.ReadAsByteArrayAsync().Result;
                return Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite,
                                              buffer2, 0, buffer2.Length, null, TaskCreationOptions.AttachedToParent);
            }
                                 ));
        }
예제 #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>
        /// <param name="context"></param>
        /// <param name="connection"></param>
        /// <returns></returns>
        public async Task ProcessResponse(MsgHandlerEventArgs args, HttpContext context, IConnection connection)
        {
            if (args.Message.Reply != null)
            {
                _log.LogTrace($"Create response to reply {args.Message.Reply}");

                if (context.Response.Body.CanSeek)
                {
                    context.Response.Body.Position = 0;
                }

                var response = new HttpResponseMessage
                {
                    StatusCode = (HttpStatusCode)context.Response.StatusCode,
                    Content    = new StreamContent(context.Response.Body),
                };

                response.Content.Headers.ContentType   = MediaTypeHeaderValue.Parse(context.Response.ContentType);
                response.Content.Headers.ContentLength = context.Response.Body.Length;

                foreach (var header in context.Response.Headers)
                {
                    response.Headers.TryAddWithoutValidation(header.Key, header.Value.AsEnumerable());
                }

                var content = new HttpMessageContent(response);
                var bytes   = await content.ReadAsByteArrayAsync();

                _log.LogTrace($"Send response to reply {args.Message.Reply}");
                connection.Publish(args.Message.Reply, bytes);
                _log.LogTrace($"Response to reply {args.Message.Reply} sended");
            }
            else
            {
                _log.LogTrace($"reply is empty, response not be sended. request url {context.Request.GetDisplayUrl()}");
            }
        }
예제 #11
0
        public async Task SerializeAsync(HttpResponseMessage response, Stream stream)
        {
            if (response.Content != null)
            {
                TraceWriter.WriteLine("SerializeAsync - before load",
                                      TraceLevel.Verbose);
                if (_bufferContent)
                {
                    await response.Content.LoadIntoBufferAsync();
                }
                TraceWriter.WriteLine("SerializeAsync - after load", TraceLevel.Verbose);
            }
            else
            {
                TraceWriter.WriteLine("Content NULL - before load",
                                      TraceLevel.Verbose);
            }

            var httpMessageContent = new HttpMessageContent(response);
            var buffer             = await httpMessageContent.ReadAsByteArrayAsync();

            TraceWriter.WriteLine("SerializeAsync - after ReadAsByteArrayAsync", TraceLevel.Verbose);
            stream.Write(buffer, 0, buffer.Length);
        }