Example #1
0
        public void Route(string[] methods, string path, EndpointHandler cb, string[] flags)
        {
            unsafe {
                int         epId = 0;
                HandlerInfo target;

                if (endpointIds.TryGetValue(path, out epId))
                {
                    target = handlers[epId];
                }
                else
                {
                    CoreEndpoint *ep = Core.ice_server_router_add_endpoint(inst, path);
                    epId = Core.ice_core_endpoint_get_id(ep);

                    target = new HandlerInfo();
                    target.SetCoreEndpoint(ep);

                    handlers[epId]    = target;
                    endpointIds[path] = epId;
                }

                foreach (string flag in flags)
                {
                    Core.ice_core_endpoint_set_flag(target.GetCoreEndpoint(), flag, true);
                }

                foreach (string m in methods)
                {
                    target.AddTargetForMethod(m, cb);
                }
            }
        }
Example #2
0
        public static string GetString(EnhancedImageServer server, string endPoint, string query = "",
			ContentType returnType = ContentType.Text, EndpointHandler handler = null, string endOfUrlForTest = null)
        {
            if(handler != null)
            {
                server.RegisterEndpointHandler(endPoint, handler);
            }
            server.StartListening();
            var client = new WebClientWithTimeout
            {
                Timeout = 3000,
            };
            client.Headers[HttpRequestHeader.ContentType] = returnType == ContentType.Text ? "text/plain" : "application/json";

            if(endOfUrlForTest != null)
            {
                return client.DownloadString(ServerBase.ServerUrlWithBloomPrefixEndingInSlash + "api/" + endOfUrlForTest);
            }
            else
            {
                if(!string.IsNullOrEmpty(query))
                    query = "?" + query;
                return client.DownloadString(ServerBase.ServerUrlWithBloomPrefixEndingInSlash + "api/" + endPoint + query);
            }
        }
Example #3
0
        public static string GetString(BloomServer server, string endPoint, string query = "",
                                       ContentType returnType = ContentType.Text, EndpointHandler handler = null, string endOfUrlForTest = null)
        {
            if (handler != null)
            {
                server.ApiHandler.RegisterEndpointHandler(endPoint, handler, true);
            }
            server.StartListening();
            var client = new WebClientWithTimeout
            {
                Timeout = 3000,
            };

            client.Headers[HttpRequestHeader.ContentType] = returnType == ContentType.Text ? "text/plain" : "application/json";

            if (endOfUrlForTest != null)
            {
                return(client.DownloadString(BloomServer.ServerUrlWithBloomPrefixEndingInSlash + "api/" + endOfUrlForTest));
            }
            else
            {
                if (!string.IsNullOrEmpty(query))
                {
                    query = "?" + query;
                }
                return(client.DownloadString(BloomServer.ServerUrlWithBloomPrefixEndingInSlash + "api/" + endPoint + query));
            }
        }
Example #4
0
        public EndpointMiddleware(RequestDelegate next, CompositionHost host, ILoggerFactory loggerFactory)
        {
            _next           = next;
            _host           = host;
            _projectSystems = host.GetExports <IProjectSystem>();
            _logger         = loggerFactory.CreateLogger <EndpointMiddleware>();
            var endpoints = _host.GetExports <Lazy <IRequest, EndpointDescriptor> >()
                            .Select(x => x.Metadata);

            var handlers = _host.GetExports <Lazy <IRequestHandler, OmniSharpLanguage> >();

            _endpoints = new HashSet <string>(
                endpoints
                .Select(x => x.EndpointName)
                .Distinct(),
                StringComparer.OrdinalIgnoreCase
                );

            var updateBufferEndpointHandler   = new Lazy <EndpointHandler <UpdateBufferRequest, object> >(() => (EndpointHandler <UpdateBufferRequest, object>)_endpointHandlers[OmnisharpEndpoints.UpdateBuffer].Value);
            var languagePredicateHandler      = new LanguagePredicateHandler(_projectSystems);
            var projectSystemPredicateHandler = new StaticLanguagePredicateHandler("Projects");
            var nugetPredicateHandler         = new StaticLanguagePredicateHandler("NuGet");
            var endpointHandlers = endpoints.ToDictionary(
                x => x.EndpointName,
                endpoint => new Lazy <EndpointHandler>(() =>
            {
                IPredicateHandler handler;

                // Projects are a special case, this allows us to select the correct "Projects" language for them
                if (endpoint.EndpointName == OmnisharpEndpoints.ProjectInformation || endpoint.EndpointName == OmnisharpEndpoints.WorkspaceInformation)
                {
                    handler = projectSystemPredicateHandler;
                }
                else if (endpoint.EndpointName == OmnisharpEndpoints.PackageSearch || endpoint.EndpointName == OmnisharpEndpoints.PackageSource || endpoint.EndpointName == OmnisharpEndpoints.PackageVersion)
                {
                    handler = nugetPredicateHandler;
                }
                else
                {
                    handler = languagePredicateHandler;
                }

                // This lets any endpoint, that contains a Request object, invoke update buffer.
                // The language will be same language as the caller, this means any language service
                // must implement update buffer.
                var updateEndpointHandler = updateBufferEndpointHandler;
                if (endpoint.EndpointName == OmnisharpEndpoints.UpdateBuffer)
                {
                    // We don't want to call update buffer on update buffer.
                    updateEndpointHandler = new Lazy <EndpointHandler <UpdateBufferRequest, object> >(() => null);
                }

                return(EndpointHandler.Factory(handler, _host, _logger, endpoint, handlers, updateEndpointHandler, Enumerable.Empty <Plugin>()));
            }),
                StringComparer.OrdinalIgnoreCase
                );

            _endpointHandlers = new ReadOnlyDictionary <string, Lazy <EndpointHandler> >(endpointHandlers);
        }
Example #5
0
 public AccountController(IDao <Account> dao)
 {
     if (endpointHandler != null)
     {
         return;
     }
     endpointHandler = new EndpointHandler(dao);
 }
Example #6
0
 /// <summary>
 /// Get called when a client (i.e. javascript) does an HTTP api call
 /// </summary>
 /// <param name="pattern">Simple string or regex to match APIs that this can handle. This must match what comes after the ".../api/" of the URL</param>
 /// <param name="handler">The method to call</param>
 /// <param name="handleOnUiThread">For safety, this defaults to true, but that can kill performance if you don't need it (BL-3452) </param>
 public void RegisterEndpointHandler(string pattern, EndpointHandler handler, bool handleOnUiThread = true)
 {
     _endpointRegistrations[pattern.ToLowerInvariant().Trim(new char[] { '/' })] = new EndpointRegistration()
     {
         Handler          = handler,
         HandleOnUIThread = handleOnUiThread
     };
 }
Example #7
0
 /// <summary>
 /// Samed as RegisterEndpointHandler, but for Endpoints that may be called by other endpoint handlers which are synchronous.
 /// If so, sets RequiresSync to false (because it would deadlock if a synchronous handler spawned off another synchronous handler)
 /// The caller should make sure that this endpoint handler can operate correctly without exclusive access to the lock!
 /// </summary>
 /// <param name="pattern">Simple string or regex to match APIs that this can handle. This must match what comes after the ".../api/" of the URL</param>
 /// <param name="handler">The method to call</param>
 /// <param name="handleOnUiThread">If true, the current thread will suspend until the UI thread can be used to call the method.
 /// This deliberately no longer has a default. It's something that should be thought about.
 /// Making it true can kill performance if you don't need it (BL-3452), and complicates exception handling and problem reporting (BL-4679).
 /// There's also danger of deadlock if something in the UI thread is somehow waiting for this request to complete.
 /// But, beware of race conditions or anything that manipulates UI controls if you make it false.</param>
 public void RegisterEndpointHandlerUsedByOthers(string pattern, EndpointHandler handler, bool handleOnUiThread)
 {
     _endpointRegistrations[pattern.ToLowerInvariant().Trim(new char[] { '/' })] = new EndpointRegistration()
     {
         Handler          = handler,
         HandleOnUIThread = handleOnUiThread,
         RequiresSync     = false
     };
 }
Example #8
0
        private static void ProcessRequest(EndpointHandler endpointHandler, EndpointHandlerRegister handlerRegister, TcpClient client)
        {
            try
            {
                NetworkStream requestStream = client.GetStream();

                Console.WriteLine($"Nachricht erhalten um: {DateTime.Now} Client: {client.Client.RemoteEndPoint}");
                Console.WriteLine("-----------------------------------------------------------------------------");

                HttpRequestParser requestParser = new HttpRequestParser();
                RequestContext    context;

                context = requestParser.ParseRequestStream(requestStream);

                Console.WriteLine("-----------------------------------------------------------------------------");
                Console.WriteLine();

                RouteMatch match = handlerRegister.GetEndPointHandler(context);

                if (match != null)
                {
                    IActionResult result = endpointHandler.Invoke(match, client, context);
                    result.Execute();
                }
                else
                {
                    HttpStatusCodeResult.NotFound(client)
                    .Execute();
                }

                client.Close();
            }
            catch (HttpRequestParserException parserEx)
            {
                string parseErrorMessage = $"Ungültiger Request, parsen nicht möglich: {parserEx.Message}";

                Console.WriteLine(parseErrorMessage);
                HttpStatusCodeResult.BadRequest(client, parseErrorMessage)
                .Execute();
            }
            catch (Exception ex) when(ex is EndPointHandlerException || ex is EndpointHandlerRegisterException)
            {
                HttpStatusCodeResult.BadRequest(client, ex.GetFullMessage(verbose: true))
                .Execute();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unerwarteter Fehler: {ex.Message}");

                HttpStatusCodeResult.InternalServerError(client)
                .Execute();
            }
            finally
            {
                client.Close();
            }
        }
Example #9
0
        public void RouteFallback(string[] methods, string path, EndpointHandler cb)
        {
            HandlerInfo target = new HandlerInfo();

            foreach (string m in methods)
            {
                target.AddTargetForMethod(m, cb);
            }
            fallbackHandlers.Insert(0, new KeyValuePair <string, HandlerInfo>(path, target));
        }
Example #10
0
 public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "records")] HttpRequest req, ILogger log)
 {
     try
     {
         EndpointHandler handler = DependencyBootstrapper.Container.Resolve(typeof(SaveEndpointHandler)) as EndpointHandler;
         return(await handler.HandleAsync(req, log));
     }
     catch (System.Exception e)
     {
         return(new ObjectResult(ErrorResponseModel.FromInternal(e.Message)));
     }
 }
Example #11
0
        /// <summary>
        /// Get called when a client (i.e. javascript) does an HTTP api call
        /// </summary>
        /// <param name="pattern">Simple string or regex to match APIs that this can handle. This must match what comes after the ".../api/" of the URL</param>
        /// <param name="handler">The method to call</param>
        /// <param name="handleOnUiThread">If true, the current thread will suspend until the UI thread can be used to call the method.
        /// This deliberately no longer has a default. It's something that should be thought about.
        /// Making it true can kill performance if you don't need it (BL-3452), and complicates exception handling and problem reporting (BL-4679).
        /// There's also danger of deadlock if something in the UI thread is somehow waiting for this request to complete.
        /// But, beware of race conditions or anything that manipulates UI controls if you make it false.</param>
        /// <param name="requiresSync">True if the handler wants the server to ensure no other thread is doing an api
        /// call while this one is running. This is our default behavior, ensuring that no API request can interfere with any
        /// other in any unexpected way...essentially all Bloom's data is safe from race conditions arising from
        /// server threads manipulating things on background threads. However, it makes it impossible for a new
        /// api call to interrupt a previous one. For example, when one api call is creating an epub preview
        /// and we get a new one saying we need to abort that (because one of the property buttons has changed),
        /// the epub that is being generated is obsolete and we want the new api call to go ahead so it can set a flag
        /// to abort the one in progress. To avoid race conditions, api calls that set requiresSync false should be kept small
        /// and simple and be very careful about touching objects that other API calls might interact with.</param>
        public EndpointRegistration RegisterEndpointHandler(string pattern, EndpointHandler handler, bool handleOnUiThread, bool requiresSync = true)
        {
            var registration = new EndpointRegistration()
            {
                Handler          = handler,
                HandleOnUIThread = handleOnUiThread,
                RequiresSync     = requiresSync,
                MeasurementLabel = pattern,                 // can be overridden... this is just a default
            };

            _endpointRegistrations[pattern.ToLowerInvariant().Trim(new char[] { '/' })] = registration;
            return(registration);            // return it so the caller can say  RegisterEndpointHandler().Measurable();
        }
Example #12
0
        public static string PostString(EnhancedImageServer server, string endPoint, string data, ContentType returnType,
			EndpointHandler handler = null)
        {
            if(handler != null)
            {
                server.RegisterEndpointHandler(endPoint, handler);
            }
            server.StartListening();
            var client = new WebClientWithTimeout
            {
                Timeout = 3000
            };
            client.Headers[HttpRequestHeader.ContentType] = returnType == ContentType.Text ? "text/plain" : "application/json";

            return client.UploadString(ServerBase.ServerUrlWithBloomPrefixEndingInSlash + "api/" + endPoint, "POST", data);
        }
Example #13
0
        public static string PostString(BloomServer server, string endPoint, string data, ContentType returnType,
                                        EndpointHandler handler = null)
        {
            if (handler != null)
            {
                server.ApiHandler.RegisterEndpointHandler(endPoint, handler, true);
            }
            server.StartListening();
            var client = new WebClientWithTimeout
            {
                Timeout = 3000
            };

            client.Headers[HttpRequestHeader.ContentType] = returnType == ContentType.Text ? "text/plain" : "application/json";

            return(client.UploadString(BloomServer.ServerUrlWithBloomPrefixEndingInSlash + "api/" + endPoint, "POST", data));
        }
Example #14
0
        private Task <Response> defaultHandler(Request req)
        {
            string uri = req.Uri;

            foreach (var p in fallbackHandlers)
            {
                if (uri.StartsWith(p.Key, System.StringComparison.Ordinal))
                {
                    EndpointHandler target = p.Value.GetTarget(req);
                    if (target != null)
                    {
                        return(target(req));
                    }
                }
            }

            return(Task.FromResult(req.CreateResponse().SetStatus(404).SetBody("Not found")));
        }
Example #15
0
        public void SupportsHandlerInjection()
        {
            // Setup
            using (var server = CreateBloomServer())
            {
                var             transaction = new PretendRequestInfo(BloomServer.ServerUrlWithBloomPrefixEndingInSlash + "api/thisWontWorkWithoutInjectionButWillWithIt");
                EndpointHandler testFunc    = (request) =>
                {
                    Assert.That(request.LocalPath(), Does.Contain("thisWontWorkWithoutInjection"));
                    Assert.That(request.CurrentCollectionSettings, Is.EqualTo(server.CurrentCollectionSettings));
                    request.ReplyWithText("Did It!");
                };
                server.ApiHandler.RegisterEndpointLegacy("thisWontWorkWithoutInjection", testFunc, true);

                // Execute
                server.MakeReply(transaction);

                // Verify
                Assert.That(transaction.ReplyContents, Is.EqualTo("Did It!"));
            }
        }
Example #16
0
        private void ExecuteWebServer()
        {
            TcpListener listener = new TcpListener(Address, Port);

            Console.WriteLine($"Starte WebServer auf {Address}:{Port}.");

            EndpointHandler         endpointHandler = new EndpointHandler(ServiceProvider);
            EndpointHandlerRegister handlerRegister = new EndpointHandlerRegister(HandlerTypes);

            try
            {
                listener.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error starting TcpListener: {ex.Message}");
                return;
            }

            Console.WriteLine("Webserver wurde erfolgreich gestartet.");

            try
            {
                while (true)
                {
                    TcpClient client = listener.AcceptTcpClient();
                    Task.Run(() => ProcessRequest(endpointHandler, handlerRegister, client));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error AcceptClient: {ex.Message}");
            }
            finally
            {
                listener.Stop();
            }
        }
Example #17
0
        private async Task realEndpointCallback(int id, Request req)
        {
            try {
                HandlerInfo     info   = handlers[id];
                EndpointHandler target = info.GetTarget(req);
                if (target == null)
                {
                    target = handlers[-1].GetTarget(req);
                }
                Response resp;

                try {
                    resp = await target(req);
                } catch (System.Exception e) {
                    resp = req.CreateResponse()
                           .SetStatus(500)
                           .SetBody(e.ToString());
                }
                resp.Send();
            } catch (System.Exception e) {
                System.Console.WriteLine(e);
            }
        }
 public DeleteEndpointHanlderTests()
 {
     _endpointRepository    = new EndpointFakeRepository();
     _endpointHandler       = new EndpointHandler(_endpointRepository);
     _deleteEndpointCommand = new DeleteEndpointCommand("1");
 }
 public GenericCommandResult Put(
     [FromBody] UpdateEndpointCommand command,
     [FromServices] EndpointHandler handler)
 {
     return((GenericCommandResult)handler.Handle(command));
 }
 public GenericCommandResult Delete(
     string serialNumber,
     [FromServices] EndpointHandler handler)
 {
     return((GenericCommandResult)handler.Handle(new DeleteEndpointCommand(serialNumber)));
 }
 /// <summary>
 /// Get called when a client (i.e. javascript) does an HTTP api call
 /// </summary>
 /// <param name="pattern">Simple string or regex to match APIs that this can handle. This must match what comes after the ".../api/" of the URL</param>
 /// <param name="handler">The method to call</param>
 /// <param name="handleOnUiThread">For safety, this defaults to true, but that can kill performance if you don't need it (BL-3452) </param>
 public void RegisterEndpointHandler(string pattern, EndpointHandler handler, bool handleOnUiThread = true)
 {
     _endpointRegistrations[pattern.ToLowerInvariant().Trim(new char[] {'/'})] = new EndpointRegistration()
     {
         Handler = handler,
         HandleOnUIThread = handleOnUiThread
     };
 }
Example #22
0
 public void Route(string path, EndpointHandler cb)
 {
     Route("", path, cb);
 }
Example #23
0
 public void Route(string method, string path, EndpointHandler cb)
 {
     Route(new string[] { method }, path, cb);
 }
Example #24
0
 public void Route(string[] methods, string path, EndpointHandler cb)
 {
     Route(methods, path, cb, new string[] {});
 }
Example #25
0
 public void SetUp()
 {
     _dao             = new Mock <IDao <Account> >();
     _endpointHandler = new EndpointHandler(_dao.Object);
 }
 public EndpointMiddlewareFacde()
 {
     this.endpointRouteBuilder = new EndpointRouteBuilder();
     this.endpointRoute        = new EndpointRoute();
     this.endpointHandler      = new EndpointHandler();
 }
 public GenericCommandResult Post(
     [FromBody] RegisterEndpointCommand command,
     [FromServices] EndpointHandler handler)
 {
     return((GenericCommandResult)handler.Handle(command));
 }
Example #28
0
 public UpdateEndpointHanlderTests()
 {
     _endpointRepository    = new EndpointFakeRepository();
     _endpointHandler       = new EndpointHandler(_endpointRepository);
     _updateEndpointCommand = new UpdateEndpointCommand("1", EEndpointState.Connected);
 }
 public RegisterEndpointHanlderTests()
 {
     _endpointRepository      = new EndpointFakeRepository();
     _endpointHandler         = new EndpointHandler(_endpointRepository);
     _registerEndpointCommand = new RegisterEndpointCommand("2", 1, 1, "v 0.0.1", EEndpointState.Connected);
 }
Example #30
0
        private IDictionary <string, Lazy <EndpointHandler> > Initialize()
        {
            var workspace         = _compositionHost.GetExport <OmniSharpWorkspace>();
            var projectSystems    = _compositionHost.GetExports <IProjectSystem>();
            var endpointMetadatas = _compositionHost.GetExports <Lazy <IRequest, OmniSharpEndpointMetadata> >()
                                    .Select(x => x.Metadata)
                                    .ToArray();

            var handlers = _compositionHost.GetExports <Lazy <IRequestHandler, OmniSharpRequestHandlerMetadata> >();

            var updateBufferEndpointHandler = new Lazy <EndpointHandler <UpdateBufferRequest, object> >(
                () => (EndpointHandler <UpdateBufferRequest, object>)_endpointHandlers[OmniSharpEndpoints.UpdateBuffer].Value);
            var languagePredicateHandler      = new LanguagePredicateHandler(projectSystems);
            var projectSystemPredicateHandler = new StaticLanguagePredicateHandler("Projects");
            var nugetPredicateHandler         = new StaticLanguagePredicateHandler("NuGet");
            var endpointHandlers = endpointMetadatas.ToDictionary(
                x => x.EndpointName,
                endpoint => new Lazy <EndpointHandler>(() =>
            {
                IPredicateHandler handler;

                // Projects are a special case, this allows us to select the correct "Projects" language for them
                if (endpoint.EndpointName == OmniSharpEndpoints.ProjectInformation || endpoint.EndpointName == OmniSharpEndpoints.WorkspaceInformation)
                {
                    handler = projectSystemPredicateHandler;
                }
                else if (endpoint.EndpointName == OmniSharpEndpoints.PackageSearch || endpoint.EndpointName == OmniSharpEndpoints.PackageSource || endpoint.EndpointName == OmniSharpEndpoints.PackageVersion)
                {
                    handler = nugetPredicateHandler;
                }
                else
                {
                    handler = languagePredicateHandler;
                }

                // This lets any endpoint, that contains a Request object, invoke update buffer.
                // The language will be same language as the caller, this means any language service
                // must implement update buffer.
                var updateEndpointHandler = updateBufferEndpointHandler;
                if (endpoint.EndpointName == OmniSharpEndpoints.UpdateBuffer)
                {
                    // We don't want to call update buffer on update buffer.
                    updateEndpointHandler = new Lazy <EndpointHandler <UpdateBufferRequest, object> >(() => null);
                }

                return(EndpointHandler.Factory(handler, _compositionHost, _logger, endpoint, handlers, updateEndpointHandler, Enumerable.Empty <Plugin>()));
            }),
                StringComparer.OrdinalIgnoreCase
                );


            // Handled as alternative middleware in http
            endpointHandlers.Add(
                OmniSharpEndpoints.CheckAliveStatus,
                new Lazy <EndpointHandler>(
                    () => new GenericEndpointHandler(x => Task.FromResult <object>(true)))
                );
            endpointHandlers.Add(
                OmniSharpEndpoints.CheckReadyStatus,
                new Lazy <EndpointHandler>(
                    () => new GenericEndpointHandler(x => Task.FromResult <object>(workspace.Initialized)))
                );
            endpointHandlers.Add(
                OmniSharpEndpoints.StopServer,
                new Lazy <EndpointHandler>(
                    () => new GenericEndpointHandler(x =>
            {
                _cancellationTokenSource.Cancel();
                return(Task.FromResult <object>(null));
            }))
                );

            return(endpointHandlers);
        }
        public void SetupHandlerAndMessages()
        {
            ConcurrentBag <Battle> allBattles = new ConcurrentBag <Battle>();

            _myEndpointHandler = new EndpointHandler(ref allBattles);
        }
Example #32
0
 public IActionResult PostReset()
 {
     endpointHandler = null;
     return(Ok());
 }
Example #33
0
 public void AddPOSTEndpoint(string endpoint, EndpointHandler callback) => AddEndpoint(endpoint, callback, new HashSet <HttpMethod>()
 {
     HttpMethod.Post
 });