示例#1
0
        public void ParseMapJsonData(List <MapDownloadResource> maps, Dictionary <String, String> mapsItemsCodes, Dictionary <String, String> regionItemsCodes, InputStream inputStream)
        {
            Console.WriteLine("Catalin ; start parsing !!!");
            long       startTime    = DemoUtils.CurrentTimeMillis();
            JSONObject reader       = new JSONObject(convertJSONFileContentToAString(inputStream));
            JSONArray  regionsArray = reader.GetJSONArray(REGIONS_ID);

            if (regionsArray != null)
            {
                readUSRegionsHierarchy(regionItemsCodes, regionsArray);
            }
            JSONArray packagesArray = reader.GetJSONArray(PACKAGES_ID);

            if (packagesArray != null)
            {
                readMapsPackages(maps, packagesArray);
            }
            JSONObject worldObject = reader.GetJSONObject(WORLD_ID);

            if (worldObject != null)
            {
                JSONArray continentsArray = worldObject.GetJSONArray(CONTINENTS_ID);
                if (continentsArray != null)
                {
                    readWorldHierarchy(mapsItemsCodes, continentsArray);
                }
            }

            /*-for (Map.Entry<String, String> currentEntry : mapsItemsCodes.entrySet()) {
             *  System.out.println("Catalin ; key = " + currentEntry.getKey() + " ; value = " + currentEntry.getValue());
             * }*/
            Console.WriteLine("Catalin ; total loading time = " + (DemoUtils.CurrentTimeMillis() - startTime) + " ; maps size = " + maps.Count);
        }
示例#2
0
 private void readCountriesHierarchy(Dictionary <String, String> mapsItemsCodes, string currentContinentCode, JSONArray countriesArray)
 {
     for (int i = 0; i < countriesArray.Length(); i++)
     {
         try
         {
             JSONObject currentCountryObject = countriesArray.GetJSONObject(i);
             if (currentCountryObject != null)
             {
                 try
                 {
                     String currentCountryCode = currentCountryObject.GetString(COUNTRY_CODE_ID);
                     if ((currentContinentCode != null) && (currentCountryCode != null))
                     {
                         mapsItemsCodes.Add(currentCountryCode, currentContinentCode);
                         try
                         {
                             JSONArray citiesArray = currentCountryObject.GetJSONArray(CITY_CODES_ID);
                             if (citiesArray != null)
                             {
                                 readCitiesHierarchy(mapsItemsCodes, currentCountryCode, citiesArray);
                             }
                         }
                         catch (JSONException ex)
                         {
                             SKLogging.WriteLog(TAG, ex.Message, SKLogging.LogDebug);
                         }
                         try
                         {
                             JSONArray statesArray = currentCountryObject.GetJSONArray(STATE_CODES_ID);
                             if (statesArray != null)
                             {
                                 readStatesHierarchy(mapsItemsCodes, currentCountryCode, statesArray);
                             }
                         }
                         catch (JSONException ex)
                         {
                             SKLogging.WriteLog(TAG, ex.Message, SKLogging.LogDebug);
                         }
                     }
                 }
                 catch (JSONException ex)
                 {
                     SKLogging.WriteLog(TAG, ex.Message, SKLogging.LogDebug);
                 }
             }
         }
         catch (JSONException ex)
         {
             SKLogging.WriteLog(TAG, ex.Message, SKLogging.LogDebug);
         }
     }
 }
示例#3
0
        /// <exception cref="Org.Codehaus.Jettison.Json.JSONException"/>
        public virtual void VerifyHsJobTaskAttemptCounters(JSONObject info, TaskAttempt att
                                                           )
        {
            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 2, info.Length());
            WebServicesTestUtils.CheckStringMatch("id", MRApps.ToString(att.GetID()), info.GetString
                                                      ("id"));
            // just do simple verification of fields - not data is correct
            // in the fields
            JSONArray counterGroups = info.GetJSONArray("taskAttemptCounterGroup");

            for (int i = 0; i < counterGroups.Length(); i++)
            {
                JSONObject counterGroup = counterGroups.GetJSONObject(i);
                string     name         = counterGroup.GetString("counterGroupName");
                NUnit.Framework.Assert.IsTrue("name not set", (name != null && !name.IsEmpty()));
                JSONArray counters = counterGroup.GetJSONArray("counter");
                for (int j = 0; j < counters.Length(); j++)
                {
                    JSONObject counter     = counters.GetJSONObject(j);
                    string     counterName = counter.GetString("name");
                    NUnit.Framework.Assert.IsTrue("name not set", (counterName != null && !counterName
                                                                   .IsEmpty()));
                    long value = counter.GetLong("value");
                    NUnit.Framework.Assert.IsTrue("value  >= 0", value >= 0);
                }
            }
        }
示例#4
0
        /// <exception cref="Org.Codehaus.Jettison.Json.JSONException"/>
        public virtual void VerifyHsTaskAttempts(JSONObject json, Task task)
        {
            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, json.Length());
            JSONObject attempts = json.GetJSONObject("taskAttempts");

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, json.Length());
            JSONArray arr = attempts.GetJSONArray("taskAttempt");

            foreach (TaskAttempt att in task.GetAttempts().Values)
            {
                TaskAttemptId id    = att.GetID();
                string        attid = MRApps.ToString(id);
                bool          found = false;
                for (int i = 0; i < arr.Length(); i++)
                {
                    JSONObject info = arr.GetJSONObject(i);
                    if (attid.Matches(info.GetString("id")))
                    {
                        found = true;
                        VerifyHsTaskAttempt(info, att, task.GetType());
                    }
                }
                NUnit.Framework.Assert.IsTrue("task attempt with id: " + attid + " not in web service output"
                                              , found);
            }
        }
示例#5
0
        private async void OpenDiseaseList(object sender, EventArgs e)
        {
            _progressBarDialog.Show();
            await Task.Run(async() => {
                try {
                    //Utils.GetDefaults("QrId")
                    // string response = await WebServices.WebServices.Get($"{Constants.PublicServerAddress}/api/getUserBenefits/{Utils.GetDefaults("Id")}", Utils.GetDefaults("Token"));
                    string response = await WebServices.WebServices.Get($"{Constants.PublicServerAddress}/api/getAllBenefits/", Utils.GetDefaults("Token"));
                    Log.Error("Debug Log in " + nameof(AsistentForm), "Response: " + response);
                    var jsonResponse = new JSONObject(response);
                    Log.Error("ASISTEN FORM BENEFITS", jsonResponse.ToString());
                    if (jsonResponse.GetInt("status") == 2)
                    {
                        JSONArray dataArray = jsonResponse.GetJSONArray("data");
                        var items           = new List <SearchListModel>();
                        for (var i = 0; i < dataArray.Length(); i++)
                        {
                            items.Add(new SearchListModel {
                                Id    = dataArray.GetJSONObject(i).GetInt("id"),
                                Title = dataArray.GetJSONObject(i).GetString("benefit")
                            });
                        }

                        var intent = new Intent(Activity, typeof(SearchListActivity));
                        intent.PutExtra("Items", JsonConvert.SerializeObject(items));
                        intent.PutExtra("SelectedItems", JsonConvert.SerializeObject(_selectedBenefits));
                        StartActivityForResult(intent, 1);
                    }
                } catch (Exception ex) {
                    Log.Error("error la beneficii", ex.Message);
                }
            });

            _progressBarDialog.Dismiss();
        }
        /// <exception cref="Org.Codehaus.Jettison.Json.JSONException"/>
        /// <exception cref="System.Exception"/>
        public virtual void TestNodeHelper(string path, string media)
        {
            WebResource r = Resource();

            Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application
                app = new MockApp(1);
            nmContext.GetApplications()[app.GetAppId()] = app;
            AddAppContainers(app);
            Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application
                app2 = new MockApp(2);
            nmContext.GetApplications()[app2.GetAppId()] = app2;
            AddAppContainers(app2);
            ClientResponse response = r.Path("ws").Path("v1").Path("node").Path(path).Accept(
                media).Get <ClientResponse>();

            NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType()
                                            );
            JSONObject json = response.GetEntity <JSONObject>();
            JSONObject info = json.GetJSONObject("containers");

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, info.Length());
            JSONArray conInfo = info.GetJSONArray("container");

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 4, conInfo.Length
                                                ());
            for (int i = 0; i < conInfo.Length(); i++)
            {
                VerifyNodeContainerInfo(conInfo.GetJSONObject(i), nmContext.GetContainers()[ConverterUtils
                                                                                            .ToContainerId(conInfo.GetJSONObject(i).GetString("id"))]);
            }
        }
示例#7
0
        private void ParseJson(JSONObject json)
        {
            try
            {
                List <RecipeShort> result = new List <RecipeShort>();

                JSONArray temp = json.GetJSONArray(Constants.RecipeFieldList);

                if (temp == null)
                {
                    return;
                }

                for (int i = 0; i < temp.Length(); i++)
                {
                    JSONObject  item   = temp.GetJSONObject(i);
                    RecipeShort parsed = new RecipeShort(item, context);
                    items.Add(parsed);
                }

                return;
            }
            catch (Exception)
            {
                //Log.Error (Tag, "Failed to parse recipe list: " + ex);
                return;
            }
        }
示例#8
0
        private void Test(JSONObject obj)
        {
            Debug.WriteLine(obj.GetString("result"));
            JSONArray array = obj.GetJSONArray("result");

            foreach (JSONObject item in array)
            {
                switch (item.GetString("poll_type"))
                {
                case "message":

                    break;

                case "group_message":
                    break;

                default:
                    break;
                }
                Debug.WriteLine(item.GetString("poll_type"));
                JSONObject nobj = item.GetJSONObject("value");

                Debug.WriteLine(nobj.GetString("msg_id2"));

                Debug.WriteLine(nobj.GetString("to_uin"));
            }
        }
示例#9
0
        public virtual void TestJobsQueryState()
        {
            WebResource r = Resource();
            // we only create 3 jobs and it cycles through states so we should have 3 unique states
            IDictionary <JobId, Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job> jobsMap = appContext
                                                                                      .GetAllJobs();
            string queryState = "BOGUS";
            JobId  jid        = null;

            foreach (KeyValuePair <JobId, Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job> entry in
                     jobsMap)
            {
                jid        = entry.Value.GetID();
                queryState = entry.Value.GetState().ToString();
                break;
            }
            ClientResponse response = r.Path("ws").Path("v1").Path("history").Path("mapreduce"
                                                                                   ).Path("jobs").QueryParam("state", queryState).Accept(MediaType.ApplicationJson)
                                      .Get <ClientResponse>();

            NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType()
                                            );
            JSONObject json = response.GetEntity <JSONObject>();

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, json.Length());
            JSONObject jobs = json.GetJSONObject("jobs");
            JSONArray  arr  = jobs.GetJSONArray("job");

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, arr.Length());
            JSONObject info = arr.GetJSONObject(0);

            Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job job = appContext.GetPartialJob(jid);
            VerifyJobsUtils.VerifyHsJobPartial(info, job);
        }
示例#10
0
        /// <summary>
        /// 虚拟 DataTable内容
        /// </summary>
        /// <returns></returns>
        public static DataTable CreatTable()
        {
            string json = "{\"total\":8,\"rows\":[{\"VehicleID\":\"粤BY818T\",\"Mileage\":0},{\"VehicleID\":\"粤B594L0\",\"Mileage\":0},{\"VehicleID\":\"粤B8C97M\",\"Mileage\":52718.32},{\"VehicleID\":\"粤B2K52P\",\"Mileage\":109411},{\"VehicleID\":\"粤BKB951\",\"Mileage\":43296.82},{\"VehicleID\":\"粤BW83B7\",\"Mileage\":8711.193},{\"VehicleID\":\"粤BK716T\",\"Mileage\":72072.73},{\"VehicleID\":\"粤B2W6G9\",\"Mileage\":167095.3}]}";

            JSONObject obj  = new JSONObject(json);
            int        num  = obj.GetInt("total");
            JSONArray  jArr = obj.GetJSONArray("rows");



            //创建DataTable 将数据库中没有的数据放到这个DT中
            DataTable datatable = new DataTable();

            datatable.Columns.Add("车辆名称", typeof(string));
            datatable.Columns.Add("行驶里程", typeof(string));
            datatable.Columns.Add("时间区间", typeof(string));
            //创建DatatTable 结束---------------------------

            //开始给临时datatable赋值
            for (int i = 0; i < 7; i++)
            {
                JSONObject obj2 = jArr.GetJSONObject(i);
                DataRow    row  = datatable.NewRow();
                row["车辆名称"] = obj2.GetString("VehicleID");
                //row["行驶里程"] = obj2.GetString("Mileage");
                //row["时间区间"] = "哈哈哈  ";
                datatable.Rows.Add(row);
            }
            return(datatable);
        }
        public virtual void TestNodeAppsState()
        {
            WebResource r = Resource();

            Org.Apache.Hadoop.Yarn.Server.Nodemanager.Containermanager.Application.Application
                app = new MockApp(1);
            nmContext.GetApplications()[app.GetAppId()] = app;
            AddAppContainers(app);
            MockApp app2 = new MockApp("foo", 1234, 2);

            nmContext.GetApplications()[app2.GetAppId()] = app2;
            Dictionary <string, string> hash2 = AddAppContainers(app2);

            app2.SetState(ApplicationState.Running);
            ClientResponse response = r.Path("ws").Path("v1").Path("node").Path("apps").QueryParam
                                          ("state", ApplicationState.Running.ToString()).Accept(MediaType.ApplicationJson)
                                      .Get <ClientResponse>();

            NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType()
                                            );
            JSONObject json = response.GetEntity <JSONObject>();
            JSONObject info = json.GetJSONObject("apps");

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, info.Length());
            JSONArray appInfo = info.GetJSONArray("app");

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, appInfo.Length
                                                ());
            VerifyNodeAppInfo(appInfo.GetJSONObject(0), app2, hash2);
        }
示例#12
0
        public virtual void TestJobsQueryFinishTimeBeginEnd()
        {
            WebResource r = Resource();
            IDictionary <JobId, Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job> jobsMap = appContext
                                                                                      .GetAllJobs();
            int size = jobsMap.Count;
            // figure out the mid end time - we expect atleast 3 jobs
            AList <long> finishTime = new AList <long>(size);

            foreach (KeyValuePair <JobId, Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job> entry in
                     jobsMap)
            {
                finishTime.AddItem(entry.Value.GetReport().GetFinishTime());
            }
            finishTime.Sort();
            NUnit.Framework.Assert.IsTrue("Error we must have atleast 3 jobs", size >= 3);
            long           midFinishTime = finishTime[size - 2];
            ClientResponse response      = r.Path("ws").Path("v1").Path("history").Path("mapreduce"
                                                                                        ).Path("jobs").QueryParam("finishedTimeBegin", 40000.ToString()).QueryParam("finishedTimeEnd"
                                                                                                                                                                    , midFinishTime.ToString()).Accept(MediaType.ApplicationJson).Get <ClientResponse
                                                                                                                                                                                                                                       >();

            NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType()
                                            );
            JSONObject json = response.GetEntity <JSONObject>();

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, json.Length());
            JSONObject jobs = json.GetJSONObject("jobs");
            JSONArray  arr  = jobs.GetJSONArray("job");

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", size - 1, arr.Length
                                                ());
        }
示例#13
0
        private IList <Meal> parseResponseToJSONArray(string response)
        {
            IList <Meal> list = new List <Meal>();

            JSONObject jsonObjectRoot = new JSONObject(response);

            JSONArray jsonArrayDania = jsonObjectRoot.GetJSONArray("dania");

            for (int i = 0; i < jsonArrayDania.Length(); i++)
            {
                JSONObject tempMealjsonObj = jsonArrayDania.GetJSONObject(i);
                Meal       tempMeal        = new Meal(
                    tempMealjsonObj.GetString("da_nazwa"),
                    tempMealjsonObj.GetString("kcal"),
                    tempMealjsonObj.GetString("cena"),
                    tempMealjsonObj.GetString("waga"),
                    tempMealjsonObj.GetString("da_foto"));

                Debug.WriteLine(String.Join(TAG, "  TempMeaL: {", tempMeal.ToString(), "}"));

                list.Add(tempMeal);
            }

            return(list);
        }
        public virtual void TestNodesQueryNew()
        {
            WebResource r   = Resource();
            MockNM      nm1 = rm.RegisterNode("h1:1234", 5120);
            MockNM      nm2 = rm.RegisterNode("h2:1235", 5121);

            rm.SendNodeStarted(nm1);
            rm.NMwaitForState(nm1.GetNodeId(), NodeState.Running);
            rm.NMwaitForState(nm2.GetNodeId(), NodeState.New);
            ClientResponse response = r.Path("ws").Path("v1").Path("cluster").Path("nodes").QueryParam
                                          ("states", NodeState.New.ToString()).Accept(MediaType.ApplicationJson).Get <ClientResponse
                                                                                                                      >();

            NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType()
                                            );
            JSONObject json = response.GetEntity <JSONObject>();

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, json.Length());
            JSONObject nodes = json.GetJSONObject("nodes");

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, nodes.Length()
                                            );
            JSONArray nodeArray = nodes.GetJSONArray("node");

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, nodeArray.Length
                                                ());
            JSONObject info = nodeArray.GetJSONObject(0);

            VerifyNodeInfo(info, nm2);
        }
示例#15
0
 private void readUSRegionsHierarchy(Dictionary <String, String> regionItemsCodes, JSONArray regionsArray)
 {
     for (int i = 0; i < regionsArray.Length(); i++)
     {
         JSONObject currentRegionObject = regionsArray.GetJSONObject(i);
         if (currentRegionObject != null)
         {
             String currentRegionCode = currentRegionObject.GetString(REGION_CODE_ID);
             if (currentRegionCode != null)
             {
                 JSONArray subRegions = currentRegionObject.GetJSONArray(SUB_REGIONS_ID);
                 if (subRegions != null)
                 {
                     for (int j = 0; j < subRegions.Length(); j++)
                     {
                         JSONObject currentSubRegionObject = subRegions.GetJSONObject(j);
                         if (currentSubRegionObject != null)
                         {
                             String subRegionCode = currentSubRegionObject.GetString(SUB_REGION_CODE_ID);
                             if (subRegionCode != null)
                             {
                                 regionItemsCodes.Add(subRegionCode, currentRegionCode);
                             }
                         }
                     }
                 }
             }
         }
     }
 }
示例#16
0
        public virtual void TestMultipleContainers()
        {
            ApplicationId        appId        = ApplicationId.NewInstance(0, 1);
            ApplicationAttemptId appAttemptId = ApplicationAttemptId.NewInstance(appId, 1);
            WebResource          r            = Resource();
            ClientResponse       response     = r.Path("ws").Path("v1").Path("applicationhistory").Path
                                                    ("apps").Path(appId.ToString()).Path("appattempts").Path(appAttemptId.ToString()
                                                                                                             ).Path("containers").QueryParam("user.name", Users[round]).Accept(MediaType.ApplicationJson
                                                                                                                                                                               ).Get <ClientResponse>();

            if (round == 1)
            {
                NUnit.Framework.Assert.AreEqual(ClientResponse.Status.Forbidden, response.GetClientResponseStatus
                                                    ());
                return;
            }
            NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType()
                                            );
            JSONObject json = response.GetEntity <JSONObject>();

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, json.Length());
            JSONObject containers = json.GetJSONObject("containers");

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, containers.Length
                                                ());
            JSONArray array = containers.GetJSONArray("container");

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 5, array.Length()
                                            );
        }
        private static double[][] computeVectors(String jsonStr)
        {
            HashSet <String> set = new HashSet <string>();

            set.Add("ShoulderLeft");
            set.Add("ElbowLeft");
            set.Add("WristLeft");
            set.Add("ShoulderRight");
            set.Add("ElbowRight");
            set.Add("WristRight");

            Dictionary <String, double[]> jointMap = new Dictionary <string, double[]>();

            JSONArray array = new JSONArray(jsonStr);

            for (int i = 0; i < array.Length(); i++)
            {
                JSONObject obj  = array.GetJSONObject(i);
                String     type = obj.GetString("JointType");
                if (set.Contains(type))
                {
                    JSONArray pos = obj.GetJSONArray("Position");
                    jointMap[type] = new double[] { double.Parse(pos.GetString(0)), double.Parse(pos.GetString(1)), double.Parse(pos.GetString(2)) };
                }
            }

            return(new double[][] { computeVector(jointMap["ShoulderLeft"], jointMap["ElbowLeft"]),
                                    computeVector(jointMap["ElbowLeft"], jointMap["WristLeft"]),
                                    computeVector(jointMap["ShoulderRight"], jointMap["ElbowRight"]),
                                    computeVector(jointMap["ElbowRight"], jointMap["WristRight"]) });
        }
        public async void FindRouteAsync(string source, string destrination) // radi sa primerom https://maps.googleapis.com/maps/api/directions/json?origin=Brooklyn&destination=Queens&mode=transit&key=AIzaSyDY8RF7Oa9h5IeD7DX6l_GtGPnjT6J7k4U
        {
            client = new HttpClient();
            // string default_for_every_query = "https://maps.googleapis.com/maps/api/directions/json?";

            HttpResponseMessage response = await client.GetAsync("https://maps.googleapis.com/maps/api/directions/json?origin=" + source + "&destination=" + destrination + "&mode=transit&key=AIzaSyDY8RF7Oa9h5IeD7DX6l_GtGPnjT6J7k4U");

            if (response.StatusCode == HttpStatusCode.OK)
            {
                HttpContent content = response.Content;
                var         json    = await content.ReadAsStringAsync();

                Console.WriteLine(json.ToString());

                JSONObject    jsonresoult       = new JSONObject(json);
                JSONArray     routesArray       = jsonresoult.GetJSONArray("routes");
                JSONObject    routes            = routesArray.GetJSONObject(0);
                JSONObject    overviewPolylines = routes.GetJSONObject("overview_polyline");
                String        encodedString     = overviewPolylines.GetString("points");
                List <LatLng> list = decodePoly(encodedString);

                PolylineOptions po = new PolylineOptions();
                //treba i < list.Count zasto puca sa tim?

                for (int i = 0; i < list.Count; i++)
                {
                    po.Add(list[i]).InvokeWidth(10).InvokeColor(0x66FF0000);//red color
                }

                gmap.AddPolyline(po);
            }
        }
示例#19
0
        List <Item> ParseJson(JSONObject json)
        {
            List <Item> result = new List <Item> ();

            try
            {
                JSONArray items = json.GetJSONArray(Constants.RecipeFieldList);
                for (int i = 0; i < items.Length(); i++)
                {
                    JSONObject item   = items.GetJSONObject(i);
                    Item       parsed = new Item();
                    parsed.Name  = item.GetString(Constants.RecipeFieldName);
                    parsed.Title = item.GetString(Constants.RecipeFieldTitle);
                    if (item.Has(Constants.RecipeFieldImage))
                    {
                        String imageFile = item.GetString(Constants.RecipeFieldImage);
                        parsed.Image = AssetUtils.LoadBitmapAsset(context, imageFile);
                    }
                    parsed.Summary = item.GetString(Constants.RecipeFieldSummary);
                    result.Add(parsed);
                }
            } catch (Exception ex) {
                Log.Error(Tag, "Failed to parse recipe list: " + ex);
            }
            return(result);
        }
        private PersonView parseResultFromUrl(string res)
        {
            if (res != null)
            {
                var result = new JSONObject(res);

                string name      = result.GetString("nume");
                string email     = result.GetString("email");
                string birthdate = result.GetString("dataNastere");
                string gender    = result.GetString("sex");
                string avatar    = Utils.GetDefaults("Avatar");
                var    list      = new List <PersonalDisease>();

                JSONArray jsonList = result.GetJSONArray("afectiuni");
                for (var i = 0; i < jsonList.Length(); i++)
                {
                    var    jsonObj     = (JSONObject)jsonList.Get(i);
                    int    cod         = jsonObj.GetInt("id");
                    string nameDisease = jsonObj.GetString("denumire");

                    list.Add(new PersonalDisease(cod, nameDisease));
                }
                var obj = new PersonView(name, email, birthdate, gender, avatar, list, "none");
                return(obj);
            }
            return(null);
        }
        public virtual void TestQueryAll()
        {
            WebResource r   = Resource();
            MockNM      nm1 = rm.RegisterNode("h1:1234", 5120);
            MockNM      nm2 = rm.RegisterNode("h2:1235", 5121);
            MockNM      nm3 = rm.RegisterNode("h3:1236", 5122);

            rm.SendNodeStarted(nm1);
            rm.SendNodeStarted(nm3);
            rm.NMwaitForState(nm1.GetNodeId(), NodeState.Running);
            rm.NMwaitForState(nm2.GetNodeId(), NodeState.New);
            rm.SendNodeLost(nm3);
            ClientResponse response = r.Path("ws").Path("v1").Path("cluster").Path("nodes").QueryParam
                                          ("states", Joiner.On(',').Join(EnumSet.AllOf <NodeState>())).Accept(MediaType.ApplicationJson
                                                                                                              ).Get <ClientResponse>();

            NUnit.Framework.Assert.AreEqual(MediaType.ApplicationJsonType, response.GetType()
                                            );
            JSONObject json  = response.GetEntity <JSONObject>();
            JSONObject nodes = json.GetJSONObject("nodes");

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 1, nodes.Length()
                                            );
            JSONArray nodeArray = nodes.GetJSONArray("node");

            NUnit.Framework.Assert.AreEqual("incorrect number of elements", 3, nodeArray.Length
                                                ());
        }
示例#22
0
        // >> autocomplete-remote-do-in-background-xamarin
        protected override Java.Lang.Void RunInBackground(params string[] @params)
        {
            HttpURLConnection urlConnection = null;

            try
            {
                URL url = new URL
                              ("http://www.telerik.com/docs/default-source/ui-for-ios/airports.json?sfvrsn=2");

                urlConnection = (HttpURLConnection)url.OpenConnection();

                urlConnection.RequestMethod        = "GET";
                urlConnection.UseCaches            = false;
                urlConnection.AllowUserInteraction = false;
                urlConnection.Connect();
                HttpStatus status = urlConnection.ResponseCode;

                if (status.Equals(HttpStatus.Ok))
                {
                    BufferedReader reader = new BufferedReader
                                                (new InputStreamReader(urlConnection.InputStream));
                    char[] buffer = new char[1024];
                    int    n;
                    Writer writer = new Java.IO.StringWriter();

                    while ((n = reader.Read(buffer)) != -1)
                    {
                        writer.Write(buffer, 0, n);
                    }

                    string json = writer.ToString();

                    try
                    {
                        JSONObject jObj = new JSONObject(json);
                        data = jObj.GetJSONArray("airports");
                    }
                    catch (JSONException ex)
                    {
                        ex.PrintStackTrace();
                    }
                }
            }
            catch (Java.IO.IOException e)
            {
                e.PrintStackTrace();
            }
            finally
            {
                if (urlConnection != null)
                {
                    urlConnection.Disconnect();
                }
            }

            return(null);
        }
示例#23
0
 public virtual int[] GetIntArray(string key)
 {
     try
     {
         JSONArray array  = _data.GetJSONArray(key);
         int       length = array.Length();
         int[]     result = new int[length];
         for (int i = 0; i < length; i++)
         {
             result[i] = array.GetInt(i);
         }
         return(result);
     }
     catch (JSONException)
     {
         return(null);
     }
 }
示例#24
0
        public string[] GetMaterialNames()
        {
            JSONArray array = json.GetJSONArray("materials");
            int       size  = array.Length();

            string[] result = new string[size];
            for (int i = 0; i < size; ++i)
            {
                result[i] = array.GetJSONObject(i).GetString("name");
            }
            return(result);
        }
示例#25
0
        /// <summary>
        /// Метод,предназначенный для расспарсивания информации,которая приходит в виде Json объекта.
        /// </summary>
        /// <param name="jObject">Информация о маршруте</param>
        /// <returns>Преобразованная информация о маршруте</returns>
        public List <List <Dictionary <string, string> > > Parse(JSONObject jObject)
        {
            List <List <Dictionary <string, string> > > routes = new List <List <Dictionary <string, string> > >();
            JSONArray jRoutes = null;
            JSONArray jLegs   = null;
            JSONArray jSteps  = null;

            try
            {
                //Получаем массив информации о маршрутах по ключу "routes".
                jRoutes = jObject.GetJSONArray("routes");
                for (int i = 0; i < jRoutes.Length(); i++)
                {
                    //Получаем массив с информацией о маршруте по ключу "legs".
                    jLegs = ((JSONObject)jRoutes.Get(i)).GetJSONArray("legs");
                    List <Dictionary <string, string> > path = new List <Dictionary <string, string> >();
                    //Loop for all legs
                    for (int j = 0; j < jLegs.Length(); j++)
                    {
                        // получаем массив отрезков из которых маршрут по ключу "steps".
                        jSteps = ((JSONObject)jLegs.Get(j)).GetJSONArray("steps");

                        for (int k = 0; k < jSteps.Length(); k++)
                        {
                            string polyline = "";
                            // Поулчаем каждую точку отрезка.
                            polyline = (string)((JSONObject)((JSONObject)jSteps.Get(k)).Get("polyline")).Get("points");
                            List <LatLng> list = DecodePolyline(polyline);

                            // Парсим каждую точку отрезка.
                            for (int l = 0; l < list.Count; l++)
                            {
                                Dictionary <string, string> hm = new Dictionary <string, string>();
                                hm.Add("lat", list[l].Latitude.ToString());
                                hm.Add("lon", list[l].Longitude.ToString());
                                path.Add(hm);
                            }
                        }
                        // Добавляем в лист наш маршурут.
                        routes.Add(path);
                    }
                }
            }
            catch (JSONException e)
            {
                Android.Util.Log.Error("Error", e.Message);
            }
            catch (Exception e)
            {
                Android.Util.Log.Error("Error", e.Message);
            }
            return(routes);
        }
示例#26
0
        /// <exception cref="Org.Codehaus.Jettison.Json.JSONException"/>
        /// <exception cref="System.Exception"/>
        public virtual void VerifyBlacklistedNodesInfo(JSONObject blacklist, AppContext ctx
                                                       )
        {
            JSONArray array = blacklist.GetJSONArray("blacklistedNodes");

            NUnit.Framework.Assert.AreEqual(array.Length(), ctx.GetBlacklistedNodes().Count);
            for (int i = 0; i < array.Length(); i++)
            {
                NUnit.Framework.Assert.IsTrue(ctx.GetBlacklistedNodes().Contains(array.GetString(
                                                                                     i)));
            }
        }
示例#27
0
        //{"retcode":0,"result":[{"poll_type":"message","value":{"msg_id":21273,"from_uin":2684355364,"to_uin":496063973,"msg_id2":105299,"msg_type":9,"reply_ip":176756443,"time":1386733521,"content":[["font",{"size":15,"color":"000000","style":[0,0,0],"name":"\u5B8B\u4F53"}],"strlist\u6492\u65E6\u53D1\u8069\r "]}},{"poll_type":"message","value":{"msg_id":21271,"from_uin":2684355364,"to_uin":496063973,"msg_id2":105297,"msg_type":9,"reply_ip":176756443,"time":1386733510,"content":[["font",{"size":15,"color":"000000","style":[0,0,0],"name":"\u5B8B\u4F53"}],"str\u5012\u8428\u7A7A\u95F4 "]}},{"poll_type":"message","value":{"msg_id":21270,"from_uin":2684355364,"to_uin":496063973,"msg_id2":105296,"msg_type":9,"reply_ip":176756443,"time":1386733508,"content":[["font",{"size":15,"color":"000000","style":[0,0,0],"name":"\u5B8B\u4F53"}],"str\u5012\u8428\u7A7A\u95F4 "]}},{"poll_type":"message","value":{"msg_id":21269,"from_uin":2684355364,"to_uin":496063973,"msg_id2":105295,"msg_type":9,"reply_ip":176756443,"time":1386733506,"content":[["font",{"size":15,"color":"000000","style":[0,0,0],"name":"\u5B8B\u4F53"}],"str\u5012\u8428\u7A7A\u95F4 "]}},{"poll_type":"message","value":{"msg_id":21272,"from_uin":2684355364,"to_uin":496063973,"msg_id2":105292,"msg_type":9,"reply_ip":176756443,"time":1386733512,"content":[["font",{"size":15,"color":"000000","style":[0,0,0],"name":"\u5B8B\u4F53"}],"str\u5012\u8428\u7A7A\u95F4 "]}},{"poll_type":"message","value":{"msg_id":21268,"from_uin":2684355364,"to_uin":496063973,"msg_id2":105291,"msg_type":9,"reply_ip":176756443,"time":1386733499,"content":[["font",{"size":15,"color":"000000","style":[0,0,0],"name":"\u5B8B\u4F53"}],"str\u5012\u8428\u7A7A\u95F4 "]}}]}


        public static List <QQMessageEventArgs> Parse(string text)
        {
            List <QQMessageEventArgs> list = new List <QQMessageEventArgs>();
            JSONObject obj = JSONConvert.DeserializeObject(text);

            Debug.WriteLine(obj.GetString("result"));
            JSONArray array = obj.GetJSONArray("result");

            foreach (JSONObject item in array)
            {
                JSONObject         newobj = item.GetJSONObject("value");
                QQMessageEventArgs m      = new QQMessageEventArgs(text);

                switch (item.GetString("poll_type"))
                {
                case "tips":
                    m = null;
                    break;

                case "message":
                    m.PollMsgType = PollType.Friend;
                    m.Data        = GetFriendMessage(newobj);
                    break;

                case "group_message":
                    m.PollMsgType = PollType.Group;
                    m.Data        = GetGroupMessage(newobj);
                    break;

                case "kick_message":
                    m.PollMsgType = PollType.KickMessage;
                    m.Data        = GetKickMessage(newobj);
                    break;

                case "system_message":
                case "sys_g_msg":
                    m.PollMsgType = PollType.System;
                    m             = null;
                    break;

                default:
                    m = null;
                    break;
                }
                if (m != null)
                {
                    list.Add(m);
                }
            }

            return(list);
        }
示例#28
0
        public static Recipe FromJson(Context context, JSONObject json)
        {
            var recipe = new Recipe();

            try
            {
                recipe.TitleText   = json.GetString(Constants.RecipeFieldTitle);
                recipe.SummaryText = json.GetString(Constants.RecipeFieldSummary);
                if (json.Has(Constants.RecipeFieldImage))
                {
                    recipe.RecipeImage = json.GetString(Constants.RecipeFieldImage);
                }
                JSONArray ingredients = json.GetJSONArray(Constants.RecipeFieldIngredients);
                recipe.IngredientsText = "";
                for (int i = 0; i < ingredients.Length(); i++)
                {
                    recipe.IngredientsText += " - " + ingredients.GetJSONObject(i).GetString(Constants.RecipeFieldText) + "\n";
                }

                JSONArray steps = json.GetJSONArray(Constants.RecipeFieldSteps);
                for (int i = 0; i < steps.Length(); i++)
                {
                    var step       = steps.GetJSONObject(i);
                    var recipeStep = new RecipeStep();
                    recipeStep.StepText = step.GetString(Constants.RecipeFieldText);
                    if (step.Has(Constants.RecipeFieldName))
                    {
                        recipeStep.StepImage = step.GetString(Constants.RecipeFieldImage);
                    }
                    recipe.RecipeSteps.Add(recipeStep);
                }
            }
            catch (Exception ex) {
                Log.Error(Tag, "Error loading recipe: " + ex);
                return(null);
            }
            return(recipe);
        }
        public void ReadQuizFromFile(View view)
        {
            ClearQuizStatus();
            JSONObject jsonObject = JsonUtils.LoadJsonFile(this, QUIZ_JSON_FILE);
            JSONArray  jsonArray  = jsonObject.GetJSONArray(JsonUtils.JSON_FIELD_QUESTIONS);

            for (int i = 0; i < jsonArray.Length(); i++)
            {
                JSONObject questionObject = jsonArray.GetJSONObject(i);
                Question   question       = Question.FromJSon(questionObject, question_index++);
                AddQuestionDataItem(question);
                SetNewQuestionStatus(question.question);
            }
        }
示例#30
0
        private static FriendMessageData GetFriendMessage(JSONObject obj)
        {
            FriendMessageData data = new FriendMessageData();

            data.MsgID   = obj.GetString("msg_id");
            data.MsgID2  = obj.GetString("msg_id2");
            data.MsgType = int.Parse(obj.GetString("msg_type"));
            data.ReplyIP = obj.GetString("reply_ip");
            data.FromUin = obj.GetString("from_uin");
            data.ToUin   = obj.GetString("to_uin");
            JSONArray content = obj.GetJSONArray("content");

            foreach (var item in content)
            {
                if (item is string)
                {
                    string text = item.ToString();
                    if (text.IndexOf("\\u") > -1)
                    {
                        text = Encode.DeUnicode(text);
                    }
                    data.Content.Add(text);
                }
                else if (item is JSONArray)
                {
                    JSONArray array = item as JSONArray;
                    string    flag  = array[0].ToString();
                    if (flag == "face")
                    {
                        data.Content.Add(string.Format("[face{0}]", array[1]));
                    }
                    //JSONArray font = item as JSONArray;
                    //foreach (var sitem in font)
                    //{
                    //    if(sitem is JSONObject )
                    //    {
                    //        JSONObject temp = sitem as JSONObject;

                    //        data.Color = Tool.GetColor(temp.GetString("color"));

                    //    }
                    //}
                }
            }



            return(data);
        }