Example #1
0
        public async Task ParseSingleApodAsync_CorrectContent()
        {
            var httpResponseParser = new HttpResponseParser();
            var input = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(_singleApodExampleContent, Encoding.UTF8, "application/json")
            };

            var expected = new ApodContent()
            {
                Copyright      = "R Jay Gabany",
                Date           = new DateTime(2019, 11, 16),
                Explanation    = "Grand tidal streams of stars seem to surround galaxy NGC 5907. The arcing structures form tenuous loops extending more than 150,000 light-years from the narrow, edge-on spiral, also known as the Splinter or Knife Edge Galaxy.Recorded only in very deep exposures, the streams likely represent the ghostly trail of a dwarf galaxy - debris left along the orbit of a smaller satellite galaxy that was gradually torn apart and merged with NGC 5907 over four billion years ago.Ultimately this remarkable discovery image, from a small robotic observatory in New Mexico, supports the cosmological scenario in which large spiral galaxies, including our own Milky Way, were formed by the accretion of smaller ones. NGC 5907 lies about 40 million light-years distant in the northern constellation Draco.",
                ContentUrlHD   = "https://apod.nasa.gov/apod/image/1911/ngc5907_gabany_rcl.jpg",
                MediaType      = MediaType.Image,
                ServiceVersion = "v1",
                Title          = "The Star Streams of NGC 5907",
                ContentUrl     = "https://apod.nasa.gov/apod/image/1911/ngc5907_gabany_rcl1024.jpg"
            };

            var actual = (await httpResponseParser.ParseSingleApodAsync(input)).Content;

            Assert.Equal(expected, actual);
        }
 public GeekRefundQuery(GeekEndPoint geekEndPoint, GeekUriComponents uriComponents, HttpResponseParser <RefundInfo> responseParser, string appId)
 {
     this.responseParser = responseParser;
     this.geekEndPoint   = geekEndPoint;
     this.uriComponents  = uriComponents;
     this.appId          = appId;
 }
 public GeekOrderQuery(GeekUriComponents uriComponents, GeekEndPoint geekEndPoint, HttpResponseParser <OrderInfo> responseParser, string appId)
 {
     this.appId          = appId;
     this.uriComponents  = uriComponents;
     this.geekEndPoint   = geekEndPoint;
     this.responseParser = responseParser;
 }
Example #4
0
        /// <summary>
        /// 设置握手结果
        /// </summary>
        /// <param name="streamReader">数据读取器</param>
        /// <returns></returns>
        public bool TrySetResult(ISessionStreamReader streamReader)
        {
            var result = HttpResponseParser.Parse(streamReader);

            if (result.IsHttp == false)
            {
                return(false);
            }
            else
            {
                streamReader.Clear();
            }

            if (result.Status == 101)
            {
                const string guid      = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
                var          bytes     = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(this.secKey + guid));
                var          secValue  = Convert.ToBase64String(bytes);
                var          secAccept = result.Header["Sec-WebSocket-Accept"];
                if (secValue == secAccept)
                {
                    return(this.TrySetResult(SocketError.Success));
                }
            }

            return(this.TrySetResult(SocketError.SocketError));
        }
Example #5
0
 public GeekRetailQROrder(GeekEndPoint geekEndPoint, GeekUriComponents uriComponent, HttpResponseParser <ToPayOrderInfo> responseParser, string notifyUrl, string appId)
 {
     this.uriComponent   = uriComponent;
     this.geekEndPoint   = geekEndPoint;
     this.responseParser = responseParser;
     this.notifyUrl      = notifyUrl;
     this.appId          = appId;
 }
 public GeekNativeQROrder(GeekEndPoint geekEndPoint, GeekUriComponents uriComponents, HttpResponseParser <ToPayNativeOrderInfo> responseParser, string returnUrl, string notifyUrl, string appId)
 {
     this.geekEndPoint   = geekEndPoint;
     this.responseParser = responseParser;
     this.uriComponents  = uriComponents;
     this.appId          = appId;
     this.returnUrl      = returnUrl;
     this.notifyUrl      = notifyUrl;
 }
        public async Task ParseHeadRequestTest()
        {
            // Arrange
            var responseText = await ResourceHelper.GetResponse("SampleHeadResponse");

            // Act
            var result = new HttpResponseParser(responseText);

            // Assert
            Assert.AreEqual(HttpStatusCode.Ok, result.StatusCode);
        }
Example #8
0
        public GeekRefundQueryTest()
        {
            GeekSign geekSign = new GeekSign(AppProperties.GeekPublicKey, AppProperties.PrivateKey);

            HttpClient httpClient = new HttpClient();

            geekEndPoint = new GeekEndPoint(httpClient, geekSign);

            uriComponents = new GeekUriComponents(GeekPaymentProperties.Scheme, GeekPaymentProperties.Host, geekSign);

            responseParser = new RefundInfoResponseParser();
        }
Example #9
0
        public async Task ParseMultipleApodsAsync_HttpResponseIsDisposed()
        {
            var httpResponseParser = new HttpResponseParser();
            var input = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(_multipleApodExampleContent, Encoding.UTF8, "application/json")
            };

            await httpResponseParser.ParseMultipleApodsAsync(input);

            await Assert.ThrowsAsync <ObjectDisposedException>(async() => await input.Content.ReadAsStringAsync());
        }
Example #10
0
        public async Task ParseSingleApodAsync_HasOneApod()
        {
            var httpResponseParser = new HttpResponseParser();
            var input = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(_singleApodExampleContent, Encoding.UTF8, "application/json")
            };

            var result = await httpResponseParser.ParseSingleApodAsync(input);

            Assert.Single(result.AllContent);
        }
Example #11
0
        private void AssertBadTcpMeesage(string message)
        {
            // Arrange
            var logger = Substitute.For <ICoreLogger>();

            // Act
            var ex = AssertException.Throws <MsalClientException>(
                () => HttpResponseParser.ExtractUriFromHttpRequest(message, logger));

            // Assert
            Assert.AreEqual(MsalError.InvalidAuthorizationUri, ex.ErrorCode);
            logger.Received(1).ErrorPii(Arg.Any <string>(), Arg.Any <string>());
        }
Example #12
0
        public static HttpResponse Create(string responseText)
        {
            var result = new HttpResponseParser(responseText);

            return(new HttpResponse(responseText)
            {
                ProtocolVersion = result.ProtocolVersion,
                Status = result.Status,
                StatusCode = result.StatusCode,
                Headers = result.Headers,
                Cookies = result.Cookies,
            });
        }
Example #13
0
        public async Task ParseSingleApodAsync_CorrectStatusCode()
        {
            var httpResponseParser = new HttpResponseParser();
            var input = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(_singleApodExampleContent, Encoding.UTF8, "application/json")
            };

            var expected = ApodStatusCode.OK;
            var actual   = (await httpResponseParser.ParseSingleApodAsync(input)).StatusCode;

            Assert.Equal(expected, actual);
        }
Example #14
0
        public async Task ParseMultipleApodsAsync_CorrectAmountOfApods()
        {
            var httpResponseParser = new HttpResponseParser();
            var input = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(_multipleApodExampleContent, Encoding.UTF8, "application/json")
            };

            var result = await httpResponseParser.ParseMultipleApodsAsync(input);

            var expectedLength = 2; // _multipleApodExampleContent contains 2 apods.
            var actualLength   = result.AllContent.Length;

            Assert.Equal(expectedLength, actualLength);
        }
Example #15
0
        /// <summary>
        /// Full constructor.
        /// </summary>
        /// <param name="socketFactory">An implementation of the <see cref="ISocketFactory"/> interface that can be used to make new unicast and multicast sockets. Cannot be null.</param>
        /// <param name="localPort">The specific local port to use for all sockets created by this instance. Specify zero to indicate the system should choose a free port itself.</param>
        /// <param name="multicastTimeToLive">The multicast time to live value for multicast sockets. Technically this is a number of router hops, not a 'Time'. Must be greater than zero.</param>
        /// <exception cref="System.ArgumentNullException">The <paramref name="socketFactory"/> argument is null.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="multicastTimeToLive"/> argument is less than or equal to zero.</exception>
        public CommunicationsServer(ISocketFactory socketFactory, int localPort, int multicastTimeToLive)
        {
            if (socketFactory == null)
            {
                throw new ArgumentNullException("socketFactory");
            }
            if (multicastTimeToLive <= 0)
            {
                throw new ArgumentOutOfRangeException("multicastTimeToLive", "multicastTimeToLive must be greater than zero.");
            }

            _BroadcastListenSocketSynchroniser = new object();
            _SendSocketSynchroniser            = new object();

            _LocalPort     = localPort;
            _SocketFactory = socketFactory;

            _RequestParser  = new HttpRequestParser();
            _ResponseParser = new HttpResponseParser();

            _MulticastTtl = multicastTimeToLive;
        }
Example #16
0
        public async Task ParseMultipleApodsAsync_CorrectContent()
        {
            var httpResponseParser = new HttpResponseParser();
            var input = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(_multipleApodExampleContent, Encoding.UTF8, "application/json")
            };

            var expected = new ApodContent[]
            {
                new ApodContent()
                {
                    Date           = new DateTime(2006, 11, 07),
                    Explanation    = "Janus is one of the stranger moons of Saturn.First, Janus travels in an unusual orbit around Saturn where it periodically trades places with its sister moon Epimetheus, which typically orbits about 50 kilometers away.Janus, although slightly larger than Epimetheus, is potato-shaped and has a largest diameter of about 190 kilometers.Next, Janus is covered with large craters but strangely appears to lack small craters.One possible reason for this is a fine dust that might cover the small moon, a surface also hypothesized for Pandora and Telesto.Pictured above, Janus was captured in front of the cloud tops of Saturn in late September.",
                    ContentUrlHD   = "https://apod.nasa.gov/apod/image/0611/janus_cassini_big.jpg",
                    MediaType      = MediaType.Image,
                    ServiceVersion = "v1",
                    Title          = "Janus: Potato Shaped Moon of Saturn",
                    ContentUrl     = "https://apod.nasa.gov/apod/image/0611/janus_cassini.jpg"
                },
                new ApodContent()
                {
                    Copyright      = "Misti\nMountain Observatory",
                    Date           = new DateTime(2005, 07, 28),
                    Explanation    = "Ghostly in appearance, Abell 39 is a remarkably simple, spherical nebula about five light-years across. Well within our own Milky Way galaxy, the cosmic sphere is roughly 7,000 light-years distant toward the constellation Hercules. Abell 39 is a planetary nebula, formed as a once sun-like star's outer atmosphere was expelled over a period of thousands of years. Still visible, the nebula's central star is evolving into a hot white dwarf. Although faint, the nebula's simple geometry has proven to be a boon to astronomers exploring the chemical abundances and life cycles of stars. In this deep image recorded under dark night skies, very distant background galaxies can be found -- some visible right through the nebula itself.",
                    ContentUrlHD   = "https://apod.nasa.gov/apod/image/0507/abell39_misti_f.jpg",
                    MediaType      = MediaType.Image,
                    ServiceVersion = "v1",
                    Title          = "Spherical Planetary Nebula Abell 39",
                    ContentUrl     = "https://apod.nasa.gov/apod/image/0507/abell39_misti_c50.jpg"
                }
            };

            var actual = (await httpResponseParser.ParseMultipleApodsAsync(input)).AllContent;

            Assert.Equal(expected, actual);
            Assert.Equal(expected[1], actual[1]);
        }
Example #17
0
        public void CanParseValidHttpGet()
        {
            // Arrange
            const string ValidTcpMessage = @"
                {GET /?code=_some-code_ HTTP/1.1
                 Host: localhost:9001
                 Accept-Language: en-GB,en;q=0.9,en-US;q=0.8,ro;q=0.7,fr;q=0.6
                 Connection: keep-alive
                 Upgrade-Insecure-Requests: 1
                 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36
                 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
                 Accept-Encoding: gzip, deflate, br
                 ... won't parse this far";

            var logger = Substitute.For <ICoreLogger>();

            // Act
            Uri actualUri = HttpResponseParser.ExtractUriFromHttpRequest(ValidTcpMessage, logger);

            // Assert
            logger.DidNotReceiveWithAnyArgs();
            Assert.AreEqual("http://localhost:9001/?code=_some-code_", actualUri.AbsoluteUri);
        }
Example #18
0
        public override void StartReceive()
        {
            if (IsClosed)
            {
                return;
            }
            Socket           readSocket = null;
            HttpObjectParser parser     = null;

            if (isClient)
            {
                readSocket = this.PipesChain.ChainState.ClientSocket;
                parser     = new HttpRequestParser();
            }
            else
            {
                readSocket = this.PipesChain.ChainState.ServerSocket;
                parser     = new HttpResponseParser();
            }

            HttpReaderState httpReaderState = new HttpReaderState(this, readSocket, parser);

            BeginReceive(httpReaderState);
        }
Example #19
0
        public async Task <MiddlemanResponse> ParseAsync(Stream stream)
        {
            var del    = new ParseDelegate();
            var parser = new HttpResponseParser(del);

            int read;
            var buffer = new byte[8192];

            var responseString = "";

            while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
            {
                var newBytes = buffer.Where(x => x != 0).ToArray();
                responseString += Encoding.ASCII.GetString(newBytes, 0, Math.Min(newBytes.Length, read));

                parser.Execute(buffer, 0, read);

                if (del.HeaderComplete)
                {
                    break;
                }
            }

            if (responseString.ToLowerInvariant().Contains("content-type: image/"))
            {
                responseString = responseString.Substring(0, responseString.IndexOf(Environment.NewLine + Environment.NewLine)).Trim();
            }
            Log.Info("RESPONSE FROM SERVER: " + Environment.NewLine + responseString.Trim() + Environment.NewLine);

            if (!del.HeaderComplete)
            {
                throw new FormatException("Parse error in response");
            }

            var response = del.Response;
            var cl       = response.ContentLength;

            if (cl > 0)
            {
                if (del.ResponseBodyStart.Count > 0)
                {
                    response.ResponseBody = new MaxReadStream(new StartAvailableStream(del.ResponseBodyStart, stream),
                                                              cl);
                }
                else
                {
                    response.ResponseBody = new MaxReadStream(stream, cl);
                }
            }
            //else if ((int)response.StatusCode == 100)
            //{
            //    throw new Exception();
            //}
            else if (response.Headers["Transfer-Encoding"] == "chunked")
            {
                if (response.Headers["Connection"] == "close")
                {
                    response.ResponseBody = del.ResponseBodyStart.Count > 0
                        ? new StartAvailableStream(del.ResponseBodyStart, stream)
                        : stream;
                }
                else
                {
                    response.ResponseBody = del.ResponseBodyStart.Count > 0
                        ? new ChunkedStream(new StartAvailableStream(del.ResponseBodyStart, stream))
                        : new ChunkedStream(stream);
                }
            }

            return(response);
        }
Example #20
0
 public void HttpResponseParser_ThrowsOnInvalidHeader()
 {
     var parser = new HttpResponseParser();
     parser.Parse("HTTP1.1 200 OK" + Environment.NewLine);
 }
Example #21
0
 public void HttpResponseParser_ThrowsOnNull()
 {
     var parser = new HttpResponseParser();
     parser.Parse(null);
 }
Example #22
0
 public void HttpResponseParser_ThrowsOnEmpty()
 {
     var parser = new HttpResponseParser();
     parser.Parse(String.Empty);
 }
Example #23
0
        public void HttpResponseParser_ThrowsOnInvalidHeader()
        {
            var parser = new HttpResponseParser();

            parser.Parse("HTTP1.1 200 OK" + Environment.NewLine);
        }
Example #24
0
        public void HttpResponseParser_ThrowsOnEmpty()
        {
            var parser = new HttpResponseParser();

            parser.Parse(String.Empty);
        }
Example #25
0
        public void HttpResponseParser_ThrowsOnNull()
        {
            var parser = new HttpResponseParser();

            parser.Parse(null);
        }
Example #26
0
        /// <summary>
        /// Full constructor.
        /// </summary>
        /// <param name="socketFactory">An implementation of the <see cref="ISocketFactory"/> interface that can be used to make new unicast and multicast sockets. Cannot be null.</param>
        /// <param name="localPort">The specific local port to use for all sockets created by this instance. Specify zero to indicate the system should choose a free port itself.</param>
        /// <param name="multicastTimeToLive">The multicast time to live value for multicast sockets. Technically this is a number of router hops, not a 'Time'. Must be greater than zero.</param>
        /// <exception cref="System.ArgumentNullException">The <paramref name="socketFactory"/> argument is null.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="multicastTimeToLive"/> argument is less than or equal to zero.</exception>
        public SsdpCommunicationsServer(ISocketFactory socketFactory, int localPort, int multicastTimeToLive)
        {
            if (socketFactory == null) throw new ArgumentNullException("socketFactory");
            if (multicastTimeToLive <= 0) throw new ArgumentOutOfRangeException("multicastTimeToLive", "multicastTimeToLive must be greater than zero.");

            _BroadcastListenSocketSynchroniser = new object();
            _SendSocketSynchroniser = new object();

            _LocalPort = localPort;
            _SocketFactory = socketFactory;

            _RequestParser = new HttpRequestParser();
            _ResponseParser = new HttpResponseParser();

            _MulticastTtl = multicastTimeToLive;
        }
Example #27
0
        private IEnumerable<System.Net.Http.HttpResponseMessage> GetSentMessages(Queue<ReceivedUdpData> queue)
        {
            var parser = new HttpResponseParser();

            var retVal = new List<System.Net.Http.HttpResponseMessage>();
            while (queue.Any())
            {
                var receivedResponse = queue.Dequeue();
                retVal.Add(parser.Parse(System.Text.UTF8Encoding.ASCII.GetString(receivedResponse.Buffer)));
            }
            return retVal;
        }
Example #28
0
        public async Task <SwitchboardResponse> ParseAsync(Stream stream)
        {
            var del    = new ParseDelegate();
            var parser = new HttpResponseParser(del);

            int read;

            byte[] buffer = new byte[8192];

            while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
            {
                parser.Execute(buffer, 0, read);

                if (del.headerComplete)
                {
                    break;
                }
            }

            if (!del.headerComplete)
            {
                throw new FormatException("Parse error in response");
            }

            var response = del.response;
            int cl       = response.ContentLength;

            if (cl > 0)
            {
                if (del.responseBodyStart.Count > 0)
                {
                    response.ResponseBody = new MaxReadStream(new StartAvailableStream(del.responseBodyStart, stream), cl);
                }
                else
                {
                    response.ResponseBody = new MaxReadStream(stream, cl);
                }
            }
            else if (response.Headers["Transfer-Encoding"] == "chunked")
            {
                if (response.Headers["Connection"] == "close")
                {
                    if (del.responseBodyStart.Count > 0)
                    {
                        response.ResponseBody = new StartAvailableStream(del.responseBodyStart, stream);
                    }
                    else
                    {
                        response.ResponseBody = stream;
                    }
                }
                else
                {
                    if (del.responseBodyStart.Count > 0)
                    {
                        response.ResponseBody = new ChunkedStream(new StartAvailableStream(del.responseBodyStart, stream));
                    }
                    else
                    {
                        response.ResponseBody = new ChunkedStream(stream);
                    }
                }
            }

            return(response);
        }