コード例 #1
0
        public void TestJson2()
        {
            String tmpDict = "{\n  \"mapName\": \"name\",\n  \"list\": [\n    {\n      \"itemId\": 1,\n      \"name\": \"name\",\n      \"list\": [\n         1, 2, 3, 4  \n      ]\n    },\n    {\n      \"itemId\": 2,\n      \"name\": \"name\",\n      \"list\": [\n         1, 2, 3, 4  \n      ]\n    },\n    {\n      \"itemId\": 3,\n      \"name\": \"name\",\n      \"list\": [\n         1, 2, 3, 4  \n      ]\n    }\n  ]\n}";

            IDictionary <String, Object> dict = RequestMap.AsDictionary(tmpDict);

            Assert.IsTrue(dict.ContainsKey("mapName"));
            Assert.IsTrue(dict.ContainsKey("list"));

            Assert.AreSame(typeof(List <Dictionary <String, Object> >), dict ["list"].GetType());
        }
コード例 #2
0
        public void TestIssueWithMockResponseAsDictionary()
        {
            String responseString = "{  \n" + "   \"website\":\"hildegard.org\",\n" + "   \"address\":{  \n"
                                    + "      \"instructions\":{  \n" + "         \"doorman\":true,\n"
                                    + "         \"text\":\"some delivery instructions text\"\n" + "      },\n"
                                    + "      \"city\":\"New York\",\n" + "      \"postalCode\":\"10577\",\n" + "      \"id\":1,\n"
                                    + "      \"state\":\"NY\",\n" + "      \"line1\":\"2000 Purchase Street\"\n" + "   },\n"
                                    + "   \"phone\":\"1-770-736-8031\",\n" + "   \"name\":\"Joe Bloggs\",\n" + "   \"id\":1,\n"
                                    + "   \"email\":\"[email protected]\",\n" + "   \"username\":\"jbloggs\"\n" + "}";

            RequestMap tmpMap = new RequestMap(RequestMap.AsDictionary(responseString));

            Assert.AreEqual("hildegard.org", tmpMap ["website"]);
            Assert.AreEqual("some delivery instructions text", tmpMap ["address.instructions.text"]);
            Assert.AreEqual("true", tmpMap ["address.instructions.doorman"].ToString().ToLower());
        }
コード例 #3
0
        public virtual IDictionary <string, object> Execute(OperationConfig config, OperationMetadata metadata, BaseObject requestMap)
        {
            RestyRequest            request;
            CryptographyInterceptor interceptor;
            IRestClient             restClient;

            try {
                request     = this.GetRequest(config, metadata, requestMap);
                interceptor = request.interceptor;
                if (this.restClient != null)
                {
                    restClient         = this.restClient;
                    restClient.BaseUrl = request.BaseUrl;
                }
                else
                {
                    restClient = new RestClient(request.BaseUrl);
                }
            } catch (Exception ex) {
                throw new ApiException(ex.Message, ex);
            }
            IRestResponse restResponse;

            try {
                ApiController.log.Debug(string.Concat(new object[]
                {
                    ">>Execute(action='",
                    config.Action,
                    "', resourcePaht='",
                    config.ResourcePath,
                    "', requestMap='",
                    requestMap,
                    "'"
                }));
                ApiController.log.Debug("excute(), request.Method='" + request.Method + "'");
                ApiController.log.Debug("excute(), request.URL=" + request.AbsoluteUrl.ToString());
                ApiController.log.Debug("excute(), request.Header=");
                ApiController.log.Debug(request.Parameters.Where(x => x.Type == ParameterType.HttpHeader));
                ApiController.log.Debug("excute(), request.Body=");
                ApiController.log.Debug(request.Parameters.Where(x => x.Type == ParameterType.RequestBody));


                restClient.UseSynchronizationContext = true;
#if NET461
                System.Net.ServicePointManager.Expect100Continue       = false;
                System.Net.ServicePointManager.MaxServicePointIdleTime = 5000;
                //System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
                restResponse = restClient.Execute(request);
#elif NETSTANDARD1_6
                restResponse = AsyncHelpers.RunSync(async() => {
                    return(await restClient.ExecuteRequestAsync(request));
                },
                                                    () => {
                    this._apiConfig?.getDoEvents()?.Invoke();
                    return(Task.FromResult(0));
                });
#endif
                ApiController.log.Debug("Execute(), response.Header=");
                ApiController.log.Debug(restResponse.Headers);
                ApiController.log.Debug("Execute(), response.Body=");
                ApiController.log.Debug(restResponse.Content.ToString());
            } catch (Exception ex3) {
                Exception ex2 = new ApiCommunicationException(ex3.Message, ex3);
                ApiController.log.Error(ex2.Message, ex2);
                throw ex2;
            }
            if (restResponse.ErrorException != null || restResponse.Content == null)
            {
                Exception ex4 = new MasterCard.Core.Exceptions.SystemException(restResponse.ErrorMessage, restResponse.ErrorException);
                ApiController.log.Error(ex4.Message, ex4);
                throw ex4;
            }
            IDictionary <string, object> dictionary = null;
            if (restResponse.Content.StartsWith("{") || restResponse.Content.StartsWith("[") || restResponse.ContentType == "application/json")
            {
                try {
                    dictionary = RequestMap.AsDictionary(restResponse.Content);
                    if (interceptor != null)
                    {
                        dictionary = interceptor.Encrypt(dictionary);
                    }
                } catch (Exception) {
                    throw new MasterCard.Core.Exceptions.SystemException("Error: parsing JSON response", restResponse.Content);
                }
            }
            else if (restResponse.Content.StartsWith("<") || restResponse.ContentType == "application/xml")
            {
                try {
                    dictionary = RequestMap.AsDictionaryFromXml(restResponse.Content);
                    if (interceptor != null)
                    {
                        dictionary = interceptor.Encrypt(dictionary);
                    }
                } catch (Exception) {
                    throw new MasterCard.Core.Exceptions.SystemException("Error: parsing XML response", restResponse.Content);
                }
            }
            if (restResponse.StatusCode < HttpStatusCode.MultipleChoices)
            {
                ApiController.log.Debug("<<Execute()");
                return(dictionary);
            }
            try {
                ApiController.ThrowException(dictionary, restResponse);
            } catch (Exception ex5) {
                ApiController.log.Error(ex5.Message, ex5);
                throw ex5;
            }
            return(null);
        }
コード例 #4
0
 public IDictionary <string, object> Decrypt(IDictionary <string, object> map)
 {
     if (map.ContainsKey("token"))
     {
         IDictionary <string, object> dictionary = (IDictionary <string, object>)map["token"];
         if (dictionary.ContainsKey("") && dictionary.ContainsKey(""))
         {
             byte[] encryptionKey = CryptUtil.DecryptRSA(CryptUtil.HexDecode((string)dictionary["encryptedKey"]), this.privateKey);
             byte[] arg_8F_0      = CryptUtil.HexDecode((string)dictionary["iv"]);
             byte[] encryptedData = CryptUtil.HexDecode((string)dictionary["encryptedData"]);
             byte[] bytes         = CryptUtil.DecryptAES(arg_8F_0, encryptionKey, encryptedData);
             string @string       = Encoding.UTF8.GetString(bytes);
             foreach (string current in this.fieldsToHide)
             {
                 dictionary.Remove(current);
             }
             foreach (KeyValuePair <string, object> current2 in ((Dictionary <string, object>)RequestMap.AsDictionary(@string)))
             {
                 dictionary.Add(current2.Key, current2.Value);
             }
         }
     }
     return(map);
 }
コード例 #5
0
        /// <summary>
        /// Execute the specified action, resourcePath and baseObject.
        /// </summary>
        /// <param name="action">Action.</param>
        /// <param name="resourcePath">Resource path.</param>
        /// <param name="requestMap">Request Map.</param>
        /// <param name="headerList">Header List.</param>
        public virtual IDictionary <String, Object> execute(string action, string resourcePath, BaseObject requestMap, List <string> headerList)
        {
            IRestResponse           response;
            IRestRequest            request;
            CryptographyInterceptor interceptor;

            try
            {
                IDictionary <String, Object> paramterMap = requestMap.Clone();
                IDictionary <String, Object> headerMap   = Util.SubMap(paramterMap, headerList);

                Uri uri = getURL(action, resourcePath, paramterMap);
                interceptor = ApiConfig.GetCryptographyInterceptor(uri.AbsolutePath);
                request     = getRequest(uri, action, paramterMap, headerMap, interceptor);
            } catch (Exception e) {
                throw new MasterCard.Core.Exceptions.ApiException(e.Message, e);
            }

            try {
                log.Debug(">>execute(action='" + action + "', resourcePaht='" + resourcePath + "', requestMap='" + requestMap + "'");
                log.Debug("excute(), request.Method='" + request.Method + "'");
                log.Debug("excute(), request.QueryString=");
                log.Debug(request.Parameters.Where(x => x.Type == ParameterType.QueryString));
                log.Debug("excute(), request.Header=");
                log.Debug(request.Parameters.Where(x => x.Type == ParameterType.HttpHeader));
                log.Debug("excute(), request.Body=");
                log.Debug(request.Parameters.Where(x => x.Type == ParameterType.RequestBody));
                response = restClient.Execute(request);
                log.Debug("execute(), response.Header=");
                log.Debug(response.Headers);
                log.Debug("execute(), response.Body=");
                log.Debug(response.Content);
            } catch (Exception e) {
                Exception wrapper = new MasterCard.Core.Exceptions.ApiCommunicationException(e.Message, e);
                log.Error(wrapper.Message, wrapper);
                throw wrapper;
            }

            if (response.ErrorException == null && response.Content != null)
            {
                IDictionary <String, Object> responseObj = null;

                if (response.Content.StartsWith("{") || response.Content.StartsWith("[") || response.ContentType == "application/json")
                {
                    try {
                        responseObj = RequestMap.AsDictionary(response.Content);
                        if (interceptor != null)
                        {
                            responseObj = interceptor.Encrypt(responseObj);
                        }
                    } catch (Exception) {
                        throw new MasterCard.Core.Exceptions.SystemException("Error: parsing JSON response", response.Content);
                    }
                }

                if (response.StatusCode < HttpStatusCode.Ambiguous)
                {
                    log.Debug("<<execute()");
                    return(responseObj);
                }
                else
                {
                    try {
                        throwException(responseObj, response);
                    } catch (Exception e) {
                        log.Error(e.Message, e);
                        throw e;
                    }
                    return(null);
                }
            }
            else
            {
                Exception wrapper = new MasterCard.Core.Exceptions.SystemException(response.ErrorMessage, response.ErrorException);
                log.Error(wrapper.Message, wrapper);
                throw wrapper;
            }
        }
コード例 #6
0
        public Dictionary <String, Object> Decrypt(IDictionary <String, Object> map)
        {
            if (map.ContainsKey("token"))
            {
                // 1) extract the encryptedData from map
                IDictionary <String, Object> tokenMap = (IDictionary <String, Object>)map["token"];

                if (tokenMap.ContainsKey("") && tokenMap.ContainsKey(""))
                {
                    //need to read the key
                    String encryptedKey          = (String)tokenMap["encryptedKey"];
                    byte[] encryptedKeyByteArray = CryptUtil.HexDecode(encryptedKey);

                    //need to decryt with RSA
                    byte[] decryptedKeyByteArray = CryptUtil.DecryptRSA(encryptedKeyByteArray, this.privateKey);

                    //need to read the iv
                    String ivString    = (String)tokenMap["iv"];
                    byte[] ivByteArray = CryptUtil.HexDecode(ivString);

                    //need to decrypt the data
                    String encryptedData          = (String)tokenMap["encryptedData"];
                    byte[] encryptedDataByteArray = CryptUtil.HexDecode(encryptedData);

                    byte[] decryptedDataArray  = CryptUtil.DecryptAES(ivByteArray, decryptedKeyByteArray, encryptedDataByteArray);
                    String decryptedDataString = System.Text.Encoding.UTF8.GetString(decryptedDataArray);

                    // remove the field that are not required in the map
                    foreach (String toHide in fieldsToHide)
                    {
                        tokenMap.Remove(toHide);
                    }

                    // add the decrypted data map to the token.
                    Dictionary <String, Object> decryptedDataMap = (Dictionary <String, Object>)RequestMap.AsDictionary(decryptedDataString);
                    foreach (KeyValuePair <String, Object> pair in decryptedDataMap)
                    {
                        tokenMap.Add(pair.Key, pair.Value);
                    }
                }
            }
            return(new Dictionary <String, Object>(map));
        }