public void TestInvokeReadWhenNotProduceMessage()
        {
            var             readCalled = new AtomicInteger();
            EmbeddedChannel channel    = new EmbeddedChannel(new TestHandler(readCalled), new HttpContentDecompressor(), new DecompressorHandler());

            channel.Configuration.IsAutoRead = false;

            readCalled.Value = 0;
            IHttpResponse response = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);

            response.Headers.Set(HttpHeaderNames.ContentEncoding, "gzip");
            response.Headers.Set(HttpHeaderNames.ContentType, "application/json;charset=UTF-8");
            response.Headers.Set(HttpHeaderNames.TransferEncoding, HttpHeaderValues.Chunked);

            Assert.True(channel.WriteInbound(response));

            // we triggered read explicitly
            Assert.Equal(1, readCalled.Value);

            Assert.True(channel.ReadInbound() is IHttpResponse);

            Assert.False(channel.WriteInbound(new DefaultHttpContent(Unpooled.Empty)));

            // read was triggered by the HttpContentDecompressor itself as it did not produce any message to the next
            // inbound handler.
            Assert.Equal(2, readCalled.Value);
            Assert.False(channel.FinishAndReleaseAll());
        }
        public void EmptyBufferBypass()
        {
            var channel = new EmbeddedChannel(new HttpResponseEncoder());

            // Test writing an empty buffer works when the encoder is at ST_INIT.
            channel.WriteOutbound(Unpooled.Empty);
            var buffer = channel.ReadOutbound <IByteBuffer>();

            Assert.Same(buffer, Unpooled.Empty);

            // Leave the ST_INIT state.
            IHttpResponse response = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);

            Assert.True(channel.WriteOutbound(response));
            buffer = channel.ReadOutbound <IByteBuffer>();
            Assert.Equal("HTTP/1.1 200 OK\r\n\r\n", buffer.ToString(Encoding.ASCII));
            buffer.Release();

            // Test writing an empty buffer works when the encoder is not at ST_INIT.
            channel.WriteOutbound(Unpooled.Empty);
            buffer = channel.ReadOutbound <IByteBuffer>();
            Assert.Same(buffer, Unpooled.Empty);

            Assert.False(channel.Finish());
        }
Exemple #3
0
        public void GetContentLengthLongDefaultValueThrowsNumberFormatException()
        {
            var message = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);

            message.Headers.Set(HttpHeaderNames.ContentLength, "bar");
            Assert.Throws <FormatException>(() => HttpUtil.GetContentLength(message, 1L));
        }
        protected internal override bool handleResponse(IChannelHandlerContext ctx, object response)
        {
            if ((response is IFullHttpResponse) || (response is DefaultHttpResponse))
            {
                DefaultHttpResponse def = (DefaultHttpResponse)response;
                if (def != null)
                {
                    status = def.Status;

                    inboundHeaders = def.Headers;
                }
            }

            bool finished = response is ILastHttpContent;

            if (finished)
            {
                if (status == null)
                {
                    throw new HttpProxyConnectException(exceptionMessage("missing response"), inboundHeaders);
                }
                if (status.Code != 200)
                {
                    throw new HttpProxyConnectException(exceptionMessage("status: " + status), inboundHeaders);
                }
            }

            return(finished);
        }
Exemple #5
0
        public void BuildResponseFromResponseTest()
        {
            //BuildResponseFromResponse(HttpResponse overrideResponse, HttpContext context)
            var httpContext = new DefaultHttpContext();

            httpContext.Response.Body = new MemoryStream();
            var response = new DefaultHttpResponse(new DefaultHttpContext())
            {
                Body = new MemoryStream()
            };
            var responseBytes =
                System.Text.Encoding.UTF8.GetBytes(
                    JsonConvert.SerializeObject(new TestingType {
                Yo = "lo", No = "low"
            }));

            response.Body.WriteAsync(responseBytes, 0, responseBytes.Length);
            response.Headers.Add(new KeyValuePair <string, StringValues>("yolo", new StringValues("solo")));
            response.StatusCode = StatusCodes.Status502BadGateway;
            var methodInfo = typeof(ResponseUtils)
                             .GetMethod("BuildResponseFromResponse", BindingFlags.Static | BindingFlags.NonPublic);

            methodInfo.Invoke(this, new object[] { response, httpContext });
            httpContext.Response.Body.Position = 0;
            var responseString       = new StreamReader(httpContext.Response.Body).ReadToEnd();
            var responseDeserialized = JsonConvert.DeserializeObject <TestingType>(responseString);

            Assert.Equal(502, httpContext.Response.StatusCode);
            Assert.Equal("lo", responseDeserialized.Yo);
            Assert.Equal("low", responseDeserialized.No);
            Assert.Equal(1, httpContext.Response.Headers.Count);
            Assert.Equal("solo", httpContext.Response.Headers.First().Value);
        }
Exemple #6
0
        public void ChunkedHeadResponse()
        {
            var ch = new EmbeddedChannel(new HttpServerCodec());

            // Send the request headers.
            Assert.True(ch.WriteInbound(Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes(
                                                                  "HEAD / HTTP/1.1\r\n\r\n"))));

            var request = ch.ReadInbound <IHttpRequest>();

            Assert.Equal(HttpMethod.Head, request.Method);
            var content = ch.ReadInbound <ILastHttpContent>();

            Assert.False(content.Content.IsReadable());
            content.Release();

            var response = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);

            HttpUtil.SetTransferEncodingChunked(response, true);
            Assert.True(ch.WriteOutbound(response));
            Assert.True(ch.WriteOutbound(EmptyLastHttpContent.Default));
            Assert.True(ch.Finish());

            var buf = ch.ReadOutbound <IByteBuffer>();

            Assert.Equal("HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n", buf.ToString(Encoding.ASCII));
            buf.Release();

            buf = ch.ReadOutbound <IByteBuffer>();
            Assert.False(buf.IsReadable());
            buf.Release();

            Assert.False(ch.FinishAndReleaseAll());
        }
Exemple #7
0
 internal HdfsWriter(DFSClient client, OutputStream @out, DefaultHttpResponse response
                     )
 {
     this.client   = client;
     this.@out     = @out;
     this.response = response;
 }
Exemple #8
0
        public async Task ThenTheFileContentIsSetCorrectly(
            DownloadRequest request,
            string expectedFileName,
            [Frozen] Mock <HttpContext> httpContext,
            [Frozen] Mock <IModelMapper> csvMapper,
            ApprenticeController controller)
        {
            //Arrange
            var expectedCsvContent = new DownloadViewModel
            {
                Name    = expectedFileName,
                Content = new MemoryStream()
            };

            csvMapper.Setup(x =>
                            x.Map <DownloadViewModel>(request))
            .ReturnsAsync(expectedCsvContent);
            var defaultHttpResponse = new DefaultHttpResponse(httpContext.Object);

            httpContext.Setup(x => x.Response).Returns(defaultHttpResponse);
            controller.ControllerContext = new ControllerContext
            {
                HttpContext = httpContext.Object
            };

            //Act
            var actual = await controller.Download(request);

            var actualFileResult = actual as FileResult;

            //Assert
            Assert.IsNotNull(actualFileResult);
            Assert.AreEqual(expectedCsvContent.Name, actualFileResult.FileDownloadName);
            Assert.AreEqual(actualFileResult.ContentType, actualFileResult.ContentType);
        }
Exemple #9
0
        public void SuccessfulUpgrade()
        {
            HttpClientUpgradeHandler.ISourceCodec  sourceCodec  = new FakeSourceCodec();
            HttpClientUpgradeHandler.IUpgradeCodec upgradeCodec = new FakeUpgradeCodec();
            var handler = new HttpClientUpgradeHandler(sourceCodec, upgradeCodec, 1024);
            var catcher = new UserEventCatcher();
            var channel = new EmbeddedChannel(catcher);

            channel.Pipeline.AddFirst("upgrade", handler);

            Assert.True(channel.WriteOutbound(new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Get, "netty.io")));
            var request = channel.ReadOutbound <IFullHttpRequest>();

            Assert.Equal(2, request.Headers.Size);
            Assert.True(request.Headers.Contains(HttpHeaderNames.Upgrade, (AsciiString)"fancyhttp", false));
            Assert.True(request.Headers.Contains((AsciiString)"connection", (AsciiString)"upgrade", false));
            Assert.True(request.Release());
            Assert.Equal(HttpClientUpgradeHandler.UpgradeEvent.UpgradeIssued, catcher.UserEvent);

            var upgradeResponse = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus.SwitchingProtocols);

            upgradeResponse.Headers.Add(HttpHeaderNames.Upgrade, (AsciiString)"fancyhttp");
            Assert.False(channel.WriteInbound(upgradeResponse));
            Assert.False(channel.WriteInbound(EmptyLastHttpContent.Default));

            Assert.Equal(HttpClientUpgradeHandler.UpgradeEvent.UpgradeSuccessful, catcher.UserEvent);
            Assert.Null(channel.Pipeline.Get("upgrade"));

            Assert.True(channel.WriteInbound(new DefaultFullHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK)));
            var response = channel.ReadInbound <IFullHttpResponse>();

            Assert.Equal(HttpResponseStatus.OK, response.Status);
            Assert.True(response.Release());
            Assert.False(channel.Finish());
        }
        public void AddPaginationHeadersShouldAddPaginationHeadersToResponse()
        {
            //Initialize
            var context = new DefaultHttpContext();
            var unused  = new DefaultHttpRequest(context)
            {
                Scheme      = "http",
                Host        = new HostString("localhost", 5000),
                Path        = new PathString("/v1/employees"),
                QueryString = new QueryString($"?{PageKey}=2&{PerPageKey}=3&active=true")
            };

            //Setup
            var response       = new DefaultHttpResponse(context);
            var paginationInfo = new PaginationInfo(new PaginationParams {
                Page = 2, PerPage = 3, Count = 10
            });

            //Invoke
            response.AddPaginationHeaders(paginationInfo);

            //Assert
            var expectedLink = $"<http://localhost:5000/v1/employees?active=true&{PageKey}=1&{PerPageKey}=3>; " +
                               $"rel=\"first\",<http://localhost:5000/v1/employees?active=true&{PageKey}=1&{PerPageKey}=3>; " +
                               $"rel=\"prev\",<http://localhost:5000/v1/employees?active=true&{PageKey}=3&{PerPageKey}=3>; " +
                               $"rel=\"next\",<http://localhost:5000/v1/employees?active=true&{PageKey}=4&{PerPageKey}=3>; " +
                               "rel=\"last\"";

            Assert.Equal(expectedLink, response.Headers["Link"]);
            Assert.Equal("2", response.Headers["X-Page"]);
            Assert.Equal("3", response.Headers["X-Per-Page"]);
            Assert.Equal("10", response.Headers["X-Total-Count"]);
            Assert.Equal("4", response.Headers["X-Total-Pages"]);
        }
Exemple #11
0
        public void GetCharsetDefaultValue()
        {
            const string SimpleContentType = "text/html";
            const string ContentTypeWithIncorrectCharset   = "text/html; charset=UTFFF";
            const string ContentTypeWithIllegalCharsetName = "text/html; charset=!illegal!";

            var message = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);

            message.Headers.Set(HttpHeaderNames.ContentType, SimpleContentType);
            Assert.Equal(Encoding.UTF8, HttpUtil.GetCharset(message));
            Assert.Equal(Encoding.UTF8, HttpUtil.GetCharset(new AsciiString(SimpleContentType)));

            message.Headers.Set(HttpHeaderNames.ContentType, SimpleContentType);
            Assert.Equal(Encoding.UTF8, HttpUtil.GetCharset(message, Encoding.UTF8));
            Assert.Equal(Encoding.UTF8, HttpUtil.GetCharset(new AsciiString(SimpleContentType), Encoding.UTF8));

            message.Headers.Set(HttpHeaderNames.ContentType, ContentTypeWithIncorrectCharset);
            Assert.Equal(Encoding.UTF8, HttpUtil.GetCharset(message));
            Assert.Equal(Encoding.UTF8, HttpUtil.GetCharset(new AsciiString(ContentTypeWithIncorrectCharset)));

            message.Headers.Set(HttpHeaderNames.ContentType, ContentTypeWithIncorrectCharset);
            Assert.Equal(Encoding.UTF8, HttpUtil.GetCharset(message, Encoding.UTF8));
            Assert.Equal(Encoding.UTF8, HttpUtil.GetCharset(new AsciiString(ContentTypeWithIncorrectCharset), Encoding.UTF8));

            message.Headers.Set(HttpHeaderNames.ContentType, ContentTypeWithIllegalCharsetName);
            Assert.Equal(Encoding.UTF8, HttpUtil.GetCharset(message));
            Assert.Equal(Encoding.UTF8, HttpUtil.GetCharset(new AsciiString(ContentTypeWithIllegalCharsetName)));

            message.Headers.Set(HttpHeaderNames.ContentType, ContentTypeWithIllegalCharsetName);
            Assert.Equal(Encoding.UTF8, HttpUtil.GetCharset(message, Encoding.UTF8));
            Assert.Equal(Encoding.UTF8, HttpUtil.GetCharset(new AsciiString(ContentTypeWithIllegalCharsetName), Encoding.UTF8));
        }
        public void Http10()
        {
            var ch  = new EmbeddedChannel(new TestEncoder());
            var req = new DefaultFullHttpRequest(HttpVersion.Http10, HttpMethod.Get, "/");

            Assert.True(ch.WriteInbound(req));

            var res = new DefaultHttpResponse(HttpVersion.Http10, HttpResponseStatus.OK);

            res.Headers.Set(HttpHeaderNames.ContentLength, HttpHeaderValues.Zero);
            Assert.True(ch.WriteOutbound(res));
            Assert.True(ch.WriteOutbound(EmptyLastHttpContent.Default));
            Assert.True(ch.Finish());

            var request = ch.ReadInbound <IFullHttpRequest>();

            Assert.True(request.Release());
            var next = ch.ReadInbound <object>();

            Assert.Null(next);

            var response = ch.ReadOutbound <IHttpResponse>();

            Assert.Same(res, response);

            var content = ch.ReadOutbound <ILastHttpContent>();

            Assert.Same(content, EmptyLastHttpContent.Default);
            content.Release();

            next = ch.ReadOutbound <object>();
            Assert.Null(next);
        }
Exemple #13
0
 internal static Dictionary <string, string> FromDefaultHttpResponse(DefaultHttpResponse response)
 {
     GaxPreconditions.CheckNotNull(response, nameof(response));
     return(new Dictionary <string, string>
     {
         { LabelsCommon.HttpStatusCode, response.StatusCode.ToString() }
     });
 }
Exemple #14
0
        public override void ExceptionCaught(ChannelHandlerContext ctx, Exception cause)
        {
            ReleaseDfsResources();
            DefaultHttpResponse resp = ExceptionHandler.ExceptionCaught(cause);

            resp.Headers().Set(HttpHeaders.Names.Connection, HttpHeaders.Values.Close);
            ctx.WriteAndFlush(response).AddListener(ChannelFutureListener.Close);
        }
 public void RemoveTransferEncodingIgnoreCase()
 {
     var message = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);
     message.Headers.Set(HttpHeaderNames.TransferEncoding, "Chunked");
     Assert.False(message.Headers.IsEmpty);
     HttpUtil.SetTransferEncodingChunked(message, false);
     Assert.True(message.Headers.IsEmpty);
 }
            /// <exception cref="System.IO.IOException"/>
            public virtual void Handle(Org.Jboss.Netty.Channel.Channel channel, Org.Apache.Hadoop.Security.Token.Token
                                       <DelegationTokenIdentifier> token, string serviceUrl)
            {
                NUnit.Framework.Assert.AreEqual(this._enclosing.testToken, token);
                HttpResponse response = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus
                                                                .Ok);

                channel.Write(response).AddListener(ChannelFutureListener.Close);
            }
Exemple #17
0
        public void CreateResponseTest_BadRequestResponseOverride()
        {
            var validationResult = new ValidationResult()
            {
                InvalidClaims = new List <InvalidClaimResult>()
                {
                    new InvalidClaimResult()
                    {
                        ActualValue   = "NO",
                        ClaimName     = "PityTheFool",
                        ExpectedValue = "Always"
                    }
                },
                MissingClaims = new List <string>()
                {
                    "You_Cross_Me_Im_Going_To_Hurt_You", "Whatever_Role_I_Play_Is_A_Positive_Role"
                }
            };
            var badRequestResponse = new Config.Claims.BadRequestResponse()
            {
                BadRequestResponseOverride = (missingClaims, invalidClaims) =>
                {
                    var response = new DefaultHttpResponse(new DefaultHttpContext())
                    {
                        Body = new MemoryStream()
                    };
                    var responseBytes =
                        System.Text.Encoding.UTF8.GetBytes(
                            JsonConvert.SerializeObject(new TestingType {
                        Yo = "lo", No = "low"
                    }));
                    response.Body.WriteAsync(responseBytes, 0, responseBytes.Length);
                    response.Headers.Add(new KeyValuePair <string, StringValues>("yolo", new StringValues("solo")));
                    response.StatusCode = StatusCodes.Status502BadGateway;
                    return(Task.FromResult((HttpResponse)response));
                },
                Headers = new HeaderDictionary(new Dictionary <string, StringValues>()
                {
                    { "I_Dont_Do_Shakespeare", new StringValues("I_Dont_Talk_In_That_Kind_Of_Broken_English") }
                }),
                HttpStatusCode = System.Net.HttpStatusCode.Conflict,
                Response       = new System.Dynamic.ExpandoObject()
            };
            var httpContext = new DefaultHttpContext();

            httpContext.Response.Body = new MemoryStream();
            ResponseUtils.CreateResponse(validationResult, httpContext, badRequestResponse).Wait();
            httpContext.Response.Body.Position = 0;
            Assert.Equal((int)System.Net.HttpStatusCode.BadGateway, httpContext.Response.StatusCode);
            Assert.Single(httpContext.Response.Headers.Where(x => x.Key == "yolo"));
            Assert.Equal("solo", httpContext.Response.Headers.First(x => x.Key == "yolo").Value);
            var responseDeserialized = JsonConvert.DeserializeObject <TestingType>((new StreamReader(httpContext.Response.Body).ReadToEnd()));

            Assert.Equal("lo", responseDeserialized.Yo);
            Assert.Equal("low", responseDeserialized.No);
        }
Exemple #18
0
        public TestHttpContext()
        {
            _responseStream = new MemoryStream();

            // if this new DefaultHttpContext thing ever causes issues, add an Initialize method
            // to this TestHttpContextClass which properly sets up the response with TestHttpContext.
            Response = new DefaultHttpResponse(new DefaultHttpContext())
            {
                Body = _responseStream
            };
        }
        public static void SendHttpFirstChunkAsync(this JT1078HttpSession session, byte[] data)
        {
            DefaultHttpResponse firstRes = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);

            firstRes.Headers.Set(ServerEntity, ServerName);
            firstRes.Headers.Set(DateEntity, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            firstRes.Headers.Set(HttpHeaderNames.ContentType, (AsciiString)"video/x-flv");
            HttpUtil.SetTransferEncodingChunked(firstRes, true);
            session.Channel.WriteAsync(firstRes);
            session.Channel.WriteAndFlushAsync(Unpooled.CopiedBuffer(data));
        }
Exemple #20
0
        public void FromDefaultHttpResponse()
        {
            var response = new DefaultHttpResponse(new DefaultHttpContext());

            response.StatusCode = 404;

            var labels = Labels.FromDefaultHttpResponse(response);

            Assert.Equal(1, labels.Count);
            Assert.Equal("404", labels[LabelsCommon.HttpStatusCode]);
        }
Exemple #21
0
        /// <exception cref="System.Exception"/>
        protected override void ChannelRead0(ChannelHandlerContext ctx, HttpRequest request
                                             )
        {
            if (request.GetMethod() != HttpMethod.Get)
            {
                DefaultHttpResponse resp = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus
                                                                   .MethodNotAllowed);
                resp.Headers().Set(HttpHeaders.Names.Connection, HttpHeaders.Values.Close);
                ctx.Write(resp).AddListener(ChannelFutureListener.Close);
                return;
            }
            QueryStringDecoder decoder = new QueryStringDecoder(request.GetUri());
            string             op      = GetOp(decoder);
            string             content;
            string             path = GetPath(decoder);

            switch (op)
            {
            case "GETFILESTATUS":
            {
                content = image.GetFileStatus(path);
                break;
            }

            case "LISTSTATUS":
            {
                content = image.ListStatus(path);
                break;
            }

            case "GETACLSTATUS":
            {
                content = image.GetAclStatus(path);
                break;
            }

            default:
            {
                throw new ArgumentException("Invalid value for webhdfs parameter" + " \"op\"");
            }
            }
            Log.Info("op=" + op + " target=" + path);
            DefaultFullHttpResponse resp_1 = new DefaultFullHttpResponse(HttpVersion.Http11,
                                                                         HttpResponseStatus.Ok, Unpooled.WrappedBuffer(Sharpen.Runtime.GetBytesForString(
                                                                                                                           content, Charsets.Utf8)));

            resp_1.Headers().Set(HttpHeaders.Names.ContentType, WebHdfsHandler.ApplicationJsonUtf8
                                 );
            resp_1.Headers().Set(HttpHeaders.Names.ContentLength, resp_1.Content().ReadableBytes
                                     ());
            resp_1.Headers().Set(HttpHeaders.Names.Connection, HttpHeaders.Values.Close);
            ctx.Write(resp_1).AddListener(ChannelFutureListener.Close);
        }
Exemple #22
0
        public void ContentTypeIsReflectedInHeadersAfterAssignment()
        {
            var context  = new DefaultHttpContext();
            var response = new DefaultHttpResponse(context);

            var scriptRequest = new HttpResponseImpl(response);

            scriptRequest.ContentType = "text/plain";
            Assert.True(scriptRequest.Headers.GetIndexedValue(ValueFactory.Create("Content-Type")).AsString().Equals("text/plain"));
            Assert.Equal("text/plain", scriptRequest.RealObject.Headers["Content-Type"]);
            Assert.Equal("text/plain", scriptRequest.RealObject.ContentType);
        }
Exemple #23
0
        private HttpResponse GetSampleResponse()
        {
            var response = new DefaultHttpResponse(new DefaultHttpContext())
            {
                Body = new MemoryStream()
            };
            var responseBytes = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { Yolo = "nolo" }));

            response.Body.WriteAsync(responseBytes, 0, responseBytes.Length);
            response.Headers.Add(new KeyValuePair <string, StringValues>("yolo", new StringValues("solo")));
            response.StatusCode = StatusCodes.Status502BadGateway;
            return(response);
        }
Exemple #24
0
        public void SelectiveResponseAggregation()
        {
            EmbeddedChannel channel = new EmbeddedChannel(new TestTextHttpObjectAggregator(1024 * 1024));

            try
            {
                // Aggregate: text/plain
                IHttpResponse response1 = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);
                IHttpContent  content1  = new DefaultHttpContent(Unpooled.CopiedBuffer("Hello, World!", Encoding.UTF8));
                response1.Headers.Set(HttpHeaderNames.ContentType, HttpHeaderValues.TextPlain);

                Assert.True(channel.WriteInbound(response1, content1, EmptyLastHttpContent.Default));

                // Getting an aggregated response out
                var msg1 = channel.ReadInbound();
                try
                {
                    Assert.True(msg1 is IFullHttpResponse);
                }
                finally
                {
                    ReferenceCountUtil.Release(msg1);
                }

                // Don't aggregate: application/json
                IHttpResponse response2 = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);
                IHttpContent  content2  = new DefaultHttpContent(Unpooled.CopiedBuffer("{key: 'value'}", Encoding.UTF8));
                response2.Headers.Set(HttpHeaderNames.ContentType, HttpHeaderValues.ApplicationJson);

                try
                {
                    Assert.True(channel.WriteInbound(response2, content2, EmptyLastHttpContent.Default));

                    // Getting the same response objects out
                    Assert.Same(response2, channel.ReadInbound <IHttpResponse>());
                    Assert.Same(content2, channel.ReadInbound <IHttpContent>());
                    Assert.Same(EmptyLastHttpContent.Default, channel.ReadInbound <EmptyLastHttpContent>());
                }
                finally
                {
                    ReferenceCountUtil.Release(response2);
                    ReferenceCountUtil.Release(content2);
                }

                Assert.False(channel.Finish());
            }
            finally
            {
                channel.CloseAsync();
            }
        }
Exemple #25
0
        public async Task <HttpResponse> ToResponseAsync(ResponseMessage responseMessage,
                                                         CancellationToken cancellationToken)
        {
            if (responseMessage == null)
            {
                throw new ArgumentNullException(nameof(responseMessage));
            }

            var result = new DefaultHttpResponse(null);

            await CopyResponseMessageToTarget(result, responseMessage, cancellationToken);

            return(result);
        }
Exemple #26
0
			protected internal virtual void SendError(ChannelHandlerContext ctx, string message
				, HttpResponseStatus status)
			{
				HttpResponse response = new DefaultHttpResponse(HttpVersion.Http11, status);
				response.SetHeader(HttpHeaders.Names.ContentType, "text/plain; charset=UTF-8");
				// Put shuffle version into http header
				response.SetHeader(ShuffleHeader.HttpHeaderName, ShuffleHeader.DefaultHttpHeaderName
					);
				response.SetHeader(ShuffleHeader.HttpHeaderVersion, ShuffleHeader.DefaultHttpHeaderVersion
					);
				response.SetContent(ChannelBuffers.CopiedBuffer(message, CharsetUtil.Utf8));
				// Close the connection as soon as the error message is sent.
				ctx.GetChannel().Write(response).AddListener(ChannelFutureListener.Close);
			}
Exemple #27
0
        public void TestUpgradeHeaders()
        {
            EmbeddedChannel ch       = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(true));
            var             response = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);

            Assert.True(ch.WriteOutbound(response));

            var headersFrame = ch.ReadOutbound <IHttp2HeadersFrame>();

            Assert.Equal("200", headersFrame.Headers.Status.ToString());
            Assert.False(headersFrame.IsEndStream);

            Assert.Null(ch.ReadOutbound <object>());
            Assert.False(ch.Finish());
        }
Exemple #28
0
        public void GetCharsetAsRawCharSequence()
        {
            const string QuotesCharsetContentType = "text/html; charset=\"utf8\"";
            const string SimpleContentType        = "text/html";

            var message = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);

            message.Headers.Set(HttpHeaderNames.ContentType, QuotesCharsetContentType);
            Assert.Equal("\"utf8\"", HttpUtil.GetCharsetAsSequence(message).ToString());
            Assert.Equal("\"utf8\"", HttpUtil.GetCharsetAsSequence(new AsciiString(QuotesCharsetContentType)));

            message.Headers.Set(HttpHeaderNames.ContentType, "text/html");
            Assert.Null(HttpUtil.GetCharsetAsSequence(message));
            Assert.Null(HttpUtil.GetCharsetAsSequence(new AsciiString(SimpleContentType)));
        }
Exemple #29
0
        public void GetCharset()
        {
            const string NormalContentType          = "text/html; charset=utf-8";
            const string UpperCaseNormalContentType = "TEXT/HTML; CHARSET=UTF-8";

            var message = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);

            message.Headers.Set(HttpHeaderNames.ContentType, NormalContentType);
            Assert.Equal(Encoding.UTF8, HttpUtil.GetCharset(message));
            Assert.Equal(Encoding.UTF8, HttpUtil.GetCharset(new AsciiString(NormalContentType)));

            message.Headers.Set(HttpHeaderNames.ContentType, UpperCaseNormalContentType);
            Assert.Equal(Encoding.UTF8, HttpUtil.GetCharset(message));
            Assert.Equal(Encoding.UTF8, HttpUtil.GetCharset(new AsciiString(UpperCaseNormalContentType)));
        }
Exemple #30
0
        /// <exception cref="System.IO.IOException"/>
        private void OnAppend(ChannelHandlerContext ctx)
        {
            WriteContinueHeader(ctx);
            string       nnId       = @params.NamenodeId();
            int          bufferSize = @params.BufferSize();
            DFSClient    dfsClient  = NewDfsClient(nnId, conf);
            OutputStream @out       = dfsClient.Append(path, bufferSize, EnumSet.Of(CreateFlag.Append
                                                                                    ), null, null);
            DefaultHttpResponse resp = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus
                                                               .Ok);

            resp.Headers().Set(HttpHeaders.Names.ContentLength, 0);
            ctx.Pipeline().Replace(this, typeof(HdfsWriter).Name, new HdfsWriter(dfsClient, @out
                                                                                 , resp));
        }