List of usage examples for org.json JSONObject getString
public String getString(String key) throws JSONException
From source file:com.samsung.locator.SamiActivity.java
/** * Connects to /live websocket if necessary *///from www. j a v a 2 s. c o m private void connectLiveWebsocket() { if (live == null) { live = new Websocket(); } if (!live.isConnected() && !live.isConnecting()) { live.connect(Config.LIVE_URL, new WebsocketEvents() { @Override public void onOpen(ServerHandshake handshakedata) { setLiveText("Live connected to from SAMI!"); } @Override public void onMessage(String message) { setLiveText("Live onMessage(): " + message); try { JSONObject json = new JSONObject(message); JSONObject dataNode = json.optJSONObject("data"); if (dataNode != null) { lastLat = dataNode.getString("lat"); lastLng = dataNode.getString("lng"); } } catch (JSONException e) { // This message doesn't contain data node, might be a ping. } } @Override public void onClose(int code, String reason, boolean remote) { setLiveText("Live closed: " + code); } @Override public void onError(Exception ex) { setLiveText("Live error: " + ex.getMessage()); } }); } }
From source file:com.quantcast.measurement.service.QCLocation.java
private MeasurementLocation parseJson(String jsonString) throws JSONException { JSONObject json = new JSONObject(jsonString); if (OK.equals(json.optString(STATUS))) { JSONArray resultsArray = json.optJSONArray(RESULTS); if (resultsArray != null) { JSONArray addressComponents; for (int i = 0; i < resultsArray.length(); i++) { addressComponents = resultsArray.getJSONObject(i).optJSONArray(ADDRESS); if (addressComponents != null) { String country = "", locality = "", state = "", postalCode = ""; for (int j = 0; j < addressComponents.length(); j++) { JSONObject obj = addressComponents.getJSONObject(j); JSONArray types = obj.optJSONArray(TYPES); if (types != null) { if (containsString(types, LOCALITY)) locality = obj.getString(SHORT_NAME); if (containsString(types, STATE)) state = obj.getString(SHORT_NAME); if (containsString(types, COUNTRY)) country = obj.getString(SHORT_NAME); if (containsString(types, POSTAL_CODE)) postalCode = obj.getString(SHORT_NAME); }//from w ww . java 2 s . co m } return new MeasurementLocation(country, state, locality, postalCode); } } } } return null; }
From source file:org.smilec.smile.bu.json.CurrentMessageJSONParser.java
public static final String getStatus(InputStream is) throws DataAccessException { String s;//from www. j av a 2 s. c o m try { s = IOUtil.loadContent(is, ENCODING); JSONObject json = new JSONObject(s); String type = ""; if (!json.toString().equals("{}")) { type = json.getString(TYPE); } return type; } catch (IOException e) { throw new DataAccessException(e); } catch (JSONException e) { throw new DataAccessException(e); } }
From source file:de.kp.ames.web.function.domain.model.ServiceObject.java
/** * Create ServiceObject from JSON representation * // ww w . j ava 2s . com * @param jForm * @return * @throws Exception */ public RegistryObjectImpl create(JSONObject jForm) throws Exception { /* * Create SpecificationLink instances */ JSONArray jSpecifications = new JSONArray(jForm.getString(RIM_SPEC)); ArrayList<SpecificationLinkImpl> specificationLinks = new ArrayList<SpecificationLinkImpl>(); for (int i = 0; i < jSpecifications.length(); i++) { JSONObject jSpecification = jSpecifications.getJSONObject(i); String uid = jSpecification.getString(RIM_ID); String seqNo = jSpecification.getString(RIM_SEQNO); RegistryObjectImpl ro = jaxrLCM.getRegistryObjectById(uid); if (ro == null) throw new Exception("[ServiceObject] RegistryObject with id <" + uid + "> does not exist."); /* * Create a new specification link */ SpecificationLinkImpl specificationLink = jaxrLCM.createSpecificationLink(); if (specificationLink == null) throw new Exception("[ServiceObject] Creation of SpecificationLink failed."); SlotImpl slot = jaxrLCM.createSlot(JaxrConstants.SLOT_SEQNO, seqNo, JaxrConstants.SLOT_TYPE); specificationLink.addSlot(slot); specificationLink.setSpecificationObject(ro); specificationLinks.add(specificationLink); } /* * Create ServiceBinding instance */ ServiceBindingImpl serviceBinding = null; if (specificationLinks.isEmpty() == false) { serviceBinding = jaxrLCM.createServiceBinding(); serviceBinding.addSpecificationLinks(specificationLinks); } /* * Create Service instance */ ServiceImpl service = jaxrLCM.createService(jForm.getString(RIM_NAME)); if (jForm.has(RIM_DESC)) service.setDescription(jaxrLCM.createInternationalString(jForm.getString(RIM_DESC))); service.setHome(jaxrHandle.getEndpoint().replace("/saml", "")); if (serviceBinding != null) service.addServiceBinding(serviceBinding); /* * Create classifications */ JSONArray jClases = jForm.has(RIM_CLAS) ? new JSONArray(jForm.getString(RIM_CLAS)) : null; if (jClases != null) { List<ClassificationImpl> classifications = createClassifications(jClases); /* * Set composed object */ service.addClassifications(classifications); } /* * Create slots */ JSONObject jSlots = jForm.has(RIM_SLOT) ? new JSONObject(jForm.getString(RIM_SLOT)) : null; if (jSlots != null) { List<SlotImpl> slots = createSlots(jSlots); /* * Set composed object */ service.addSlots(slots); } /* * Indicate as created */ this.created = true; return service; }
From source file:de.kp.ames.web.function.domain.model.ServiceObject.java
/** * Update ServiceObject from JSON representation * // w w w. j a v a 2 s . co m * @param jForm * @return * @throws Exception */ public RegistryObjectImpl update(JSONObject jForm) throws Exception { /* * Determine service from unique identifier */ String sid = jForm.getString(RIM_ID); ServiceImpl service = (ServiceImpl) jaxrLCM.getRegistryObjectById(sid); if (service == null) throw new Exception("[ServiceObject] RegistryObject with id <" + sid + "> does not exist."); /* * Remove service binding and associated specification links */ Collection<?> bindings = service.getServiceBindings(); if (bindings.isEmpty() == false) service.removeServiceBindings(bindings); /* * SpecificationLink instances */ JSONArray jSpecifications = new JSONArray(jForm.getString(RIM_SPEC)); ArrayList<SpecificationLinkImpl> specificationLinks = new ArrayList<SpecificationLinkImpl>(); for (int i = 0; i < jSpecifications.length(); i++) { JSONObject jSpecification = jSpecifications.getJSONObject(i); String uid = jSpecification.getString(RIM_ID); String seqNo = jSpecification.getString(RIM_SEQNO); RegistryObjectImpl ro = jaxrLCM.getRegistryObjectById(uid); if (ro == null) throw new Exception("[ServiceObject] RegistryObject with id <" + uid + "> does not exist."); /* * Create a new specification link */ SpecificationLinkImpl specificationLink = jaxrLCM.createSpecificationLink(); if (specificationLink == null) throw new Exception("[ServiceObject] Creation of SpecificationLink failed."); SlotImpl slot = jaxrLCM.createSlot(JaxrConstants.SLOT_SEQNO, seqNo, JaxrConstants.SLOT_TYPE); specificationLink.addSlot(slot); specificationLink.setSpecificationObject(ro); specificationLinks.add(specificationLink); } /* * Create ServiceBinding instance */ ServiceBindingImpl serviceBinding = null; if (specificationLinks.isEmpty() == false) { serviceBinding = jaxrLCM.createServiceBinding(); serviceBinding.addSpecificationLinks(specificationLinks); } if (serviceBinding != null) service.addServiceBinding(serviceBinding); /* * Update core metadata */ updateMetadata(service, jForm); // /* // * Name & description // */ // if (jForm.has(RIM_NAME)) service.setName(jaxrLCM.createInternationalString(jForm.getString(RIM_NAME))); // if (jForm.has(RIM_DESC)) service.setDescription(jaxrLCM.createInternationalString(jForm.getString(RIM_DESC))); // // /* // * Update slots // */ // JSONObject jSlots = jForm.has(RIM_SLOT) ? new JSONObject(jForm.getString(RIM_SLOT)) : null; // if (jSlots != null) { // // List<SlotImpl> slots = updateSlots(service, jSlots); // /* // * Set composed object // */ // service.addSlots(slots); // // } /* * Indicate as updated */ this.created = false; return service; }
From source file:org.seadpdt.impl.SearchServiceImpl.java
@POST @Path("/") @Consumes(MediaType.APPLICATION_JSON)/*from ww w . j ava2s. c om*/ @Produces(MediaType.APPLICATION_JSON) public Response getFilteredListOfROs(String filterString, @QueryParam("repo") String repoName) { JSONObject filter = new JSONObject(filterString); String creator = filter.getString("Creator"); String startDate = filter.getString("Start Date"); String endDate = filter.getString("End Date"); String searchString = filter.getString("Search String"); String title = filter.getString("Title"); // query Document query; if (repoName != null) { query = createPublishedFilter().append("Repository", repoName); } else { query = createPublishedFilter(); } if (searchString != null && !"".equals(searchString)) { // doing a text search in entire RO using the given search string query = query.append("$text", new Document("$search", "\"" + searchString + "\"")); } if (title != null && !"".equals(title)) { // regex for title query = query.append("Aggregation.Title", new Document("$regex", title).append("$options", "i")); } Date start = null; Date end = null; try { if (startDate != null && !"".equals(startDate)) { start = simpleDateFormat.parse(startDate); } if (endDate != null && !"".equals(endDate)) { end = simpleDateFormat.parse(endDate); } } catch (Exception e) { e.printStackTrace(); // ignore } return getAllPublishedROs(query, start, end, "(?i)(.*)" + creator + "(.*)"); }
From source file:org.seadpdt.impl.SearchServiceImpl.java
private String getPersonName(String creator) { String personProfile = getPersonProfile(creator); if (personProfile == null) { return removeVivo(creator); } else {/*from w w w .j a va2s . c om*/ JSONObject profile = new JSONObject(personProfile); String givenName = profile.getString("givenName"); String familyName = profile.getString("familyName"); if (givenName == null && familyName == null) { return creator; } String fullName = (givenName == null ? "" : givenName) + " " + (familyName == null ? "" : familyName); return fullName.trim(); } }
From source file:com.gvccracing.android.tttimer.Tabs.RaceInfoTab.java
public void postData() { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( "http://www.gvccracing.com/?page_id=2525&pass=com.gvccracing.android.tttimer"); try {// w ww . ja va 2s . c o m // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); InputStream is = response.getEntity().getContent(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(20); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } /* Convert the Bytes read to a String. */ String text = new String(baf.toByteArray()); JSONObject mainJson = new JSONObject(text); JSONArray jsonArray = mainJson.getJSONArray("members"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); String firstName = json.getString("fname"); String lastName = json.getString("lname"); String licenseStr = json.getString("license"); Integer license = 0; try { license = Integer.parseInt(licenseStr); } catch (Exception ex) { Log.e(LOG_TAG(), "Unable to parse license string"); } long age = json.getLong("age"); String categoryStr = json.getString("category"); Integer category = 5; try { category = Integer.parseInt(categoryStr); } catch (Exception ex) { Log.e(LOG_TAG(), "Unable to parse category string"); } String phone = json.getString("phone"); long phoneNumber = 0; try { phoneNumber = Long.parseLong(phone.replace("-", "").replace("(", "").replace(")", "") .replace(" ", "").replace(".", "").replace("*", "")); } catch (Exception e) { Log.e(LOG_TAG(), "Unable to parse phone number"); } String gender = json.getString("gender"); String econtact = json.getString("econtact"); String econtactPhone = json.getString("econtact_phone"); long eContactPhoneNumber = 0; try { eContactPhoneNumber = Long.parseLong(econtactPhone.replace("-", "").replace("(", "") .replace(")", "").replace(" ", "").replace(".", "").replace("*", "")); } catch (Exception e) { Log.e(LOG_TAG(), "Unable to parse econtact phone number"); } Long member_id = json.getLong("member_id"); String gvccCategory; switch (category) { case 1: case 2: case 3: gvccCategory = "A"; break; case 4: gvccCategory = "B4"; break; case 5: gvccCategory = "B5"; break; default: gvccCategory = "B5"; break; } Log.w(LOG_TAG(), lastName); Cursor racerInfo = Racer.Instance().Read(getActivity(), new String[] { Racer._ID, Racer.FirstName, Racer.LastName, Racer.USACNumber, Racer.PhoneNumber, Racer.EmergencyContactName, Racer.EmergencyContactPhoneNumber }, Racer.USACNumber + "=?", new String[] { license.toString() }, null); if (racerInfo.getCount() > 0) { racerInfo.moveToFirst(); Long racerID = racerInfo.getLong(racerInfo.getColumnIndex(Racer._ID)); Racer.Instance().Update(getActivity(), racerID, firstName, lastName, license, 0l, phoneNumber, econtact, eContactPhoneNumber, gender); Cursor racerClubInfo = RacerClubInfo.Instance().Read(getActivity(), new String[] { RacerClubInfo._ID, RacerClubInfo.GVCCID, RacerClubInfo.RacerAge, RacerClubInfo.Category }, RacerClubInfo.Racer_ID + "=? AND " + RacerClubInfo.Year + "=? AND " + RacerClubInfo.Upgraded + "=?", new String[] { racerID.toString(), "2013", "0" }, null); if (racerClubInfo.getCount() > 0) { racerClubInfo.moveToFirst(); long racerClubInfoID = racerClubInfo .getLong(racerClubInfo.getColumnIndex(RacerClubInfo._ID)); String rciCategory = racerClubInfo .getString(racerClubInfo.getColumnIndex(RacerClubInfo.Category)); boolean upgraded = gvccCategory != rciCategory; if (upgraded) { RacerClubInfo.Instance().Update(getActivity(), racerClubInfoID, null, null, null, null, null, null, null, null, null, upgraded); RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0, 0, age, member_id, false); } else { RacerClubInfo.Instance().Update(getActivity(), racerClubInfoID, null, null, null, null, null, null, null, age, member_id, upgraded); } } else { RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0, 0, age, member_id, false); } if (racerClubInfo != null) { racerClubInfo.close(); } } else { // TODO: Better birth date Uri resultUri = Racer.Instance().Create(getActivity(), firstName, lastName, license, 0l, phoneNumber, econtact, eContactPhoneNumber, gender); long racerID = Long.parseLong(resultUri.getLastPathSegment()); RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0, 0, age, member_id, false); } if (racerInfo != null) { racerInfo.close(); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { Log.e(LOG_TAG(), e.getMessage()); } }
From source file:com.namelessdev.mpdroid.cover.ItunesCover.java
@Override public String[] getCoverUrl(final AlbumInfo albumInfo) throws Exception { final String response; final JSONObject jsonRootObject; final JSONArray jsonArray; String coverUrl;//from ww w . ja v a2s .c om JSONObject jsonObject; try { response = executeGetRequest("https://itunes.apple.com/search?term=" + albumInfo.getAlbum() + ' ' + albumInfo.getArtist() + "&limit=5&media=music&entity=album"); jsonRootObject = new JSONObject(response); jsonArray = jsonRootObject.getJSONArray("results"); for (int i = 0; i < jsonArray.length(); i++) { jsonObject = jsonArray.getJSONObject(i); coverUrl = jsonObject.getString("artworkUrl100"); if (coverUrl != null) { // Based on some tests even if the cover art size returned // is 100x100 // Bigger versions also exists. return new String[] { coverUrl.replace("100x100", "600x600") }; } } } catch (final Exception e) { if (CoverManager.DEBUG) { Log.e(TAG, "Failed to get cover URL from " + getName(), e); } } return new String[0]; }
From source file:com.google.testing.testify.risk.frontend.server.task.UploadDataTask.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) { String user = req.getParameter("user"); String jsonString = req.getParameter("json"); try {//from w w w . j a va 2 s. c o m // TODO(jimr): add impersonation of user in string user. JSONObject json = new JSONObject(jsonString); JSONObject item; if (json.has("bug")) { item = json.getJSONObject("bug"); Bug bug = new Bug(); bug.setParentProjectId(item.getLong("projectId")); bug.setExternalId(item.getLong("bugId")); bug.setTitle(item.getString("title")); bug.setPath(item.getString("path")); bug.setSeverity(item.getLong("severity")); bug.setPriority(item.getLong("priority")); bug.setBugGroups(Sets.newHashSet(StringUtil.csvToList(item.getString("groups")))); bug.setBugUrl(item.getString("url")); bug.setState(item.getString("status")); bug.setStateDate(item.getLong("statusDate")); dataService.addBug(bug); } else if (json.has("test")) { item = json.getJSONObject("test"); TestCase test = new TestCase(); test.setParentProjectId(item.getLong("projectId")); test.setExternalId(item.getLong("testId")); test.setTitle(item.getString("title")); test.setTags(Sets.newHashSet(StringUtil.csvToList(item.getString("tags")))); test.setTestCaseUrl(item.getString("url")); test.setState(item.getString("result")); test.setStateDate(item.getLong("resultDate")); dataService.addTestCase(test); } else if (json.has("checkin")) { item = json.getJSONObject("checkin"); Checkin checkin = new Checkin(); checkin.setParentProjectId(item.getLong("projectId")); checkin.setExternalId(item.getLong("checkinId")); checkin.setSummary(item.getString("summary")); checkin.setDirectoriesTouched(Sets.newHashSet(StringUtil.csvToList(item.getString("directories")))); checkin.setChangeUrl(item.getString("url")); checkin.setState(item.getString("state")); checkin.setStateDate(item.getLong("stateDate")); dataService.addCheckin(checkin); } else { LOG.severe("No applicable data found for json: " + json.toString()); } } catch (JSONException e) { // We don't issue a 500 or similar response code here to prevent retries, which would have // no different a result. LOG.severe("Couldn't parse input JSON: " + jsonString); return; } }