Example #1
0
        /// <summary>
        /// Fills all the attributes members of the Resource obj.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="resource"></param>
        /// <param name="response"></param>
        /// <returns></returns>
        protected static MPBase FillResourceWithResponseData <T>(T resource, MPAPIResponse response) where T : MPBase
        {
            if (response.JsonObjectResponse != null &&
                response.JsonObjectResponse is JObject)
            {
                JObject jsonObject = null;

                jsonObject = (JObject)response.JsonObjectResponse;
                T resourceObject = (T)MPCoreUtils.GetResourceFromJson <T>(resource.GetType(), jsonObject);
                resource = (T)FillResource(resourceObject, resource);
                resource._lastKnownJson = MPCoreUtils.GetJsonFromResource(resource);
            }

            return(resource);
        }
Example #2
0
        /// <summary>
        /// Calls the api and returns an MPApiResponse.
        /// </summary>
        /// <returns>A MPAPIResponse object with the results.</returns>
        public static MPAPIResponse CallAPI(
            HttpMethod httpMethod,
            string path,
            PayloadType payloadType,
            JObject payload,
            bool useCache,
            MPRequestOptions requestOptions)
        {
            string        cacheKey = httpMethod.ToString() + "_" + path;
            MPAPIResponse response = null;

            if (requestOptions == null)
            {
                requestOptions = new MPRequestOptions();
            }

            if (useCache)
            {
                response = MPCache.GetFromCache(cacheKey);

                if (response != null)
                {
                    response.IsFromCache = true;
                }
            }

            if (response == null)
            {
                response = new MPRESTClient().ExecuteRequest(
                    httpMethod,
                    path,
                    payloadType,
                    payload,
                    requestOptions);

                if (useCache)
                {
                    MPCache.AddToCache(cacheKey, response);
                }
                else
                {
                    MPCache.RemoveFromCache(cacheKey);
                }
            }

            return(response);
        }
Example #3
0
        /// <summary>
        /// Adds a response to the cache structure.
        /// </summary>
        /// <param name="key">Key representing the URL.</param>
        /// <param name="response">Response representing the response of the given URL parameter.</param>
        public static void AddToCache(string key, MPAPIResponse response)
        {
            try
            {
                var opcoesDoCache = new MemoryCacheEntryOptions()
                {
                    AbsoluteExpiration = DateTime.MaxValue,
                    Priority = CacheItemPriority.Normal
                };

                _cache.Set(key, response, opcoesDoCache);
            }
            catch (Exception ex)
            {
                throw new MPException("An error has occured in the cache structure (ADD): " + ex.Message);
            }
        }
Example #4
0
        protected static List <T> ProcessMethodBulk <T>(Type clazz, string methodName, Dictionary <string, string> mapParams, bool useCache, MPRequestOptions requestOptions) where T : MPBase
        {
            //Validates the method executed
            if (!ALLOWED_BULK_METHODS.Contains(methodName))
            {
                throw new MPException("Method \"" + methodName + "\" not allowed");
            }

            var annotatedMethod = GetAnnotatedMethod(clazz, methodName);
            var hashAnnotation  = GetRestInformation(annotatedMethod);

            if (requestOptions == null)
            {
                int retries        = (int)hashAnnotation["retries"];
                int requestTimeout = (int)hashAnnotation["requestTimeout"];
                requestOptions = new MPRequestOptions
                {
                    Retries = retries,
                    Timeout = requestTimeout
                };
            }

            T           resource    = null;
            HttpMethod  httpMethod  = (HttpMethod)hashAnnotation["method"];
            PayloadType payloadType = (PayloadType)hashAnnotation["payloadType"];
            string      path        = ParsePath(hashAnnotation["path"].ToString(), mapParams, resource, requestOptions);
            JObject     payload     = (httpMethod == HttpMethod.POST || httpMethod == HttpMethod.PUT) ? new JObject() : null;

            MPAPIResponse response = CallAPI(httpMethod, path, payloadType, payload, useCache, requestOptions);

            List <T> resourceArray = new List <T>();

            if (response.StatusCode >= 200 && response.StatusCode < 300)
            {
                resourceArray = FillArrayWithResponseData <T>(clazz, response);
            }

            return(resourceArray);
        }
Example #5
0
        protected static List <T> FillArrayWithResponseData <T>(Type clazz, MPAPIResponse response) where T : MPBase
        {
            List <T> resourceArray = new List <T>();

            if (response.JsonObjectResponse != null)
            {
                JArray jsonArray = MPCoreUtils.GetArrayFromJsonElement <T>(response.JsonObjectResponse);

                if (jsonArray != null)
                {
                    for (int i = 0; i < jsonArray.Count(); i++)
                    {
                        T resource = (T)MPCoreUtils.GetResourceFromJson <T>(clazz, (JObject)jsonArray[i]);

                        resource.DumpLog();

                        resource._lastKnownJson = MPCoreUtils.GetJsonFromResource(resource);
                        resourceArray.Add(resource);
                    }
                }
            }
            else
            {
                JArray jsonArray = MPCoreUtils.GetJArrayFromStringResponse <T>(response.StringResponse);
                if (jsonArray != null)
                {
                    for (int i = 0; i < jsonArray.Count(); i++)
                    {
                        T resource = (T)MPCoreUtils.GetResourceFromJson <T>(clazz, (JObject)jsonArray[i]);
                        resource._lastKnownJson = MPCoreUtils.GetJsonFromResource(resource);
                        resourceArray.Add(resource);
                    }
                }
            }
            return(resourceArray);
        }
Example #6
0
        /// <summary>
        /// Core implementation of processMethod. Retrieves a generic type.
        /// </summary>
        /// <typeparam name="T">Generic type that will return.</typeparam>
        /// <param name="clazz">Type of Class we are using.</param>
        /// <param name="resource">Resource we will use and return in the implementation.</param>
        /// <param name="methodName">The name of the method  we are trying to call.</param>
        /// <param name="parameters">Parameters to use in the process.</param>
        /// <param name="useCache">Cache configuration.</param>
        /// <param name="requestOptions">Object containing the request options.</param>
        /// <returns>Generic type object, containing information about retrieval process.</returns>
        protected static T ProcessMethod <T>(Type clazz, T resource, string methodName, Dictionary <string, string> parameters, bool useCache, MPRequestOptions requestOptions) where T : MPBase
        {
            if (resource == null)
            {
                try
                {
                    resource = (T)Activator.CreateInstance(clazz);
                }
                catch (Exception ex)
                {
                    throw new MPException(ex.Message);
                }
            }

            var         clazzMethod = GetAnnotatedMethod(clazz, methodName);
            var         restData    = GetRestInformation(clazzMethod);
            HttpMethod  httpMethod  = (HttpMethod)restData["method"];
            PayloadType payloadType = (PayloadType)restData["payloadType"];
            JObject     payload     = GeneratePayload(httpMethod, resource);

            if (requestOptions == null)
            {
                int requestTimeout = (int)restData["requestTimeout"];
                int retries        = (int)restData["retries"];
                requestOptions = new MPRequestOptions
                {
                    Retries = retries,
                    Timeout = requestTimeout
                };
            }

            string        path     = ParsePath(restData["path"].ToString(), parameters, resource, requestOptions);
            MPAPIResponse response = CallAPI(httpMethod, path, payloadType, payload, useCache, requestOptions);

            if (response.StatusCode >= 200 && response.StatusCode < 300)
            {
                if (httpMethod != HttpMethod.DELETE)
                {
                    resource = (T)FillResourceWithResponseData(resource, response);
                    resource._lastApiResponse = response;
                }
                else
                {
                    resource = null;
                }
            }
            else if (response.StatusCode >= 400 && response.StatusCode < 500)
            {
                BadParamsError badParamsError = MPCoreUtils.GetBadParamsError(response.StringResponse);
                resource.Errors = badParamsError;
            }
            else
            {
                MPException webserverError = new MPException()
                {
                    StatusCode   = response.StatusCode,
                    ErrorMessage = response.StringResponse
                };
                webserverError.Cause.Add(response.JsonObjectResponse.ToString());
                throw webserverError;
            }

            return(resource);
        }