List of usage examples for org.json JSONObject getJSONObject
public JSONObject getJSONObject(String key) throws JSONException
From source file:org.schedulesdirect.grabber.ScheduleTask.java
protected Map<String, Collection<String>> getStaleStationIds() { Map<String, Collection<String>> staleIds = new HashMap<>(); DefaultJsonRequest req = factory.get(DefaultJsonRequest.Action.POST, RestNouns.SCHEDULE_MD5S, clnt.getHash(), clnt.getUserAgent(), clnt.getBaseUrl()); JSONArray data = new JSONArray(); for (int i = 0; i < this.req.length(); ++i) { JSONObject o = new JSONObject(); o.put("stationID", this.req.getString(i)); data.put(o);/*from ww w . j ava 2s . c o m*/ } try { JSONObject result = Config.get().getObjectMapper().readValue(req.submitForJson(data), JSONObject.class); if (!JsonResponseUtils.isErrorResponse(result)) { Iterator<?> idItr = result.keys(); while (idItr.hasNext()) { String stationId = idItr.next().toString(); boolean schedFileExists = Files .exists(vfs.getPath("schedules", String.format("%s.txt", stationId))); Path cachedMd5File = vfs.getPath("md5s", String.format("%s.txt", stationId)); JSONObject cachedMd5s = Files.exists(cachedMd5File) ? Config.get().getObjectMapper() .readValue(new String(Files.readAllBytes(cachedMd5File), ZipEpgClient.ZIP_CHARSET.toString()), JSONObject.class) : new JSONObject(); JSONObject stationInfo = result.getJSONObject(stationId); Iterator<?> dateItr = stationInfo.keys(); while (dateItr.hasNext()) { String date = dateItr.next().toString(); JSONObject dateInfo = stationInfo.getJSONObject(date); if (!schedFileExists || isScheduleStale(dateInfo, cachedMd5s.optJSONObject(date))) { Collection<String> dates = staleIds.get(stationId); if (dates == null) { dates = new ArrayList<String>(); staleIds.put(stationId, dates); } dates.add(date); if (LOG.isDebugEnabled()) LOG.debug(String.format("Station %s/%s queued for refresh!", stationId, date)); } else if (LOG.isDebugEnabled()) LOG.debug(String.format("Station %s is unchanged on the server; skipping it!", stationId)); } Files.write(cachedMd5File, stationInfo.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); } } } catch (Throwable t) { Grabber.failedTask = true; LOG.error("Error processing cache; returning partial stale list!", t); } return staleIds; }
From source file:com.foxykeep.datadroidpoc.data.factory.CityListJsonFactory.java
public static Bundle parseResult(String wsResponse) throws DataException { ArrayList<City> cityList = new ArrayList<City>(); try {/*from w w w . j a v a 2 s.c o m*/ JSONObject parser = new JSONObject(wsResponse); JSONObject jsonRoot = parser.getJSONObject(JSONTag.CITY_LIST_ELEM_CITIES); JSONArray jsonPersonArray = jsonRoot.getJSONArray(JSONTag.CITY_LIST_ELEM_CITY); int size = jsonPersonArray.length(); for (int i = 0; i < size; i++) { JSONObject jsonPerson = jsonPersonArray.getJSONObject(i); City city = new City(); city.name = jsonPerson.getString(JSONTag.CITY_LIST_ELEM_CITY_NAME); city.postalCode = jsonPerson.getString(JSONTag.CITY_LIST_ELEM_CITY_POSTAL_CODE); city.state = jsonPerson.getString(JSONTag.CITY_LIST_ELEM_CITY_STATE); city.country = jsonPerson.getString(JSONTag.CITY_LIST_ELEM_CITY_COUNTRY); cityList.add(city); } } catch (JSONException e) { Log.e(TAG, "JSONException", e); throw new DataException(e); } Bundle bundle = new Bundle(); bundle.putParcelableArrayList(PoCRequestFactory.BUNDLE_EXTRA_CITY_LIST, cityList); return bundle; }
From source file:com.github.sommeri.sourcemap.SourceMapConsumerV3.java
/** * @param sourceMapRoot//from w w w .j a va 2s. c om * @throws SourceMapParseException */ private void parseMetaMap(JSONObject sourceMapRoot, SourceMapSupplier sectionSupplier) throws SourceMapParseException { if (sectionSupplier == null) { sectionSupplier = new DefaultSourceMapSupplier(); } try { // Check basic assertions about the format. int version = sourceMapRoot.getInt("version"); if (version != 3) { throw new SourceMapParseException("Unknown version: " + version); } String file = sourceMapRoot.getString("file"); if (file.isEmpty()) { throw new SourceMapParseException("File entry is missing or empty"); } if (sourceMapRoot.has("lineCount") || sourceMapRoot.has("mappings") || sourceMapRoot.has("sources") || sourceMapRoot.has("names")) { throw new SourceMapParseException("Invalid map format"); } SourceMapGeneratorV3 generator = new SourceMapGeneratorV3(); JSONArray sections = sourceMapRoot.getJSONArray("sections"); for (int i = 0, count = sections.length(); i < count; i++) { JSONObject section = sections.getJSONObject(i); if (section.has("map") && section.has("url")) { throw new SourceMapParseException( "Invalid map format: section may not have both 'map' and 'url'"); } JSONObject offset = section.getJSONObject("offset"); int line = offset.getInt("line"); int column = offset.getInt("column"); String mapSectionContents; if (section.has("url")) { String url = section.getString("url"); mapSectionContents = sectionSupplier.getSourceMap(url); if (mapSectionContents == null) { throw new SourceMapParseException("Unable to retrieve: " + url); } } else if (section.has("map")) { mapSectionContents = section.getString("map"); } else { throw new SourceMapParseException( "Invalid map format: section must have either 'map' or 'url'"); } generator.mergeMapSection(line, column, mapSectionContents); } StringBuilder sb = new StringBuilder(); try { generator.appendTo(sb, file); } catch (IOException e) { // Can't happen. throw new RuntimeException(e); } parse(sb.toString()); } catch (IOException ex) { throw new SourceMapParseException("IO exception: " + ex); } catch (JSONException ex) { throw new SourceMapParseException("JSON parse exception: " + ex); } }
From source file:com.foxykeep.datadroidpoc.data.factory.PersonListJsonFactory.java
public static ArrayList<Person> parseResult(String wsResponse) throws DataException { ArrayList<Person> personList = new ArrayList<Person>(); try {//from w w w. ja v a 2s.com JSONObject parser = new JSONObject(wsResponse); JSONObject jsonRoot = parser.getJSONObject(JSONTag.PERSON_LIST_ELEM_PERSONS); JSONArray jsonPersonArray = jsonRoot.getJSONArray(JSONTag.PERSON_LIST_ELEM_PERSON); int size = jsonPersonArray.length(); for (int i = 0; i < size; i++) { JSONObject jsonPerson = jsonPersonArray.getJSONObject(i); Person person = new Person(); person.firstName = jsonPerson.getString(JSONTag.PERSON_LIST_ELEM_PERSON_FIRST_NAME); person.lastName = jsonPerson.getString(JSONTag.PERSON_LIST_ELEM_PERSON_LAST_NAME); person.email = jsonPerson.getString(JSONTag.PERSON_LIST_ELEM_PERSON_EMAIL); person.city = jsonPerson.getString(JSONTag.PERSON_LIST_ELEM_PERSON_CITY); person.postalCode = jsonPerson.getInt(JSONTag.PERSON_LIST_ELEM_PERSON_POSTAL_CODE); person.age = jsonPerson.getInt(JSONTag.PERSON_LIST_ELEM_PERSON_AGE); person.isWorking = jsonPerson.getInt(JSONTag.PERSON_LIST_ELEM_PERSON_IS_WORKING) == 1; personList.add(person); } } catch (JSONException e) { Log.e(TAG, "JSONException", e); throw new DataException(e); } return personList; }
From source file:com.norman0406.slimgress.API.Knobs.PortalKnobs.java
public PortalKnobs(JSONObject json) throws JSONException { super(json);// w w w .j a v a2s. c o m JSONObject resonatorLimits = json.getJSONObject("resonatorLimits"); JSONArray bands = resonatorLimits.getJSONArray("bands"); mBands = new ArrayList<Band>(); for (int i = 0; i < bands.length(); i++) { JSONObject band = bands.getJSONObject(i); Band newBand = new Band(); newBand.applicableLevels = getIntArray(band, "applicableLevels"); newBand.remaining = band.getInt("remaining"); mBands.add(newBand); } mCanPlayerRemoveMod = json.getBoolean("canPlayerRemoveMod"); mMaxModsPerPlayer = json.getInt("maxModsPerPlayer"); }
From source file:com.foxykeep.datadroidpoc.data.factory.PhoneListFactory.java
public static ArrayList<Phone> parseResult(String wsResponse) throws DataException { ArrayList<Phone> phoneList = new ArrayList<Phone>(); try {/* ww w . j a va2 s. c om*/ JSONObject parser = new JSONObject(wsResponse); JSONObject jsonRoot = parser.getJSONObject(JSONTag.CRUD_PHONE_LIST_ELEM_PHONES); JSONArray jsonPhoneArray = jsonRoot.getJSONArray(JSONTag.CRUD_PHONE_LIST_ELEM_PHONE); int size = jsonPhoneArray.length(); for (int i = 0; i < size; i++) { JSONObject jsonPhone = jsonPhoneArray.getJSONObject(i); Phone phone = new Phone(); phone.serverId = jsonPhone.getLong(JSONTag.CRUD_PHONE_LIST_ELEM_ID); phone.name = jsonPhone.getString(JSONTag.CRUD_PHONE_LIST_ELEM_NAME); phone.manufacturer = jsonPhone.getString(JSONTag.CRUD_PHONE_LIST_ELEM_MANUFACTURER); phone.androidVersion = jsonPhone.getString(JSONTag.CRUD_PHONE_LIST_ELEM_ANDROID_VERSION); phone.screenSize = jsonPhone.getDouble(JSONTag.CRUD_PHONE_LIST_ELEM_SCREEN_SIZE); phone.price = jsonPhone.getInt(JSONTag.CRUD_PHONE_LIST_ELEM_PRICE); phoneList.add(phone); } } catch (JSONException e) { Log.e(TAG, "JSONException", e); throw new DataException(e); } return phoneList; }
From source file:org.collectionspace.chain.csp.webui.record.RecordSearchList.java
/** * Retrieve the mini summary information e.g. summary and number and append * the csid and recordType to it/*from w w w .j a v a 2 s.c om*/ * * @param {Storage} storage Type of storage (e.g. AuthorizationStorage, * RecordStorage,...) * @param {String} type The type of record requested (e.g. permission) * @param {String} csid The csid of the record * @return {JSONObject} The JSON string containing the mini record * @throws ExistException * @throws UnimplementedException * @throws UnderlyingStorageException * @throws JSONException */ private JSONObject generateMiniRecord(Storage storage, String type, String csid) throws JSONException { String postfix = "list"; if (this.mode == MODE_SEARCH) { postfix = "search"; } JSONObject restrictions = new JSONObject(); JSONObject out = new JSONObject(); try { if (csid == null || csid.equals("")) { return out; } out = storage.retrieveJSON(type + "/" + csid + "/view/" + postfix, restrictions); out.put("csid", csid); String recordtype = null; if (!r.isType("searchall")) { recordtype = type_to_url.get(type); } else { JSONObject summarylist = out.getJSONObject("summarylist"); String uri = summarylist.getString("uri"); if (uri != null && uri.startsWith("/")) { uri = uri.substring(1); } String[] parts = uri.split("/"); String recordurl = parts[0]; Record itemr = r.getSpec().getRecordByServicesUrl(recordurl); if (itemr == null) { String docType = summarylist.getString("docType"); itemr = r.getSpec().getRecordByServicesDocType(docType); } if (itemr == null) { recordtype = UNKNOWN_RECORD_TYPE; log.warn("Could not get record type for record with services URI " + uri); } else { recordtype = type_to_url.get(itemr.getID()); String refName = null; if (summarylist.has("refName")) { refName = summarylist.getString("refName"); } // For an authority item (i.e. an item in a vocabulary), // include the name of its parent vocabulary in a // "namespace" value within the mini summary. RefName.AuthorityItem item = null; if (refName != null) { item = RefName.AuthorityItem.parse(refName); } // If this refName could be successfully parsed (above) as an // authority item refName, then include the "namespace" value. if (item != null) { String namespace = item.getParentShortIdentifier(); if (namespace != null) { out.put("namespace", namespace); } else { log.warn("Could not get vocabulary namespace for record with services URI " + uri); } } } } out.put("recordtype", recordtype); // CSPACE-2894 if (this.r.getID().equals("permission")) { String summary = out.getString("summary"); String name = Generic.ResourceNameUI(this.r.getSpec(), summary); if (name.contains(WORKFLOW_SUB_RESOURCE)) { return null; } out.put("summary", name); out.put("display", Generic.getPermissionView(this.r.getSpec(), summary)); } } catch (ExistException e) { out.put("csid", csid); out.put("isError", true); JSONObject msg = new JSONObject(); msg.put("severity", "error"); msg.put("message", "Exist Exception:" + e.getMessage()); JSONArray msgs = new JSONArray(); msgs.put(msg); out.put("messages", msgs); } catch (UnimplementedException e) { out.put("csid", csid); out.put("isError", true); JSONObject msg = new JSONObject(); msg.put("severity", "error"); msg.put("message", "Exist Exception:" + e.getMessage()); JSONArray msgs = new JSONArray(); msgs.put(msg); out.put("messages", msgs); } catch (UnderlyingStorageException e) { out.put("csid", csid); out.put("isError", true); JSONObject msg = new JSONObject(); msg.put("severity", "error"); msg.put("message", "Exist Exception:" + e.getMessage()); JSONArray msgs = new JSONArray(); msgs.put(msg); out.put("messages", msgs); } return out; }
From source file:org.collectionspace.chain.csp.webui.record.RecordSearchList.java
/** * This function is the general function that calls the correct funtions to * get all the data that the UI requested and get it in the correct format * for the UI.// w w w . j a v a2 s. c o m * * @param {Storage} storage The type of storage requested (e.g. * RecordStorage, AuthorizationStorage,...) * @param {UIRequest} ui The request from the ui to which we send a * response. * @param {String} param If a querystring has been added to the * URL(e.g.'?query='), it will be in this param * @param {String} pageSize The amount of results per page requested. * @param {String} pageNum The amount of pages requested. * @throws UIException */ private void search_or_list(Storage storage, UIRequest ui, String path) throws UIException { try { JSONObject restrictedkey = GenericSearch.setRestricted(ui, null, null, null, (mode == MODE_SEARCH), this.r); JSONObject restriction = restrictedkey.getJSONObject("restriction"); String key = restrictedkey.getString("key"); JSONObject results = getResults(ui, storage, restriction, key, path); //cache for record traverser if (results.has("pagination") && results.getJSONObject("pagination").has("separatelists")) { GenericSearch.createTraverser(ui, this.r.getID(), "", results, restriction, key, 1); } ui.sendJSONResponse(results); } catch (JSONException e) { throw new UIException("JSONException during search_or_list", e); } catch (ExistException e) { throw new UIException("ExistException during search_or_list", e); } catch (UnimplementedException e) { throw new UIException("UnimplementedException during search_or_list", e); } catch (UnderlyingStorageException x) { UIException uiexception = new UIException(x.getMessage(), x.getStatus(), x.getUrl(), x); ui.sendJSONResponse(uiexception.getJSON()); } }
From source file:org.collectionspace.chain.csp.webui.record.RecordSearchList.java
private boolean morePermissions(JSONObject permissionResults, String key) throws JSONException { boolean result = false; if (permissionResults.has("pagination")) { JSONObject pagination = permissionResults.getJSONObject("pagination"); JSONArray separatelists = pagination.getJSONArray("separatelists"); String[] permissionsList = (String[]) separatelists.get(0); ///*from w ww . ja va 2 s. c o m*/ // If the permissionsList is not empty then there still might // be another page of permissions, so we'll return true // if (permissionsList != null && permissionsList.length > 0) { result = true; } } // // Just to be safe, we'll also return true if we found items in the result list. // if (permissionResults.has(key) && permissionResults.getJSONArray(key).length() > 0) { result = true; } return result; }
From source file:org.collectionspace.chain.csp.webui.record.RecordSearchList.java
private void advancedSearch(Storage storage, UIRequest ui, String path, JSONObject params) throws UIException { try {//from ww w. j a v a 2 s. c om JSONObject results = new JSONObject(); JSONObject restrictedkey = GenericSearch.setRestricted(ui, null, null, null, true, this.r); JSONObject restriction = restrictedkey.getJSONObject("restriction"); String key = restrictedkey.getString("key"); GenericSearch.buildQuery(this.r, params, restriction); key = "results"; results = getJSON(storage, restriction, key, base); //cache for record traverser if (results.has("pagination") && results.getJSONObject("pagination").has("separatelists")) { GenericSearch.createTraverser(ui, this.r.getID(), "", results, restriction, key, 1); } ui.sendJSONResponse(results); } catch (JSONException e) { throw new UIException("JSONException during advancedSearch " + e.getMessage(), e); } catch (ExistException e) { throw new UIException("ExistException during search_or_list", e); } catch (UnimplementedException e) { throw new UIException("UnimplementedException during search_or_list", e); } catch (UnderlyingStorageException x) { UIException uiexception = new UIException(x.getMessage(), x.getStatus(), x.getUrl(), x); ui.sendJSONResponse(uiexception.getJSON()); } }