Exemple #1
0
        public void HttpConnection_Query_Timeout()
        {
            EnhancedSocket sockListen = null;
            EnhancedSocket sockAccept = null;
            HttpConnection con;
            HttpRequest    request;
            HttpResponse   response;
            string         content;
            TimeSpan       orgTimeout;
            IAsyncResult   ar;

            orgTimeout = HttpStack.TimeoutSweepInterval;
            HttpStack.TimeoutSweepInterval = TimeSpan.FromMilliseconds(250);

            sockListen = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sockListen.Bind(new IPEndPoint(IPAddress.Any, ServerPort));
            sockListen.Listen(10);

            try
            {
                ar = sockListen.BeginAccept(null, null);

                con = new HttpConnection(HttpOption.None);
                con.Connect("http://localhost:" + ServerPort.ToString());

                sockAccept = sockListen.EndAccept(ar);

                content             = "Test: Timeout";
                request             = new HttpRequest("GET", "/foo.htm", null);
                request["Response"] = content;
                request["Close"]    = "no";

                try
                {
                    response = con.Query(request, SysTime.Now + TimeSpan.FromMilliseconds(250));
                    Thread.Sleep(1000);
                    Assert.Fail();
                }
                catch (TimeoutException)
                {
                }

                Assert.IsTrue(con.IsClosed);
                con.Close();
            }
            finally
            {
                HttpStack.TimeoutSweepInterval = orgTimeout;

                if (sockListen != null)
                {
                    sockListen.Close();
                }

                if (sockAccept != null)
                {
                    sockAccept.Close();
                }
            }
        }
Exemple #2
0
        public void timeout()
        {
            IConnection con = HttpConnection.Connect("http://example.com/");

            con.Timeout(1000);
            Assert.AreEqual(1000, con.Request().Timeout());
        }
Exemple #3
0
        /// <summary>
        /// Authenticates against the authentication service via a HTTP/POST.
        /// </summary>
        /// <param name="realm">The authentication realm.</param>
        /// <param name="account">The account.</param>
        /// <param name="password">The password.</param>
        /// <returns>A see cref="AuthenticationResult" /> instance.</returns>
        public AuthenticationResult AuthenticateViaPost(string realm, string account, string password)
        {
            HttpConnection  con         = new HttpConnection(HttpOption.None);
            JsonAuthRequest authRequest = new JsonAuthRequest(realm, account, password);
            HttpRequest     request;
            HttpResponse    response;
            string          content;

            try
            {
                con.Connect(uri.Host, uri.Port);
                request = new HttpRequest(HttpStack.Http11, "post", uri.AbsolutePath,
                                          new BlockArray(Helper.ToUTF8(JsonSerializer.ToString(authRequest))));

                request["host"]         = uri.Host;
                request["accept"]       = "*/*";
                request["content-type"] = "application/json";

                response = con.Query(request, SysTime.Now + TimeSpan.FromSeconds(10));
                if ((int)response.Status < 200 || (int)response.Status > 299)
                {
                    throw new HttpException(response.Status);
                }

                content = Helper.FromUTF8(response.Content.ToByteArray());

                return(((JsonAuthResponse)JsonSerializer.Read(content, typeof(JsonAuthResponse))).ToAuthResult());
            }
            finally
            {
                con.Close();
            }
        }
Exemple #4
0
        public void cookie()
        {
            IConnection con = HttpConnection.Connect("http://example.com/");

            con.Cookie("Name", "Val");
            Assert.AreEqual("Val", con.Request().Cookie("Name"));
        }
Exemple #5
0
        public void referrer()
        {
            IConnection con = HttpConnection.Connect("http://example.com/");

            con.Referrer("http://foo.com");
            Assert.AreEqual("http://foo.com", con.Request().Header("Referer"));
        }
Exemple #6
0
        /// <summary>
        /// Fetch a URL, and parse it as HTML. Provided for compatibility; in most cases use <code>Connect(string)</code> instead.
        /// The encoding character set is determined by the content-type header or http-equiv meta tag, or falls back to <code>UTF-8</code>.
        /// </summary>
        /// <param name="url">URL to fetch (with a GET). The protocol must be <code>http</code> or <code>https</code>.</param>
        /// <param name="timeoutMillis">Connection and read timeout, in milliseconds. If exceeded, IOException is thrown.</param>
        /// <returns>The parsed HTML.</returns>
        /// <seealso cref="Connect(string)"/>
        /// <exception cref="HttpStatusException">If the response is not OK and HTTP response errors are not ignored.</exception>
        /// <exception cref="UnsupportedMimeTypeException">If the response mime type is not supported and those errors are not ignored.</exception>
        /// <exception cref="IOException">If a connection or read error occurs.</exception>
        //@throws java.net.MalformedURLException if the request URL is not a HTTP or HTTPS URL, or is otherwise malformed
        //@throws java.net.SocketTimeoutException if the connection times out
        public static Document Parse(Uri url, int timeoutMillis)
        {
            IConnection con = HttpConnection.Connect(url);

            con.Timeout(timeoutMillis);
            return(con.Get());
        }
Exemple #7
0
        /// <summary>
        /// Authenticates against the authentication service via a HTTP/GET.
        /// </summary>
        /// <param name="realm">The authentication realm.</param>
        /// <param name="account">The account.</param>
        /// <param name="password">The password.</param>
        /// <returns>A see cref="AuthenticationResult" /> instance.</returns>
        public AuthenticationResult AuthenticateViaGet(string realm, string account, string password)
        {
            HttpConnection con = new HttpConnection(HttpOption.None);
            HttpRequest    request;
            HttpResponse   response;
            string         content;

            try
            {
                con.Connect(uri.Host, uri.Port);
                request = new HttpRequest(HttpStack.Http11, "get",
                                          string.Format("{0}?realm={1}&account={2}&password={3}",
                                                        uri.AbsolutePath, Helper.EscapeUri(realm), Helper.EscapeUri(account), Helper.EscapeUri(password)),
                                          null);

                request["host"]   = uri.Host;
                request["accept"] = "*/*";

                response = con.Query(request, SysTime.Now + TimeSpan.FromSeconds(10));
                if ((int)response.Status < 200 || (int)response.Status > 299)
                {
                    throw new HttpException(response.Status);
                }

                content = Helper.FromUTF8(response.Content.ToByteArray());

                return(((JsonAuthResponse)JsonSerializer.Read(content, typeof(JsonAuthResponse))).ToAuthResult());
            }
            finally
            {
                con.Close();
            }
        }
Exemple #8
0
        public void HttpConnection_Query_EndPoint()
        {
            HttpServer     server;
            HttpConnection con;
            HttpRequest    request;
            HttpResponse   response;
            string         content;

            server = new HttpServer(new IPEndPoint[] { new IPEndPoint(IPAddress.Any, ServerPort) }, new IHttpModule[] { new TestModule() }, 5, 100, int.MaxValue);
            server.Start();

            try
            {
                con = new HttpConnection(HttpOption.None);
                con.Connect(new IPEndPoint(IPAddress.Loopback, ServerPort));

                for (int i = 0; i < 10; i++)
                {
                    content             = "Test: " + i.ToString();
                    request             = new HttpRequest("GET", "/foo.htm", null);
                    request["Response"] = content;
                    request["Close"]    = "no";

                    response = con.Query(request, DateTime.MaxValue);
                    CollectionAssert.AreEqual(Encoding.ASCII.GetBytes(content), response.Content.ToByteArray());
                }

                con.Close();
            }
            finally
            {
                server.Stop();
            }
        }
Exemple #9
0
        public void userAgent()
        {
            IConnection con = HttpConnection.Connect("http://example.com/");

            con.UserAgent("Mozilla");
            Assert.AreEqual("Mozilla", con.Request().Header("User-Agent"));
        }
Exemple #10
0
        public void method()
        {
            IConnection con = HttpConnection.Connect("http://example.com/");

            Assert.AreEqual(Method.Get, con.Request().Method());
            con.Method(Method.Post);
            Assert.AreEqual(Method.Post, con.Request().Method());
        }
Exemple #11
0
        public void HttpConnection_Connect_Fail()
        {
            HttpConnection con;

            try
            {
                con = new HttpConnection(HttpOption.None);
                con.Connect("http://foobar_error:" + ServerPort.ToString());
            }
            catch
            {
            }
        }
        public void data()
        {
            var con = HttpConnection.Connect("http://example.com/");

            con.Data("Name", "Val", "Foo", "bar");
            var values = con.Request().Data();
            var data   = values.ToArray();
            var one    = data[0];
            var two    = data[1];

            Assert.AreEqual("Name", one.Key());
            Assert.AreEqual("Val", one.Value());
            Assert.AreEqual("Foo", two.Key());
            Assert.AreEqual("bar", two.Value());
        }
Exemple #13
0
        public void data()
        {
            IConnection con = HttpConnection.Connect("http://example.com/");

            con.Data("Name", "Val", "Foo", "bar");
            ICollection <KeyVal> values = con.Request().Data();

            Object[] data = values.ToArray();
            KeyVal   one  = (KeyVal)data[0];
            KeyVal   two  = (KeyVal)data[1];

            Assert.AreEqual("Name", one.Key());
            Assert.AreEqual("Val", one.Value());
            Assert.AreEqual("Foo", two.Key());
            Assert.AreEqual("bar", two.Value());
        }
Exemple #14
0
        void WaitForConnection()
        {
            while (isStarted)
            {
                try
                {
                    connection = new HttpConnection(true);
                    connection.Connect(listenPort);

                    if (!connection.StopWaiting && connection.Connected && Connected != null)
                    {
                        new Thread(conObj =>
                        {
                            Connected(conObj as IConnection);
                        }).Start(connection);
                    }
                }
                catch (Exception exc)
                {
                    Trace.Write(exc.Message);
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// Implements the background tasks.
        /// </summary>
        /// <param name="state">Not used.</param>
        private void OnBkTask(object state)
        {
            if (!isRunning)
            {
                return;
            }

            try
            {
                // Update the service run time.

                perf.Runtime.RawValue = (int)(DateTime.UtcNow - startTime).TotalMinutes;

                if (pollTimer.HasFired)
                {
                    // Execute HTTP requests for all of the configured monitor URIs
                    // and then wait for them to return or timeout before setting the health status.
                    // Note that I'm configuring the request so the Host header will be set to
                    // the header in the URI but the request will actually be submitted to the
                    // local host.

                    try
                    {
                        if (services.Count == 0)
                        {
                            isHealthy = true;
                        }
                        else
                        {
                            bool fail = false;

                            for (int i = 0; i < this.services.Count; i++)
                            {
                                var site = services[i];

                                try
                                {
                                    using (var httpConnection = new HttpConnection(HttpOption.None))
                                    {
                                        HttpRequest  request;
                                        HttpResponse response;

                                        request = new HttpRequest("GET", site.Service.Uri, null);
                                        request["X-Health-Check"] = "true";

                                        httpConnection.Connect(new IPEndPoint(IPAddress.Loopback, site.Service.Uri.Port));
                                        response = httpConnection.Query(request, SysTime.Now + TimeSpan.FromSeconds(5));

                                        if (response.Status != HttpStatus.OK)
                                        {
                                            if (site.IsHealthy)
                                            {
                                                if (site.Service.IsCritical)
                                                {
                                                    SysLog.LogError("Critical local service [{0}] transitioned to unhealthy status with code [{1}={2}].", site.Service.Uri, response.Status, (int)response.Status);
                                                }
                                                else
                                                {
                                                    SysLog.LogWarning("Noncritical local service [{0}] transitioned to unhealthy status with code [{1}={2}].", site.Service.Uri, response.Status, (int)response.Status);
                                                }
                                            }

                                            if (site.Service.IsCritical)
                                            {
                                                fail = true;
                                            }

                                            site.IsHealthy  = false;
                                            site.StatusCode = (int)response.Status;
                                        }
                                        else
                                        {
                                            if (!site.IsHealthy)
                                            {
                                                if (site.Service.IsCritical)
                                                {
                                                    SysLog.LogInformation("Critical local service [{0}] transitioned to healthy status.", site.Service.Uri);
                                                }
                                                else
                                                {
                                                    SysLog.LogInformation("Noncritical local service [{0}] transitioned to healthy status.", site.Service.Uri);
                                                }
                                            }

                                            site.IsHealthy  = true;
                                            site.StatusCode = (int)response.Status;
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    if (site.IsHealthy)
                                    {
                                        if (site.Service.IsCritical)
                                        {
                                            SysLog.LogError("Critical local service [{0}] transitioned to unhealthy status with exception [{1}]: {2}.", site.Service.Uri, e.GetType().Name, e.Message);
                                        }
                                        else
                                        {
                                            SysLog.LogWarning("Noncritical local service [{0}] transitioned to unhealthy status with exception [{1}]: {2}.", site.Service.Uri, e.GetType().Name, e.Message);
                                        }
                                    }

                                    if (site.Service.IsCritical)
                                    {
                                        fail = true;
                                    }

                                    site.IsHealthy  = false;
                                    site.StatusCode = 0;
                                }
                            }

                            isHealthy = !fail;
                        }
                    }
                    finally
                    {
                        pollTimer.Reset();
                    }
                }
            }
            catch (Exception e)
            {
                SysLog.LogException(e);
                isHealthy = false;
            }
            finally
            {
                // Update the status performance counter.

                this.perf.Status.RawValue = isHealthy ? 1 : 0;
            }
        }
Exemple #16
0
 /// <summary>
 /// Creates a new IConnection to a URL. Use to fetch and parse a HTML page.
 /// Use examples:
 /// <ul>
 /// <li><code>Document doc = NSoupClient.Connect("http://example.com").UserAgent("Mozilla").Data("name", "jsoup").Get();</code></li>
 /// <li><code>Document doc = NSoupClient.Connect("http://example.com").Cookie("auth", "token").Post();</code></li>
 /// </ul>
 /// </summary>
 /// <param name="url">URL to connect to. The protocol must be <code>http</code> or <code>https</code>.</param>
 /// <returns>the connection. You can add data, cookies, and headers; set the user-agent, referrer, method; and then execute.</returns>
 public static IConnection Connect(string url)
 {
     return(HttpConnection.Connect(url));
 }
        public void throwsExceptionOnBodyWithoutExecute()
        {
            var con = HttpConnection.Connect("http://example.com");

            con.Response().Body();
        }
Exemple #18
0
        public void throwsExceptionOnBodyAsBytesWithoutExecute()
        {
            IConnection con = HttpConnection.Connect("http://example.com");

            con.Response().BodyAsBytes();
        }
Exemple #19
0
        public void throwsExceptionOnParseWithoutExecute()
        {
            IConnection con = HttpConnection.Connect("http://example.com");

            con.Response().Parse();
        }
Exemple #20
0
        public void connectWithUrl()
        {
            IConnection con = HttpConnection.Connect(new Uri("http://example.com"));

            Assert.AreEqual("http://example.com/", con.Request().Url().ToString());
        }
Exemple #21
0
        public void throwsOnOdddData()
        {
            IConnection con = HttpConnection.Connect("http://example.com/");

            con.Data("Name", "val", "what");
        }
Exemple #22
0
        public void HttpConnection_Send_Fail()
        {
            EnhancedSocket sockListen = null;
            EnhancedSocket sockAccept = null;
            HttpConnection con;
            HttpRequest    request;
            HttpResponse   response;
            TimeSpan       orgTimeout;
            IAsyncResult   ar;

            orgTimeout = HttpStack.TimeoutSweepInterval;
            HttpStack.TimeoutSweepInterval = TimeSpan.FromMilliseconds(250);

            sockListen = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sockListen.Bind(new IPEndPoint(IPAddress.Any, ServerPort));
            sockListen.Listen(10);

            try
            {
                ar = sockListen.BeginAccept(null, null);

                con = new HttpConnection(HttpOption.None);
                con.Connect("http://localhost:" + ServerPort.ToString());

                sockAccept = sockListen.EndAccept(ar);

                request                   = new HttpRequest("GET", "/foo.htm", null);
                request.Content           = new BlockArray(new byte[100000]);
                request["Content-Length"] = request.Content.Size.ToString();

                ar = con.BeginQuery(request, DateTime.MaxValue, null, null);
                sockAccept.Close();
                sockAccept = null;

                try
                {
                    response = con.EndQuery(ar);
                    Assert.Fail();
                }
                catch
                {
                }

                Assert.IsTrue(con.IsClosed);
                con.Close();
            }
            finally
            {
                HttpStack.TimeoutSweepInterval = orgTimeout;

                if (sockListen != null)
                {
                    sockListen.Close();
                }

                if (sockAccept != null)
                {
                    sockAccept.Close();
                }
            }
        }
Exemple #23
0
 public void throwsOnMalformedUrl()
 {
     IConnection con = HttpConnection.Connect("bzzt");
 }