List of usage examples for org.json JSONObject getJSONArray
public JSONArray getJSONArray(String key) throws JSONException
From source file:com.maya.portAuthority.googleMaps.Instructions.java
/** * Receives a JSONObject and returns a Direction * //from ww w .j a v a 2 s . c o m * @param jsonObject * @return The Direction retrieved by the JSON Object */ public static List<Direction> parse(JSONObject jsonObject) throws Exception { List<Direction> directionsList = null; // returned direction Direction currentGDirection = null; // current direction List<Legs> legsList = null; // legs Legs currentLeg = null; // current leg List<Path> pathsList = null;// paths Path currentPath = null;// current path // JSON parts: JSONArray routes = null; JSONObject route = null; JSONObject bound = null; JSONArray legs = null; JSONObject leg = null; JSONArray steps = null; JSONObject step = null; String polyline = ""; try { routes = jsonObject.getJSONArray("routes"); LOGGER.info("routes found : " + routes.length()); directionsList = new ArrayList<Direction>(); // traverse routes for (int i = 0; i < routes.length(); i++) { route = (JSONObject) routes.get(i); legs = route.getJSONArray("legs"); LOGGER.info("route[" + i + "]contains " + legs.length() + " legs"); // traverse legs legsList = new ArrayList<Legs>(); for (int j = 0; j < legs.length(); j++) { leg = (JSONObject) legs.get(j); steps = leg.getJSONArray("steps"); LOGGER.info("route[" + i + "]:leg[" + j + "] contains " + steps.length() + " steps"); // traverse all steps pathsList = new ArrayList<Path>(); for (int k = 0; k < steps.length(); k++) { step = (JSONObject) steps.get(k); polyline = (String) ((JSONObject) (step).get("polyline")).get("points"); // Build the List of GDPoint that define the path List<Point> list = decodePoly(polyline); // Create the GDPath currentPath = new Path(list); currentPath.setDistance(((JSONObject) step.get("distance")).getInt("value")); currentPath.setDuration(((JSONObject) step.get("duration")).getInt("value")); currentPath.setHtmlText(step.getString("html_instructions")); currentPath.setTravelMode(step.getString("travel_mode")); LOGGER.info("routes[" + i + "]:legs[" + j + "]:Step[" + k + "] contains " + list.size() + " points"); // Add it to the list of Path of the Direction pathsList.add(currentPath); } // currentLeg = new Legs(pathsList); currentLeg.setDistance(((JSONObject) leg.get("distance")).getInt("value")); currentLeg.setmDuration(((JSONObject) leg.get("duration")).getInt("value")); currentLeg.setEndAddr(leg.getString("end_address")); currentLeg.setStartAddr(leg.getString("start_address")); legsList.add(currentLeg); LOGGER.info("Added a new Path and paths size is : " + pathsList.size()); } // Build the GDirection using the paths found currentGDirection = new Direction(legsList); bound = (JSONObject) route.get("bounds"); currentGDirection .setNorthEastBound(new Location(((JSONObject) bound.get("northeast")).getDouble("lat"), ((JSONObject) bound.get("northeast")).getDouble("lng"))); currentGDirection .setmSouthWestBound(new Location(((JSONObject) bound.get("southwest")).getDouble("lat"), ((JSONObject) bound.get("southwest")).getDouble("lng"))); currentGDirection.setCopyrights(route.getString("copyrights")); directionsList.add(currentGDirection); } } catch (JSONException e) { LOGGER.error("Parsing JSon from GoogleDirection Api failed, see stack trace below:", e); throw new Exception("Parsing JSon from GoogleDirection Api failed"); } catch (Exception e) { LOGGER.error("Parsing JSon from GoogleDirection Api failed, see stack trace below:", e); throw new Exception("Parsing JSon from GoogleDirection Api failed"); } return directionsList; }
From source file:org.cvrgrid.waveform.backing.GlobusUploadBacking.java
/** * Private API that polls all the endpoints for a user. *//* ww w . ja v a2 s. co m*/ private Status getEndpoints(JSONTransferAPIClient client, String query, String endpointType) { try { JSONTransferAPIClient.Result r = client.getResult(query); Map<String, GlobusEndpointList> globusEndpointLists = this.getGlobusEndpointLists(); GlobusEndpointList globusEndpointList = globusEndpointLists.get(endpointType); logger.info("Endpoint Listing " + query + " for " + client.getUsername() + ": "); Iterator<?> keys = r.document.keys(); while (keys.hasNext()) { String next = (String) keys.next(); if (next.equalsIgnoreCase("data_type")) { globusEndpointList.setDataType(r.document.getString(next)); } else if (next.equalsIgnoreCase("length")) { globusEndpointList.setLength(new Integer(r.document.getString(next))); } else if (next.equalsIgnoreCase("limit")) { globusEndpointList.setLimit(r.document.getString(next)); } else if (next.equalsIgnoreCase("offset")) { globusEndpointList.setOffset(r.document.getString(next)); } else if (next.equalsIgnoreCase("total")) { globusEndpointList.setTotal(r.document.getString(next)); } else if (next.equalsIgnoreCase("data")) { JSONArray data = r.document.getJSONArray(next); int size = data.length(); ArrayList<GlobusEndpoint> globusEndpoints = new ArrayList<GlobusEndpoint>(); for (int j = 0; j < size; j++) { GlobusEndpoint globusEndpoint = new GlobusEndpoint(); JSONObject globusEndpointInfo = data.getJSONObject(j); Iterator<?> keys2 = globusEndpointInfo.keys(); while (keys2.hasNext()) { String next2 = (String) keys2.next(); if (next2.equalsIgnoreCase("data_type")) { globusEndpoint.setDataType(globusEndpointInfo.getString(next2)); } else if (next2.equalsIgnoreCase("username")) { globusEndpoint.setUserName(globusEndpointInfo.getString(next2)); } else if (next2.equalsIgnoreCase("globus_connect_setup_key")) { globusEndpoint.setGlobusConnectSetupKey(globusEndpointInfo.getString(next2)); } else if (next2.equalsIgnoreCase("name")) { globusEndpoint.setName(globusEndpointInfo.getString(next2)); } else if (next2.equalsIgnoreCase("activated")) { globusEndpoint.setActivated(globusEndpointInfo.getBoolean(next2)); } else if (next2.equalsIgnoreCase("is_globus_connect")) { globusEndpoint.setIsGlobusConnect(globusEndpointInfo.getBoolean(next2)); } else if (next2.equalsIgnoreCase("ls_link")) { JSONObject linkInfo = globusEndpointInfo.getJSONObject(next2); GlobusLink lsLink = new GlobusLink(); Iterator<?> keys3 = linkInfo.keys(); while (keys3.hasNext()) { String next3 = (String) keys3.next(); if (next3.equalsIgnoreCase("data_type")) { lsLink.setDataType(linkInfo.getString(next3)); } else if (next3.equalsIgnoreCase("href")) { lsLink.setHref(linkInfo.getString(next3)); } else if (next3.equalsIgnoreCase("resource")) { lsLink.setResource(linkInfo.getString(next3)); } else if (next3.equalsIgnoreCase("relationship")) { lsLink.setRelationship(linkInfo.getString(next3)); } else if (next3.equalsIgnoreCase("title")) { lsLink.setTitle(linkInfo.getString(next3)); } } globusEndpoint.setLsLink(lsLink); } else if (next2.equalsIgnoreCase("canonical_name")) { globusEndpoint.setCanonicalName(globusEndpointInfo.getString(next2)); } else if (next2.equalsIgnoreCase("myproxy_server")) { globusEndpoint.setMyProxyServer(globusEndpointInfo.getString(next2)); } else if (next2.equalsIgnoreCase("expire_time")) { //globusEndpoint.setExpireTime(new Date(globusEndpointInfo.getString(next2))); } else if (next2.equalsIgnoreCase("public")) { globusEndpoint.setGlobusPublic(globusEndpointInfo.getBoolean(next2)); } else if (next2.equalsIgnoreCase("description")) { globusEndpoint.setDescription(globusEndpointInfo.getString(next2)); } else if (next2.equalsIgnoreCase("data")) { JSONArray serverData = globusEndpointInfo.getJSONArray(next2); int serverDataSize = serverData.length(); ArrayList<GlobusServer> globusServers = new ArrayList<GlobusServer>(); for (int k = 0; k < serverDataSize; k++) { GlobusServer globusServer = new GlobusServer(); JSONObject globusServerInfo = serverData.getJSONObject(k); Iterator<?> keys4 = globusServerInfo.keys(); while (keys4.hasNext()) { String next4 = (String) keys4.next(); if (next4.equalsIgnoreCase("data_type")) { globusServer.setDataType(globusServerInfo.getString(next4)); } else if (next4.equalsIgnoreCase("id")) { globusServer.setId(globusServerInfo.getInt(next4)); } else if (next4.equalsIgnoreCase("hostname")) { globusServer.setHostname(globusServerInfo.getString(next4)); } else if (next4.equalsIgnoreCase("uri")) { globusServer.setUri(globusServerInfo.getString(next4)); } else if (next4.equalsIgnoreCase("scheme")) { globusServer.setScheme(globusServerInfo.getString(next4)); } else if (next4.equalsIgnoreCase("port")) { if (globusServerInfo.get("port").toString().equalsIgnoreCase("null")) { globusServer.setPort(0); } else { globusServer.setPort(globusServerInfo.getInt(next4)); } } else if (next4.equalsIgnoreCase("subject")) { globusServer.setSubject(globusServerInfo.getString(next4)); } else if (next4.equalsIgnoreCase("is_connected")) { globusServer.setIsConnected(globusServerInfo.getBoolean(next4)); } } globusServers.add(globusServer); } globusEndpoint.setGlobusServers(globusServers); } } globusEndpoints.add(globusEndpoint); } globusEndpointList.setGlobusEndpoints(globusEndpoints); } } globusEndpointLists.put(endpointType, globusEndpointList); this.setGlobusEndpointLists(globusEndpointLists); return Status.OK; } catch (Exception e) { logger.error("Got an exception..\n"); logger.error(e.getMessage()); logger.error(e.getStackTrace().toString()); e.printStackTrace(); return Status.FAIL; } }
From source file:com.bmwcarit.barefoot.roadmap.Loader.java
/** * Reads road type configuration from JSON representation. * * @param jsonconfig JSON representation of the road type configuration. * @return Mapping of road class identifiers to priority factor and default maximum speed. * @throws JSONException thrown on JSON extraction or parsing error. *//* w w w . j av a 2 s.co m*/ public static Map<Short, Tuple<Double, Integer>> roadtypes(JSONObject jsonconfig) throws JSONException { Map<Short, Tuple<Double, Integer>> config = new HashMap<>(); JSONArray jsontags = jsonconfig.getJSONArray("tags"); for (int i = 0; i < jsontags.length(); ++i) { JSONObject jsontag = jsontags.getJSONObject(i); JSONArray jsonvalues = jsontag.getJSONArray("values"); for (int j = 0; j < jsonvalues.length(); ++j) { JSONObject jsonvalue = jsonvalues.getJSONObject(j); config.put((short) jsonvalue.getInt("id"), new Tuple<>(jsonvalue.getDouble("priority"), jsonvalue.getInt("maxspeed"))); } } return config; }
From source file:com.ymt.demo1.plates.hub.FireHubMainFragment.java
/** * hub??// ww w . j a va2s. c o m */ public StringRequest hubPlateRequest() { return new StringRequest(BaseURLUtil.PLATE_REQUEST_URL, new Response.Listener<String>() { @Override public void onResponse(String s) { // Log.e("TAG", ">>>>>>>>>>>>>.s " + s); try { JSONObject jsonObject = new JSONObject(s); if (jsonObject.getInt("retCode") == 0) { //? JSONArray jsonArray = jsonObject.getJSONArray("data"); int length = jsonArray.length(); for (int i = 0; i < length; i++) { JSONObject object = jsonArray.getJSONObject(i); HubPlate hubPlate = new HubPlate(); hubPlate.setFid(object.getInt("fid")); hubPlate.setFup(object.getInt("fup")); hubPlate.setLastpost(object.getString("lastpost")); hubPlate.setName(object.getString("name")); hubPlate.setType(object.getString("type")); hubPlate.setRank(object.optInt("rank")); hubPlate.setThreads(object.optInt("threads")); plateList.add(hubPlate); } update1List(); } } catch (JSONException e) { AppContext.toastBadJson(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { AppContext.toastBadInternet(); } }); }
From source file:dhbw.RaplaCalGenerator.HTMLCleaner.java
public ArrayList<Course> generateCourses(String location) { try {//from w w w. j a v a2 s.co m head.add(html.indexOf("<head")); head.add(html.indexOf("/head") + 6); html.delete(head.get(0), head.get(1)); int index = 0; while (html.indexOf("<br>", index) != -1) { //kill <br> int actualBr = html.indexOf("<br>"); html.delete(actualBr, actualBr + 4); index = actualBr; } index = 0; while (html.indexOf("", index) != -1) { //kill <br> int actual = html.indexOf(""); html.replace(actual, actual + 2, ""); index = actual + 10; //System.out.println("Another deleted: " + html.substring(actual - 5, actual +20)); } index = 0; while (html.indexOf("", index) != -1) { //kill <br> int actual = html.indexOf(""); html.replace(actual, actual + 2, ""); index = actual + 10; //System.out.println("Another deleted: " + html.substring(actual - 5, actual +20)); } index = 0; while (html.indexOf("", index) != -1) { //kill <br> int actual = html.indexOf(""); html.replace(actual, actual + 2, ""); index = actual + 10; //System.out.println("Another deleted: " + html.substring(actual - 5, actual +20)); } JSONObject myJSON = XML.toJSONObject(html.toString()); JSONArray coursesL1 = myJSON.getJSONObject("html").getJSONObject("body").getJSONArray("div") .getJSONObject(1).getJSONObject("table").getJSONObject("tbody").getJSONArray("tr"); JSONObject itemsO = coursesL1.getJSONObject(4).getJSONArray("td").getJSONObject(0); //System.out.println(itemsO.keySet()); for (int i = 2; i < coursesL1.length(); i++) { JSONArray tds = coursesL1.getJSONObject(i).getJSONArray("td"); for (int j = 0; j < tds.length(); j++) { JSONObject entry = tds.getJSONObject(j); Set<String> contents = entry.keySet(); if (contents.contains("a")) { Course newCourse = new Course(); JSONObject actualCourse = entry.getJSONObject("a"); JSONArray courseContent = actualCourse.getJSONArray("content"); newCourse.setTitle(courseContent.getString(1)); String courseTimes = actualCourse.getJSONObject("span").getJSONArray("div").getString(1); String[] splits = courseTimes.split(" "); String day = splits[1].substring(0, 2); String month = splits[1].substring(3, 5); String year = splits[1].substring(6, 8); String[] times = splits[2].split("-"); String[] startTime = times[0].split(":"); String[] endTime = times[1].split(":"); int i_day = Integer.parseInt(day); int i_month = Integer.parseInt(month); int i_year = Integer.parseInt(year) + 2000; int i_startHours = Integer.parseInt(startTime[0]); int i_startMinutes = Integer.parseInt(startTime[1]); int i_endHours = Integer.parseInt(endTime[0]); int i_endMinutes = Integer.parseInt(endTime[1]); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm"); Date startDate = format.parse( i_year + "-" + i_month + "-" + i_day + " " + i_startHours + "-" + i_startMinutes); Date endDate = format.parse( i_year + "-" + i_month + "-" + i_day + " " + i_endHours + "-" + i_endMinutes); newCourse.setStartDate(startDate); newCourse.setEndDate(endDate); courses.add(newCourse); } } } return this.courses; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:de.kp.ames.web.core.search.SearcherImpl.java
/** * A helper method to retrieve requested * facets from a JSON-based query object * /*from ww w . ja v a 2 s . c o m*/ * @param jQuery * @return * @throws Exception */ protected String setFacets(JSONObject jQuery) throws Exception { String fp = null; if (jQuery.has(JsonConstants.J_FACET)) { /* * Externally selected facets are mapped * onto a filter query */ fp = ""; JSONArray jFacets = jQuery.getJSONArray(JsonConstants.J_FACET); for (int i = 0; i < jFacets.length(); i++) { JSONObject jFacet = jFacets.getJSONObject(i); String field = jFacet.getString(JsonConstants.J_FIELD); String value = jFacet.getString(JsonConstants.J_VALUE); fp += "+" + field + ":\"" + value + "\""; } } return fp; }
From source file:rsInstanceJumpstart.rackspaceAccount.java
public String[][] listServers() { String[][] thisServerList = new String[100][5]; //String thisServerList; HttpURLConnection connection; String output = ""; int thisServerListCounter = 0; String thisServerLink;/*ww w . j a va 2s . co m*/ try { for (int i = 0; i < serviceCatalogJson.getJSONObject("access").getJSONArray("serviceCatalog") .length(); i++) { if ("cloudServersOpenStack".equals(serviceCatalogJson.getJSONObject("access") .getJSONArray("serviceCatalog").getJSONObject(i).get("name").toString())) { for (int ii = 0; ii < serviceCatalogJson.getJSONObject("access").getJSONArray("serviceCatalog") .getJSONObject(i).getJSONArray("endpoints").length(); ii++) { String thisEndpoint = serviceCatalogJson.getJSONObject("access") .getJSONArray("serviceCatalog").getJSONObject(i).getJSONArray("endpoints") .getJSONObject(ii).get("publicURL").toString(); if (thisEndpoint.length() > 0) { try { output = ""; System.out.println("current endpoint: " + thisEndpoint); connection = (HttpURLConnection) new URL(thisEndpoint + "/servers") .openConnection(); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("X-Auth-Token", currentAuthToken); InputStream response; response = connection.getInputStream(); //System.out.println(String.valueOf(connection.getResponseCode())); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { output += line + "\n"; } } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { System.out.println(e); } } } } catch (IOException e) { System.out.println(e); } JSONObject thisResponseJson = new JSONObject(output); if (thisResponseJson.getJSONArray("servers").length() > 0) { for (int iii = 0; iii < thisResponseJson.getJSONArray("servers").length(); iii++) { thisServerLink = thisResponseJson.getJSONArray("servers").getJSONObject(iii) .getJSONArray("links").getJSONObject(0).get("href").toString(); //query for details of each server try { output = ""; connection = (HttpURLConnection) new URL(thisServerLink).openConnection(); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("X-Auth-Token", currentAuthToken); InputStream response; response = connection.getInputStream(); //System.out.println(String.valueOf(connection.getResponseCode())); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { output += line + "\n"; } } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { System.out.println(e); } } } } catch (IOException e) { System.out.println(e); } //System.out.println(output); JSONObject thisServer = new JSONObject(output); System.out.println(thisServer.getJSONObject("server").get("name").toString()); if ("SHUTOFF".equals(thisServerList[thisServerListCounter][2] = thisServer .getJSONObject("server").getString("status"))) { thisServerList[thisServerListCounter][0] = thisServer .getJSONObject("server").getString("name"); thisServerList[thisServerListCounter][1] = thisServer .getJSONObject("server").getString("id"); thisServerList[thisServerListCounter][2] = thisServer .getJSONObject("server").getString("status"); thisServerList[thisServerListCounter][3] = thisServerLink; thisServerList[thisServerListCounter][4] = thisServer .getJSONObject("server").getString("accessIPv4"); System.out.println(thisServerList[thisServerListCounter][2]); thisServerListCounter++; } } } } } } } } catch (JSONException e) { //let's assume for now we won't have any } //thisServerList = output; return thisServerList; }
From source file:com.kerio.dashboard.api.NotificationGetter.java
public HashMap<String, Notification> getAllNotifications() { HashMap<String, Notification> result = null; JSONObject arguments = new JSONObject(); try {// w w w .j av a2 s . c om arguments.put("lastNotifications", this.fakeNotification); arguments.put("timeout", 0); } catch (JSONException e) { return result; } JSONObject ret = client.exec("Notifications.get", arguments); if (ret == null) { return result; } try { JSONArray nn = ret.getJSONArray("notifications"); if (nn.length() == 0) { return result; } lastNotifications = nn; result = new HashMap<String, Notification>(); for (int i = 0; i < lastNotifications.length(); ++i) { JSONObject notificationInfo = lastNotifications.getJSONObject(i); String key = lastNotifications.getString(i); String type = notificationInfo.getString("type"); String value = notificationInfo.getString("value"); Notification notification = this.createNotification(type, value); result.put(key, notification); } } catch (JSONException e) { } return result; }
From source file:com.nikitaend.instafeed.sola.instagram.InstagramSession.java
/** * Searches for media by location and creation time. * /* w ww . j a va 2s .c o m*/ * @param latitude * latitude of location * @param longitude * longitude of location * @param minTimestamp * the min timestamp of media to be returned. Can be null if * needed. * @param maxTimestamp * the max timestamp of media to be returned. Can be null if * needed. * @param distance * the of the location. Can be null if needed. * @throws Exception, JSONException * @return List of recent media that meet the search parameters */ public List<Media> searchMedia(Object latitude, Object longitude, Object minTimestamp, Object maxTimestamp, Object distance) throws Exception { ArrayList<Media> media = new ArrayList<Media>(); String uri = UriFactory.Media.SEARCH_MEDIA + "?access_token=" + getAccessToken() + "&lat=" + latitude + "&lng=" + longitude + "&min_timestamp=" + minTimestamp + "&max_timestamp=" + maxTimestamp + "&distance=" + distance; JSONObject object = (new GetMethod(uri)).call().getJSON(); JSONArray mediaItems = object.getJSONArray("data"); for (int i = 0; i < mediaItems.length(); i++) { media.add(Media.fromJSON(mediaItems.getJSONObject(i), getAccessToken())); } return media; }
From source file:com.nikitaend.instafeed.sola.instagram.InstagramSession.java
/** * Finds and returns the most popular media on instagram. * /*from w w w . ja v a 2s . c o m*/ * @throws Exception, JSONException * @return List of the most popular media on instagram. */ public List<Media> getPopularMedia() throws Exception { ArrayList<Media> media = new ArrayList<Media>(); String uri = uriConstructor.constructUri(UriFactory.Media.GET_POPULAR_MEDIA, null, true); JSONObject object = (new GetMethod().setMethodURI(uri)).call().getJSON(); JSONArray mediaItems = object.getJSONArray("data"); for (int i = 0; i < mediaItems.length(); i++) { media.add(Media.fromJSON(mediaItems.getJSONObject(i), getAccessToken())); } return media; }