예제 #1
0
 public RequestMiddleware(RequestDelegate nextStep, IHttpClientCache httpClientCache,
                          IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
 {
     _nextStep           = nextStep;
     _httpRequestHandler = new HttpClientRequestHandler(httpClientCache, GlobalConfig.CircuitBreaker);
     _httpDataRepository = new HttpDataRepository(httpContextAccessor);
 }
예제 #2
0
        private void InvokeHandler(IHttpRequestHandler handler, HttpListenerContext context)
        {
            var handleHttpRequestCommand = new HandleHttpRequestCommand(handler, context);
            var handleHttpRequestThread  = new Thread(handleHttpRequestCommand.Execute);

            handleHttpRequestThread.Start();
        }
예제 #3
0
        public TickerService(IHttpRequestHandler httpRequestHandler, IConfiguration configuration)
        {
            _httpRequestHandler = httpRequestHandler;
            _configuration      = configuration;

            _url = _configuration.GetSection("endpoints").GetSection("mercadobitcoin").Value;
        }
예제 #4
0
 protected DnsResolvedHttpClientHandler(IHttpRequestHandler requestHandler = null, bool disableDnsQuery = false)
 {
     this.requestHandler  = requestHandler;
     this.disableDnsQuery = disableDnsQuery;
     // SSL bypass
     ServerCertificateCustomValidationCallback = DangerousAcceptAnyServerCertificateValidator;
 }
예제 #5
0
        public bool TryGetHandler(string method, Uri url, out IHttpRequestHandler handler)
        {
            var definition = new Definition(method, url);

            if (_concreteHandlers.TryGetValue(definition, out handler))
            {
                return(true);
            }

            var httpMethod = (HttpVerb)Enum.Parse(_verbType, method, true);

            foreach (var requestHandler in _requestHandlers)
            {
                if (!requestHandler.Applicable(httpMethod, url))
                {
                    continue;
                }

                _concreteHandlers.Add(definition, requestHandler);
                handler = requestHandler;
                break;
            }

            return(handler != null);
        }
예제 #6
0
        /// <summary>
        /// Constructs an actual <see cref="IOpsGenieApiClient"/>.
        /// </summary>
        /// <param name="httpHandler">The <see cref="IHttpRequestHandler"/> to use</param>
        /// <param name="settings">The <see href="https://www.opsgenie.com/">opsgenie</see> API settings</param>
        public OpsGenieApiClient(
            IHttpRequestHandler httpHandler,
            OpsGenieSettings settings)
        {
            if (httpHandler == null)
            {
                throw new ArgumentNullException(nameof(httpHandler));
            }

            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            if (string.IsNullOrWhiteSpace(settings.ApiKey))
            {
                throw new ArgumentException("settings.ApiKey was not set", nameof(settings.ApiKey));
            }
            if (string.IsNullOrWhiteSpace(settings.HeartbeatName))
            {
                throw new ArgumentException("settings.HeartbeatName was not set", nameof(settings.HeartbeatName));
            }

            this.httpHandler = httpHandler;

            headerApiKeyValue = $"GenieKey {settings.ApiKey}";

            var encodedHeartbeatName = HttpUtility.UrlEncode(settings.HeartbeatName);

            heartbeatUrl = $"https://api.opsgenie.com/v2/heartbeats/{encodedHeartbeatName}/ping";
        }
예제 #7
0
 public CoreDumpAnalyzer(IArchiveHandler archiveHandler, IFilesystem filesystem, IProcessHandler processHandler, IHttpRequestHandler requestHandler)
 {
     this.archiveHandler = archiveHandler ?? throw new ArgumentNullException("ArchiveHandler must not be null!");
     this.filesystem     = filesystem ?? throw new ArgumentNullException("Filesystem must not be null!");
     this.processHandler = processHandler ?? throw new ArgumentNullException("ProcessHandler must not be null!");
     this.requestHandler = requestHandler ?? throw new ArgumentNullException("RequestHandler must not be null!");
 }
예제 #8
0
 /// <summary>
 /// Map an IHttpRequestHandler instance to a URI
 /// </summary>
 /// <param name="uri"></param>
 /// <param name="handler"></param>
 public void AddHttpRequestHandler(string uri, IHttpRequestHandler handler)
 {
     // TODO: Verify URI
     lock (m_handlers)
     {
         m_handlers.Add(uri, handler);
     }
 }
 public IHttpRoutable Ascent(IHttpRequestHandler fallback = null)
 {
     if (fallback != null)
     {
         _pipeline.PushUnconditional(fallback);
     }
     return(_parent);
 }
예제 #10
0
		/// <summary>
		/// Map an IHttpRequestHandler instance to a URI
		/// </summary>
		/// <param name="uri"></param>
		/// <param name="handler"></param>
        public void AddHttpRequestHandler(string uri, IHttpRequestHandler handler)
        {
            // TODO: Verify URI
            lock (m_handlers)
            {
                m_handlers.Add(uri, handler);
            }
        }
        public WebServer(int port, IHttpRequestHandler mvcRequestHandler, IHttpRequestHandler fileHandler)
        {
            this.port     = port;
            this.listener = new TcpListener(IPAddress.Parse(LocalhostIPAddress), port);

            this.mvcRequestHandler = mvcRequestHandler;
            this.fileHandler       = fileHandler;
        }
 private void InvokeHandler(IHttpRequestHandler handler, HttpListenerContext context)
 {
     if (handler == null)
         return;
     Console.WriteLine("Request being handled");
     HandleHttpRequestCommand command = new HandleHttpRequestCommand(handler, context);
     Thread commandThread = new Thread(command.Execute);
     commandThread.Start();
 }
 public void PushConditional(IHttpRouteCondition condition, IHttpRequestHandler handler, Func <HttpRouter> routerFactory)
 {
     if (_currentRouter == null)
     {
         _currentRouter = routerFactory();
         _handlers.Add(_currentRouter);
     }
     _currentRouter.When(condition, handler);
 }
예제 #14
0
파일: HttpServer.cs 프로젝트: kodlar/r-i-m
        public HttpServer(IHttpRequestHandler requestHandler,
                          IClientFactory clientFactory,
                          IClientContainer clientContainer,
                          IFirewall firewall) : this(requestHandler, clientFactory, clientContainer, firewall, null)
        {
            string serialized = System.IO.File.ReadAllText("rimserver.json");

            Options = JsonConvert.DeserializeObject <ServerOptions>(serialized);
        }
예제 #15
0
        public HttpProcessor(TcpClient socket, IHttpRequestHandler requestHandler)
        {
            Socket = socket;
            RequestHandler = requestHandler;
            HttpHeaders = new Hashtable();

            InputStream = new BufferedStream(Socket.GetStream());
            OutputWriter = new StreamWriter(new BufferedStream(Socket.GetStream()));
        }
        public ConnectionHandler(
            Socket client,
            IHttpRequestHandler httpRequestHandler)
        {
            CoreValidator.ThrowIfNull(client, nameof(client));
            CoreValidator.ThrowIfNull(httpRequestHandler, nameof(httpRequestHandler));

            this.client             = client;
            this.httpRequestHandler = httpRequestHandler;
        }
예제 #17
0
        public DasyncMiddleware(IOptionsMonitor <DasyncOptions> optionsMonitor, IHttpRequestHandler httpRequestHandler)
        {
            _options            = optionsMonitor.CurrentValue;
            _httpRequestHandler = httpRequestHandler;

            if (_options.ApiPath == null)
            {
                _options.ApiPath = DasyncOptions.Defaults.ApiPath;
            }
        }
        private void InvokeHandler(IHttpRequestHandler requestHandler, HttpListenerContext context)
        {
            var handleHttpRequestCommand = new HttpRequestExecutor(requestHandler, context);
            var handleHttpRequestThread  = new Thread(new ThreadStart(() =>
            {
                handleHttpRequestCommand.Execute();
            }));

            handleHttpRequestThread.Start();
        }
예제 #19
0
 public void AddHttpRequestHandler(IHttpRequestHandler httpRequestHandler)
 {
     if (!_httpRequestHandlers.ContainsKey(httpRequestHandler.GetName()))
     {
         _httpRequestHandlers.Add(httpRequestHandler.GetName(), httpRequestHandler);
     }
     else
     {
         _httpRequestHandlers[httpRequestHandler.GetName()] = httpRequestHandler;
     }
 }
예제 #20
0
 public void AddRequestHandler(IHttpRequestHandler handler)
 {
     if (!handlerDictionary.ContainsKey(handler.GetName()))
     {
         handlerDictionary.Add(handler.GetName(), handler);   //currently, the handler doesn't exist in the dictionary, so add it
     }
     else
     {
         handlerDictionary[handler.GetName()] = handler;      //replace the request handler with the new one
     }
 }
 public void AddHttpRequestHandler(IHttpRequestHandler httpRequestRequestHandler)
 {
     if (_httpRequestHandlers.ContainsKey(httpRequestRequestHandler.Name))
     {
         _httpRequestHandlers[httpRequestRequestHandler.Name] = httpRequestRequestHandler;
     }
     else
     {
         _httpRequestHandlers.Add(httpRequestRequestHandler.Name, httpRequestRequestHandler);
     }
 }
 public void AddRequestHandler(IHttpRequestHandler handler)
 {
     if (!handlerDictionary.ContainsKey(handler.GetName()))
     {
         handlerDictionary.Add(handler.GetName(), handler);   //currently, the handler doesn't exist in the dictionary, so add it
     }
     else
     {
         handlerDictionary[handler.GetName()] = handler;      //replace the request handler with the new one
     }
 }
예제 #23
0
        public void HandleContext(RequestData data)
        {
            HttpListenerRequest request = data.Context.Request;

            Log.Debug($"Received request to {request.Url.AbsolutePath}");
            string requestHandlerName = request.Url.AbsolutePath;
            // Find corresponding handler
            IHttpRequestHandler handler = this._httpRequestHandlers.ContainsKey(requestHandlerName) ? this._httpRequestHandlers[requestHandlerName] : _httpRequestHandlers[InvalidRequestHandler.Path];

            // Invoke chosen handler
            this.InvokeHandler(handler, data);
        }
예제 #24
0
    private void InvokeHandler(IHttpRequestHandler handler, HttpListenerContext context)
    {
        if (handler == null)
        {
            return;
        }
        Console.WriteLine("Request being handled");
        HandleHttpRequestCommand command = new HandleHttpRequestCommand(handler, context);
        Thread commandThread             = new Thread(command.Execute);

        commandThread.Start();
    }
예제 #25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AirbrakeNotifier"/> class.
        /// </summary>
        /// <param name="config">The <see cref="AirbrakeConfig"/> instance to use.</param>
        /// <param name="httpRequestHandler">The <see cref="IHttpRequestHandler"/> implementation to use.</param>
        public AirbrakeNotifier(AirbrakeConfig config, IHttpRequestHandler httpRequestHandler = null)
        {
            this.config = config ?? throw new ArgumentNullException(nameof(config));

            if (!string.IsNullOrEmpty(config.LogFile))
            {
                logResponse = response => Utils.LogResponse(config.LogFile, response);
            }

            // use default provider that returns HttpWebRequest from standard .NET library
            // if custom implementation has not been provided
            this.httpRequestHandler = httpRequestHandler ?? new HttpRequestHandler(config.ProjectId, config.ProjectKey, config.Host);
        }
예제 #26
0
        public ConnectionHandler(
            Socket client,
            IHttpRequestHandler mvcRequestHandler,
            IHttpRequestHandler fileHandler)
        {
            Validation.EnsureNotNull(client, nameof(client));
            Validation.EnsureNotNull(mvcRequestHandler, nameof(mvcRequestHandler));
            Validation.EnsureNotNull(fileHandler, nameof(fileHandler));

            this.client            = client;
            this.mvcRequestHandler = mvcRequestHandler;
            this.fileHandler       = fileHandler;
        }
예제 #27
0
        private async Task HandleRequest(HttpListenerContext context, IHttpRequestHandler handler)
        {
            using var cancellationSource = new CancellationTokenSource();
            using var dependencyScope    = _dependencyProvider.CreateScope();

            try
            {
                await handler.Handle(context, cancellationSource.Token);
            }
            catch (Exception)
            {
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            }
        }
예제 #28
0
 protected override void ProcessSession(ISession session)
 {
     try {
         HttpProcessor processor = new HttpProcessor(session);
         using (HttpContext context = processor.CreateHttpContext()) {
             Debug.WriteLine(context.Request.RequestUri);
             context.Response.Server = _serverName;
             IHttpRequestHandler handler = GetHandler(context.Request.RequestUri);
             if (handler != null)
             {
                 try {
                     handler.Handle(context);
                 }
                 catch (Exception) {
                     context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                     context.Response.Content    = new StringContent("<html><body><h1>Internal Server Error</h1></body></html>", MediaType.TEXT_HTML);
                 }
             }
             else
             {
                 context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                 context.Response.Content    = new StringContent("<html><body><h1>Not Found</h1></body></html>", MediaType.TEXT_HTML);
             }
         }
     }
     catch (HttpException ex) {
         using (HttpContext context = new HttpContext(session)) {
             context.Response                   = new HttpResponse();
             context.Response.Server            = _serverName;
             context.Response.StatusCode        = ex.StatusCode;
             context.Response.StatusDescription = ex.Message;
             context.Response.Content           = new StringContent(string.Format("<html><body><h1>{0}</h1></body></html>", ex.Message), MediaType.TEXT_HTML);
         }
     }
     catch (Exception ex) {
         using (HttpContext context = new HttpContext(session)) {
             context.Response            = new HttpResponse();
             context.Response.Server     = _serverName;
             context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
             context.Response.Content    = new StringContent("<html><body><h1>Internal Server Error</h1></body></html>", MediaType.TEXT_HTML);
         }
     }
 }
예제 #29
0
        public void Start()
        {
            if (server != null)
            {
                try
                {
                    server.Start();
                    Talk.Info("Started on port " + port);
                }
                catch (Exception e) {
                    Talk.Error("Failed to start on port " + port + ". " + e.ToString());
                    return;
                }

                isRunning = true;
                new Thread(() =>
                {
                    while (isRunning)
                    {
                        var context = server.GetContext();
                        IHttpRequestHandler handler = null;

                        Talk.Info("From: '" + context.Request.RemoteEndPoint.Address + ", Request => " + context.Request.Url);

                        // get relative url cause handlers are sotred by relative keys
                        var url = GetRealtiveUrl(context.Request.Url.ToString());

                        if (requestHandlers.TryGetValue(url, out handler))
                        {
                            handler.HandleRequest(context);
                        }
                        else
                        {
                            new RestPrefixNotRegistredHandler().HandleRequest(context);
                        }
                    }
                }).Start();
            }
            else
            {
                Talk.Warning("Not initialized. Server not started.");
            }
        }
예제 #30
0
        /// <summary>
        /// Find the matching handler for the request
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="partialUri"></param>
        /// <returns></returns>
        internal IHttpRequestHandler GetHandlerForUri(string uri, out string partialUri)
        {
            partialUri = uri;
            int length = 0;
            IHttpRequestHandler handler = null;

            lock (m_handlers)
            {
                // Find the longest match
                foreach (string mapped in m_handlers.Keys)
                {
                    if (uri.StartsWith(mapped) && (mapped.Length > length))
                    {
                        length     = mapped.Length;
                        handler    = m_handlers[mapped];
                        partialUri = uri.Substring(length);
                    }
                }
            }
            return(handler);
        }
예제 #31
0
파일: HttpServer.cs 프로젝트: kodlar/r-i-m
        public HttpServer(IHttpRequestHandler requestHandler,
                          IClientFactory clientFactory,
                          IClientContainer clientContainer,
                          IFirewall firewall,
                          ServerOptions options)
        {
            RequestHandler = requestHandler;
            ClientFactory  = clientFactory;
            Container      = Container;

            if (firewall != null)
            {
                Firewall = firewall;
            }

            if (options != null)
            {
                Options = options;
            }

            Logger = new ErrorLogger(this);
        }
예제 #32
0
        private void LoadRoute(IHttpRequestHandler root)
        {
            var rootType = root.GetType();

            if (LoadedRoutes.Contains(rootType))
            {
                return;
            }

            lock (SyncRoot) {
                if (LoadedRoutes.Add(rootType))
                {
                    var routes = GetRoutesOfHandler(rootType);
                    foreach (var route in routes)
                    {
                        var tuple = Tuple.Create(rootType, route.Name);
                        var value = CreateRoute(tuple);
                        Routers.Add(tuple, value);
                    }
                }
            }
        }
예제 #33
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AirbrakeNotifier"/> class.
        /// </summary>
        /// <param name="config">The <see cref="AirbrakeConfig"/> instance to use.</param>
        /// <param name="logger">The <see cref="ILogger"/> implementation to use.</param>
        /// <param name="httpRequestHandler">The <see cref="IHttpRequestHandler"/> implementation to use.</param>
        public AirbrakeNotifier(AirbrakeConfig config, ILogger logger = null, IHttpRequestHandler httpRequestHandler = null)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            this.config = config;

            // use default FileLogger if no custom implementation has been provided
            // but config contains non-empty value for "LogFile" property
            if (logger != null)
            {
                this.logger = logger;
            }
            else if (!string.IsNullOrEmpty(config.LogFile))
            {
                this.logger = new FileLogger(config.LogFile);
            }

            // use default provider that returns HttpWebRequest from standard .NET library
            // if custom implementation has not been provided
            this.httpRequestHandler = httpRequestHandler ?? new HttpRequestHandler(config.ProjectId, config.ProjectKey, config.Host);
        }
예제 #34
0
 public void AddPageHandler(string path, IHttpRequestHandler handler)
 {
     _handlers[path] = handler;
 }
예제 #35
0
        public HttpRouter With(string function, IHttpRequestHandler handler)
        {
            _handlers.Add(function, handler);

            return this;
        }
 public HandleHttpRequestCommand(IHttpRequestHandler handler, HttpListenerContext context)
 {
     this.handler = handler;
     this.context = context;
 }
예제 #37
0
 public void AddRequestHandler(IHttpRequestHandler handler)
 {
     resourceLocator.AddRequestHandler(handler);
 }
예제 #38
0
 public UrlsHandler AddCriteria(Regex Regex, IHttpRequestHandler Handler)
 {
     Criterias.Add(new Tuple<Regex, IHttpRequestHandler>(Regex, Handler));
     return this;
 }
예제 #39
0
 public void Use(IHttpRequestHandler handler)
 {
     _handlers.Add(handler);
 }