Example #1
0
        /// <summary>
        /// Process endpoint request and retrieve a Rest Response properly
        /// </summary>
        /// <param name="path">Request path</param>
        /// <param name="method">HTTP method</param>
        /// <param name="request">Rest Request</param>
        /// <returns>Rest Response</returns>
        public RestResponse Process(string path, string method, RestRequest request)
        {
            try {
                return(_restProcessor.Process(path, method, request));
            } catch (Exception ex) {
                var exceptionName = ex.InnerException switch {
                    Exception iex => iex.GetType().Name,
                    null => ex.GetType().Name
                };

                IRestExceptionHandler handler = _restProcessor.GetExceptionHandler(exceptionName);

                if (handler != null)
                {
                    return(handler.HandleException(ex.InnerException));
                }

                Logger.Error(ex.Message);

                return(new RestResponse(
                           "Internal Server Error",
                           "plain/text",
                           System.Net.HttpStatusCode.InternalServerError
                           ));
            }
        }
Example #2
0
        /// <summary>
        /// Process endpoint request and retrieve a Rest Response properly
        /// </summary>
        /// <param name="path">Request path</param>
        /// <param name="method">HTTP method</param>
        /// <param name="request">Rest Request</param>
        /// <returns>Rest Response</returns>
        public RestResponse Process(string path, string method, RestRequest request)
        {
            try {
                return(_restProcessor.Process(path, method, request));
            } catch (Exception ex) {
                var exceptionName             = ex.InnerException.GetType().Name;
                IRestExceptionHandler handler = _restProcessor.GetExceptionHandler(exceptionName);

                if (handler != null)
                {
                    return(handler.HandleException(ex.InnerException));
                }

                throw ex;
            }
        }
Example #3
0
        public void Init(Assembly runningAssembly, string modulesAssembly)
        {
            Type[] typelist = Tools.GetTypesInNamespace(runningAssembly, modulesAssembly);
            for (int i = 0; i < typelist.Length; i++)
            {
                Type tClass = typelist[i];

                // Search for REST Attribute
                Attribute t = tClass.GetCustomAttribute(typeof(REST));
                if (t != null)
                {
                    Logger.Log("RestProcessor", $"Found REST class {tClass.Name}");
                    REST trest = (REST)t;
                    proxies.Add(tClass.Name, new RestProxy(tClass, injectables));

                    MethodInfo[] methods = tClass.GetMethods();
                    foreach (var methodInfo in methods)
                    {
                        foreach (Type rt in RestTypes)
                        {
                            Attribute rta = methodInfo.GetCustomAttribute(rt);
                            if (rta != null)
                            {
                                RestCall restCall = new RestCall();
                                try {
                                    restCall.className  = tClass.Name;
                                    restCall.methodName = methodInfo.Name;
                                    restCall.method     = (IHttpMethod)rta;
                                    restCall.baseRest   = trest;

                                    Logger.Log("RestProcessor", $"Registering method {methodInfo.Name} for {restCall.method.Method} {trest.Path}{restCall.method.Path}");

                                    AddEndpoint(restCall);
                                } catch (DuplicateRestMethodException) {
                                    Logger.Log("RestProcessor", $"DuplicateRestMethodException: There is already a {restCall.method.Method} {trest.Path}{restCall.method.Path} registered.");
                                }
                            }
                        }
                    }
                }

                // Search for RestExceptionHandler Attribute
                t = tClass.GetCustomAttribute(typeof(RestExceptionHandler));
                if (t != null)
                {
                    Logger.Log("RestProcessor", $"Found a RestExceptionHandler {tClass.Name}");
                    if (typeof(IRestExceptionHandler).IsAssignableFrom(tClass))
                    {
                        RestExceptionHandler reh = (RestExceptionHandler)t;
                        if (typeof(Exception).IsAssignableFrom(reh.exceptionType))
                        {
                            IRestExceptionHandler handler = (IRestExceptionHandler)Activator.CreateInstance(tClass);
                            exceptionHandlers.Add(reh.ExceptionType.Name, handler);
                            Logger.Log("RestProcessor", $"     Registered a custom exception handler for exception \"{reh.ExceptionType.Name}\" for class {tClass.Name}");
                        }
                        else
                        {
                            Logger.Log("RestProcessor", $"     Class {tClass.Name} contains the \"RestExceptionHandler\" attribute the passed type does not inherit Exception class. Skipping it.");
                        }
                    }
                    else
                    {
                        Logger.Log("RestProcessor", $"     Class {tClass.Name} contains the \"RestExceptionHandler\" attribute but does not implement IRestExceptionHandler. Skipping it.");
                    }
                }
            }
            if (proxies.Count != 0 || endpoints.Keys.Count != 0 || exceptionHandlers.Keys.Count != 0)
            {
                Logger.Log("RestProcessor", $"Initialized {proxies.Count} REST proxies.");
                Logger.Log("RestProcessor", $"Initialized {endpoints.Keys.Count} REST endpoints.");
                Logger.Log("RestProcessor", $"Initialized {exceptionHandlers.Keys.Count} Custom Exception Handlers");
            }
        }
Example #4
0
        RestResult ProcessHttpCalls(HttpListenerRequest request)
        {
            string[]    ePath = request.Url.AbsolutePath.Split(new char[] { '/' }, 2, StringSplitOptions.RemoveEmptyEntries);
            RestRequest req   = new RestRequest(request);

            if (ePath.Length == 0)
            {
                return(new RestResult(new ErrorObject {
                    ErrorCode = ErrorCodes.NotFound,
                    Message = "No application specified",
                    ErrorField = "url"
                }.ToJSON(), MimeTypes.JSON, HttpStatusCode.NotFound));
            }
            string path   = ePath.Length > 1 ? "/" + ePath[1] : "/";
            string method = request.HttpMethod;
            string app    = ePath[0];

            if (app != "remoteSigner")
            {
                /*return new RestResult(new ErrorObject {
                 *  ErrorCode = ErrorCodes.NotFound,
                 *  Message = $"Application {app} not found",
                 *  ErrorField = "url"
                 * }.ToJSON(), MimeTypes.JSON, HttpStatusCode.NotFound);*/
                // Bypass
                path = "/" + ePath[0] + path;
            }

            Logger.Debug("HTTP Server", $"Processing HTTP Call for App {app}: {method} {path}");

            if (restProcessor.ContainsEndPoint(path, method))
            {
                try {
                    return(restProcessor.CallEndPoint(path, method, req));
                } catch (Exception e) {
                    string exceptionName          = e.InnerException.GetType().Name;
                    string baseName               = e.InnerException.GetType().BaseType.Name;
                    IRestExceptionHandler handler = restProcessor.GetExceptionHandler(exceptionName) ?? restProcessor.GetExceptionHandler(baseName);
                    if (handler != null)
                    {
                        return(handler.HandleException(e.InnerException));
                    }
                    RestResult result = new RestResult();
                    string     exceptionMessage;
                    if (e.InnerException != null)   // In the rest exceptions the real exception will be at InnerException.
                    {
                        Logger.Debug("HTTP Server", $"Exception when calling application {app} in endpoint {method} {path} \r\n {e.InnerException}");
                        exceptionMessage = e.InnerException.ToString();
                    }
                    else     // But if we got a internal exception at AppServer, it will be in the root.
                    {
                        Logger.Debug("HTTP Server", $"Exception when calling application {app} in endpoint {method} {path} \r\n {e}");
                        exceptionMessage = e.ToString();
                    }
                    result.StatusCode  = HttpStatusCode.InternalServerError;
                    result.ContentType = "text/plain";
                    result.Result      = Encoding.UTF8.GetBytes(exceptionMessage);
                    return(result);
                }
            }
            return(new RestResult(new ErrorObject {
                ErrorCode = ErrorCodes.NotFound,
                Message = "Endpoint not found",
                ErrorField = "url"
            }.ToJSON(), MimeTypes.JSON, HttpStatusCode.NotFound));
        }