protected bool APIAccepted(ESBContext context)
        {
            if (context.Path.StartsWith("/", StringComparison.CurrentCulture))
            {
                context.Path = context.Path.Remove(0, 1);
            }

            if (context.Path.EndsWith("/", StringComparison.CurrentCulture))
            {
                context.Path = context.Path.Remove((context.Path.Length - 1), 1);
            }

            var paths = context.Path.Split(new char[] { '/' });

            if (paths.Length <= 2)
            {
                return(false);
            }

            string apiName = paths[0];
            string version = paths[1];

            var apiInfo = ESBFactory.Instance.APIStore.Get(apiName, version);

            if (apiInfo == null || apiInfo.Count == 0)
            {
                return(false);
            }

            return(FindAPI(context, paths, apiInfo));
        }
Exemple #2
0
        public async Task <bool> Process(HttpContext context, ResponseHandle resp)
        {
            ESBContext esbContext = new ESBContext();

            var headers = context.Request.Headers.GetEnumerator();

            esbContext.Headers = new Dictionary <string, string>();

            if (context.Request.Headers != null)
            {
                while (headers.MoveNext())
                {
                    esbContext.Headers.Add(headers.Current.Key, headers.Current.Value);
                }
            }

            await ReadBody(context, esbContext);

            esbContext.Host = context.Request.Host.Value;

            ExtractIP(context, esbContext);

            esbContext.Method      = context.Request.Method;
            esbContext.Path        = context.Request.Path;
            esbContext.QueryString = context.Request.QueryString.Value;
            esbContext.Url         = string.Format("{0}://{1}{2}{3}", context.Request.Scheme,
                                                   context.Request.Host, context.Request.Path,
                                                   context.Request.QueryString);

            return(await process.Process(esbContext, resp));
        }
        private bool MiddlesAccepted(ESBContext context, ResponseHandle responseHandle)
        {
            IMiddleHandle[] middles = ESBFactory.Instance.Middles;

            string msg  = null;
            int    code = 400;

            foreach (IMiddleHandle handle in middles)
            {
                if (!handle.CanHandle(context, out msg, out code))
                {
                    string json = ESBUtil.ParseJson(new
                    {
                        MiddleName = handle.GetType().FullName,
                        Message    = "O middle rejeitou a solicitação",
                        Url        = context.Url,
                        Detail     = msg
                    });

                    responseHandle.Write(ESBUtil.CreateBytes(json), code);
                    return(false);
                }
            }

            return(true);
        }
Exemple #4
0
        public async Task Process(ESBContext context,
                                  Inbound.ResponseHandle responseHandle)
        {
            InvokeInterceptor(context);

            await responseHandle.Write(context.ResponseBody,
                                       context.StatusCode, context.ResponseHeaders);
        }
Exemple #5
0
 public async Task Dispatch(ESBContext context,
                            ResponseHandle responseHandle,
                            DispatchType dispatchType)
 {
     if (commands.TryGetValue(dispatchType, out IDispachCommand command))
     {
         await command.Dispatch(context, responseHandle);
     }
 }
        private void InvokeInterceptor(ESBContext context)
        {
            IMiddleHandle[] middles = ESBFactory.Instance.Middles;

            foreach (IMiddleHandle handle in middles)
            {
                handle.RequestInterceptor(context);
            }
        }
Exemple #7
0
        public Uri CreateUri(ESBContext context)
        {
            UriBuilder builder = new UriBuilder(Uri)
            {
                Path  = context.Attributes(ESBContants.URL_PATH_OUT_KEY),
                Query = context.QueryString
            };

            return(builder.Uri);
        }
        private string GetAccept(ESBContext context)
        {
            string header = null;

            context.Headers.TryGetValue("Accept", out header);

            if (string.IsNullOrEmpty(header))
            {
                header = GetConteType(context, "*/*");;
            }

            return(header);
        }
        private bool FindAPI(ESBContext context, string[] paths,
                             List <APIInfo> apiInfo)
        {
            paths = RemoveAppInfo(paths);

            foreach (APIInfo api in apiInfo)
            {
                if (api.Validate(context, paths))
                {
                    context.ApiInfo = api;
                    return(true);
                }
            }

            return(false);
        }
        public async Task <bool> Process(ESBContext context, ResponseHandle responseHandle)
        {
            if (!APIAccepted(context))
            {
                return(false);
            }

            if (!MiddlesAccepted(context, responseHandle))
            {
                throw new ESBException("Request not valid", 501);
            }

            InvokeInterceptor(context);

            await gateway.Dispatch(context, responseHandle, DispatchType.REST);

            return(true);
        }
        private string GetConteType(ESBContext context, string other = null)
        {
            string contentType = null;

            context.Headers.TryGetValue("Content-Type", out contentType);
            if (string.IsNullOrEmpty(contentType))
            {
                if (string.IsNullOrEmpty(other))
                {
                    contentType = "application/json";
                }
                else
                {
                    contentType = other;
                }
            }


            return(contentType);
        }
Exemple #12
0
        private static void ExtractIP(HttpContext context, ESBContext esbContext)
        {
            string ip;

            if (!esbContext.Headers.TryGetValue("HTTP_X_FORWARDED_FOR", out ip))
            {
                if (!esbContext.Headers.TryGetValue("REMOTE_ADDR", out ip))
                {
                    if (!esbContext.Headers.TryGetValue("HTTP_X_FORWARDED_FOR", out ip))
                    {
                        if (!esbContext.Headers.TryGetValue("X_FORWARDED_FOR", out ip))
                        {
                            ip = context.Connection.RemoteIpAddress.ToString();
                        }
                    }
                }
            }


            esbContext.IP = ip;
        }
Exemple #13
0
        public bool Validate(ESBContext context, string[] paths)
        {
            if (PathList.Length != paths.Length)
            {
                return(false);
            }

            StringBuilder sb = new StringBuilder();

            if (!context.Method.Equals(Method))
            {
                return(false);
            }

            for (int i = 0; i < PathList.Length; i++)
            {
                string pReq    = paths[i];
                string pSource = PathList[i];

                if (pSource.StartsWith("{", StringComparison.CurrentCulture) &&
                    pSource.EndsWith("}", StringComparison.CurrentCulture))
                {
                    sb.Append("/").Append(pReq);

                    continue;
                }

                if (!pReq.Equals(pSource))
                {
                    return(false);
                }

                sb.Append("/").Append(pReq);
            }

            context.Attributes(ESBContants.URL_PATH_OUT_KEY, sb.ToString());


            return(true);
        }
Exemple #14
0
        private static async Task ReadBody(HttpContext context, ESBContext esbContext)
        {
            if (context.Request.ContentLength.HasValue &&
                context.Request.Body.CanRead)
            {
                var bufferSize = context.Request.ContentLength.HasValue ?
                                 context.Request.ContentLength.Value :
                                 1024 * 4;

                byte[] bytes = new byte[bufferSize];

                var count = await context.Request.Body.ReadAsync(bytes, 0, bytes.Length);

                if (count != bytes.Length)
                {
                    var arrayCopy = new byte[count];
                    Array.Copy(bytes, arrayCopy, count);
                }

                esbContext.Body = bytes;
            }
        }
        public async Task Dispatch(ESBContext context,
                                   Inbound.ResponseHandle responseHandle)
        {
            try
            {
                //using (HttpClientHandler handler = new HttpClientHandler())
                //{
                //handler.ServerCertificateCustomValidationCallback = delegate {

                //	return true;
                //};

                //using (HttpClient client = new HttpClient(handler))
                using (HttpClient client = new HttpClient())
                {
                    HttpContent content = null;
                    if (context.Body != null && context.Body.Length > 0)
                    {
                        content =
                            new ByteArrayContent(context.Body);

                        content.Headers.ContentType =
                            new MediaTypeHeaderValue(GetConteType(context));
                    }

                    HttpRequestMessage msg = new HttpRequestMessage()
                    {
                        Content = content
                    };

                    msg.Headers.Add("User-Agent", ESBContants.HEADER_USER_AGENTE);
                    msg.Headers.Add("X-Forwarded-For", context.IP);
                    msg.Headers.Add("Accept", GetAccept(context));
                    msg.Method     = new HttpMethod(context.Method);
                    msg.RequestUri = CreateUri(context);
                    var resp = await client.SendAsync(msg);

                    Dictionary <string, string> headersMap = new Dictionary <string, string>();

                    var headers = resp.Headers.GetEnumerator();
                    while (headers.MoveNext())
                    {
                        headersMap.Add(headers.Current.Key,
                                       string.Join(",", headers.Current.Value));
                    }

                    string contentType = resp.Content != null &&
                                         resp.Content.Headers != null
                                             ? resp.Content.Headers.ContentType.ToString() : null;

                    byte[] bytes;

                    using (var strem = await resp.Content.ReadAsStreamAsync())
                    {
                        bytes = new byte[strem.Length];

                        await strem.ReadAsync(bytes, 0, bytes.Length);
                    }

                    if (!string.IsNullOrEmpty(contentType))
                    {
                        headersMap.Add("Content-Type", contentType);
                    }

                    context.ResponseBody    = bytes;
                    context.StatusCode      = (int)resp.StatusCode;
                    context.ResponseHeaders = headersMap;

                    await ESBFactory
                    .Instance
                    .OutboundProcess
                    .Process(context, responseHandle);
                }
                //}
            }
            catch (Exception e)
            {
                var json = ESBUtil.ParseJson(new
                {
                    Message = "Não foi possível enviar a solicitação para a origem",
                    Url     = context.Url,
                    Detail  = e.Message,
                    Trace   = e.StackTrace
                });

                await responseHandle.Write(ESBUtil.CreateBytes(json), 501);
            }
        }
 private Uri CreateUri(ESBContext context)
 {
     return(context.ApiInfo.CreateUri(context));
 }