List of usage examples for org.json JSONObject keys
public Iterator keys()
From source file:config.Manejador.java
public boolean deleteIntoArray(JSONObject criteria, JSONObject target) throws JSONException, IOException { boolean retorno = false; JSONObject js_obj = new JSONObject(this.src_archivo); JSONArray js_array = (JSONArray) js_obj.get(this.nom_coleccion); System.out.println(criteria.toString(4)); if (criteria.has("idx")) { int idx_registro = criteria.getInt("idx"); int idx_arr_obj = 0; JSONObject registro = js_array.getJSONObject(idx_registro); JSONArray arr_registro, arr_criteria; JSONObject obj_arr_criteria;//from w ww .j ava 2 s.c om Iterator it_target = target.keys(); if (it_target.hasNext()) { String key = it_target.next().toString(); arr_registro = registro.getJSONArray(key); arr_criteria = criteria.getJSONArray(key); obj_arr_criteria = arr_criteria.getJSONObject(0); idx_arr_obj = obj_arr_criteria.getInt("idx"); arr_registro.remove(idx_arr_obj); registro.put(key, arr_registro); js_array.put(idx_registro, registro); js_obj.put(this.nom_coleccion, js_array); retorno = true; this.src_archivo = js_obj.toString(4); this.saveFile(); } } return retorno; }
From source file:com.dwdesign.tweetings.util.Utils.java
public static Bundle parseArguments(final String string) { final Bundle bundle = new Bundle(); if (string != null) { try {// w ww. j a v a2 s.c o m final JSONObject json = new JSONObject(string); final Iterator<?> it = json.keys(); while (it.hasNext()) { final Object key_obj = it.next(); if (key_obj == null) { continue; } final String key = key_obj.toString(); final Object value = json.get(key); if (value instanceof Boolean) { bundle.putBoolean(key, json.getBoolean(key)); } else if (value instanceof Integer) { // Simple workaround for account_id if (INTENT_KEY_ACCOUNT_ID.equals(key)) { bundle.putLong(key, json.getLong(key)); } else { bundle.putInt(key, json.getInt(key)); } } else if (value instanceof Long) { bundle.putLong(key, json.getLong(key)); } else if (value instanceof String) { bundle.putString(key, json.getString(key)); } else { Log.w(LOGTAG, "Unknown type " + value.getClass().getSimpleName() + " in arguments key " + key); } } } catch (final JSONException e) { e.printStackTrace(); } catch (final ClassCastException e) { e.printStackTrace(); } } return bundle; }
From source file:org.collectionspace.chain.csp.persistence.services.GenericStorage.java
/** * update the item/*from w w w . j a v a 2 s. c o m*/ * @param root * @param creds * @param cache * @param filePath * @param jsonObject * @param thisr * @param serviceurl * @throws ExistException * @throws UnimplementedException * @throws UnderlyingStorageException */ public void updateJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache, String filePath, JSONObject jsonObject, JSONObject restrictions, Record thisr, String serviceurl) throws ExistException, UnimplementedException, UnderlyingStorageException { try { Map<String, Document> parts = new HashMap<String, Document>(); Document doc = null; for (String section : thisr.getServicesRecordPathKeys()) { String path = thisr.getServicesRecordPath(section); String[] record_path = path.split(":", 2); doc = XmlJsonConversion.convertToXml(thisr, jsonObject, section, "PUT"); if (doc != null) { parts.put(record_path[0], doc); // log.info(doc.asXML()); } } // This checks for hierarchy support, and does nothing if not appropriate. handleHierarchyPayloadSend(thisr, parts, jsonObject, filePath); int status = 0; if (thisr.isMultipart()) { String restrictedPath = getRestrictedPath(serviceurl, filePath, restrictions, null); ReturnedMultipartDocument docm = conn.getMultipartXMLDocument(RequestMethod.PUT, restrictedPath, parts, creds, cache); status = docm.getStatus(); } else { ReturnedDocument docm = conn.getXMLDocument(RequestMethod.PUT, serviceurl + filePath, doc, creds, cache); status = docm.getStatus(); } //XXX Completely untested subrecord update for (FieldSet fs : thisr.getAllSubRecords("PUT")) { Record sr = fs.usesRecordId(); if (sr.isRealRecord()) {//only deal with ones which are separate Records in the services //get list of existing subrecords JSONObject toDeleteList = new JSONObject(); JSONObject toUpdateList = new JSONObject(); JSONArray toCreateList = new JSONArray(); String getPath = serviceurl + filePath + "/" + sr.getServicesURL(); Integer subcount = 0; String firstfile = ""; String[] filepaths = null; while (!getPath.equals("")) { JSONObject data = getListView(creds, cache, getPath, sr.getServicesListPath(), "csid", false, sr); filepaths = (String[]) data.get("listItems"); subcount += filepaths.length; if (firstfile.equals("") && subcount != 0) { firstfile = filepaths[0]; } // need to paginate // if(sr.getID().equals("termlistitem")) for (String uri : filepaths) { String path = uri; if (path != null && path.startsWith("/")) { path = path.substring(1); } toDeleteList.put(path, "original"); } if (data.has("pagination")) { Integer ps = Integer.valueOf(data.getJSONObject("pagination").getString("pageSize")); Integer pn = Integer.valueOf(data.getJSONObject("pagination").getString("pageNum")); Integer ti = Integer.valueOf(data.getJSONObject("pagination").getString("totalItems")); if (ti > (ps * (pn + 1))) { JSONObject pgRestrictions = new JSONObject(); pgRestrictions.put("pageSize", Integer.toString(ps)); pgRestrictions.put("pageNum", Integer.toString(pn + 1)); getPath = getRestrictedPath(getPath, pgRestrictions, sr.getServicesSearchKeyword(), "", false, ""); // need more values } else { getPath = ""; } } } //how does that compare to what we need if (sr.isType("authority")) { //XXX need to use configuredVocabStorage } else { if (fs instanceof Field) { JSONObject subdata = new JSONObject(); //loop thr jsonObject and find the fields I need for (FieldSet subfs : sr.getAllFieldTopLevel("PUT")) { String key = subfs.getID(); if (jsonObject.has(key)) { subdata.put(key, jsonObject.get(key)); } } if (subcount == 0) { //create toCreateList.put(subdata); } else { //update - there should only be one String firstcsid = firstfile; toUpdateList.put(firstcsid, subdata); toDeleteList.remove(firstcsid); } } else if (fs instanceof Group) {//JSONObject //do we have a csid //subrecorddata.put(value); if (jsonObject.has(fs.getID())) { Object subdata = jsonObject.get(fs.getID()); if (subdata instanceof JSONObject) { if (((JSONObject) subdata).has("_subrecordcsid")) { String thiscsid = ((JSONObject) subdata).getString("_subrecordcsid"); //update if (toDeleteList.has(thiscsid)) { toUpdateList.put(thiscsid, (JSONObject) subdata); toDeleteList.remove(thiscsid); } else { //something has gone wrong... best just create it from scratch toCreateList.put(subdata); } } else { //create toCreateList.put(subdata); } } } } else {//JSONArray Repeat //need to find if we have csid's for each one if (jsonObject.has(fs.getID())) { Object subdata = jsonObject.get(fs.getID()); if (subdata instanceof JSONArray) { JSONArray subarray = (JSONArray) subdata; for (int i = 0; i < subarray.length(); i++) { JSONObject subrecord = subarray.getJSONObject(i); if (subrecord.has("_subrecordcsid") == true) { String thiscsid = subrecord.getString("_subrecordcsid"); // update if (toDeleteList.has(thiscsid)) { toUpdateList.put(thiscsid, subrecord); toDeleteList.remove(thiscsid); } else { // something has gone wrong... no existing records match the CSID being passed in, so // we will try to create a new record. Could fail if a record with the same short ID already exists toCreateList.put(subrecord); } } else if (subrecord.has("shortIdentifier") == true) { String thisShortID = subrecord.getString("shortIdentifier"); // update String thiscsid = lookupCsid(cache, filepaths, serviceurl, thisShortID); // See if we can find a matching short ID in the current list of items if (thiscsid != null) { toUpdateList.put(thiscsid, subrecord); toDeleteList.remove(thiscsid); } else { // // Since we couldn't find an existing record with that short ID, we need to create it. // toCreateList.put(subrecord); } } else { // create since we couldn't look for existing records via CSID or Short ID toCreateList.put(subrecord); } } } } } String savePath = serviceurl + filePath + "/" + sr.getServicesURL() + "/"; //do delete JSONObject existingcsid = new JSONObject(); Iterator<String> rit = toDeleteList.keys(); while (rit.hasNext()) { String key = rit.next(); deleteJSON(root, creds, cache, key, savePath, sr); // will fail if this record is a term having active references -i.e., one or more non-deleted records reference it. } //do update JSONObject updatecsid = new JSONObject(); Iterator<String> keys = toUpdateList.keys(); while (keys.hasNext()) { String key = keys.next(); JSONObject value = toUpdateList.getJSONObject(key); JSONObject subrRestrictions = new JSONObject(); updateJSON(root, creds, cache, key, value, subrRestrictions, sr, savePath); } //do create JSONArray createcsid = new JSONArray(); for (int i = 0; i < toCreateList.length(); i++) { JSONObject value = toCreateList.getJSONObject(i); subautocreateJSON(root, creds, cache, sr, value, savePath); } } } } //if(status==404) // throw new ExistException("Not found: "+serviceurl+filePath); if (status > 299 || status < 200) throw new UnderlyingStorageException("Bad response ", status, serviceurl + filePath); } catch (ConnectionException e) { throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e.getStatus(), e.getUrl(), e); } catch (JSONException e) { throw new UnimplementedException("JSONException", e); } catch (UnsupportedEncodingException e) { throw new UnimplementedException("UnsupportedEncodingException", e); } }
From source file:net.oauth.consumer.OAuth2Consumer.java
private synchronized Map<String, String> parseJSONObject(JSONObject json) throws JSONException { Map<String, String> parameters = null; if (json != null && json.length() > 0) { parameters = new LinkedHashMap<String, String>(); @SuppressWarnings("unchecked") Iterator<String> iter = json.keys(); if (iter != null) { while (iter.hasNext()) { String key = iter.next(); parameters.put(key, json.getString(key)); }// www . jav a2s .co m } } return parameters; }
From source file:notaql.performance.PerformanceTest.java
private static String composeEngine(JSONObject engine) { final StringBuilder builder = new StringBuilder(); builder.append(engine.get("engine")); builder.append("("); final String params = StreamSupport .stream(Spliterators.spliteratorUnknownSize(engine.keys(), Spliterator.ORDERED), false) .filter(k -> !k.equals("engine")).map(k -> k + " <- " + toArg(k, engine)) .collect(Collectors.joining(", ")); builder.append(params);/*from w w w. j a va 2s .co m*/ builder.append(")"); return builder.toString(); }
From source file:com.inbeacon.cordova.CordovaInbeaconManager.java
private void attachUser(final JSONObject kwargs, final CallbackContext callbackContext) { // kwargs keys can be: // name, email, customerid, address, gender, zip, city, country, birth, phone_mobile, // phone_home, phone_work, social_facebook_id, social_twitter_id, social_linkedin_id cordova.getThreadPool().execute(new Runnable() { public void run() { HashMap<String, String> user = new HashMap<String, String>(); for (Iterator<String> iter = kwargs.keys(); iter.hasNext();) { String key = iter.next(); try { user.put(key, kwargs.getString(key)); } catch (JSONException e) { callbackContext.error("Invalid user info: " + e.toString()); }/*from w w w . ja v a2 s . co m*/ } InbeaconManager.getSharedInstance().attachUser(user); callbackContext.success(); } }); }
From source file:org.emergent.android.weave.syncadapter.SyncCache.java
/** * In://from w w w. j a v a2s . co m * <p/> * <pre> * { * "id":"global" * "modified": 1.28702415227E9 * "payload": * {"syncID":"JnvqPEn(6~", * "storageVersion":3, * "engines":{"clients":{"version":1,"syncID":"LwjtCQjdsV"}, * "bookmarks":{"version":1,"syncID":"ApPN6v8VY4"}, * "forms":{"version":1,"syncID":"UKeuhB.aOZ"}, * "tabs":{"version":1,"syncID":"G!nU*7H.7j"}, * "history":{"version":1,"syncID":"9Tvy_Vlb44"}, * "passwords":{"version":1,"syncID":"yfBi2v7Pp)"}, * "prefs":{"version":1,"syncID":"*eONx!6GXA"}}} * } * </pre> * <p/> * Out: * <pre> * syncID : ... * storageVersion : ... * clients.version : ... * clients.syncID : ... * ... * </pre> * * @param mgObj * @return */ private static Properties convertMetaGlobalToFlatProperties(JSONObject mgObj) { Properties retval = new Properties(); try { // Log.w(TAG, "mgObj: " + mgObj.toString(2)); JSONObject payload = new JSONObject(String.valueOf(mgObj.get("payload"))); transferIfExists(retval, payload, "syncID", null); transferIfExists(retval, payload, "storageVersion", null); if (payload.has("engines")) { JSONObject enginesObj = payload.getJSONObject("engines"); // Log.w(TAG, "engObj: " + enginesObj.toString(2)); for (Iterator iter = enginesObj.keys(); iter.hasNext();) { String engName = (String) iter.next(); // Log.w(TAG, "engName: " + engName); JSONObject engObj = enginesObj.getJSONObject(engName); transferIfExists(retval, engObj, "syncID", engName + "."); transferIfExists(retval, engObj, "version", engName + "."); } } } catch (JSONException e) { Log.w(TAG, e); } return retval; }
From source file:io.selendroid.SelendroidCapabilities.java
public SelendroidCapabilities(JSONObject source) throws JSONException { Iterator<String> iter = source.keys(); while (iter.hasNext()) { String key = iter.next(); Object value = source.get(key); setCapability(key, decode(value)); }//from ww w . ja v a 2 s. c o m if (source.has(CapabilityType.BROWSER_NAME) && !source.has(AUT)) { setAut(source.getString(CapabilityType.BROWSER_NAME)); } }
From source file:ai.susi.server.api.vis.PieChartServlet.java
public JFreeChart getChart(JSONObject jsonData, boolean legendBit, boolean tooltipBit) { DefaultPieDataset dataset = new DefaultPieDataset(); Iterator<String> iter = jsonData.keys(); while (iter.hasNext()) { String keyData = iter.next(); Float value = Float.parseFloat(jsonData.getString(keyData)); dataset.setValue(keyData, value); }/*from ww w .j ava2 s. c o m*/ boolean legend = legendBit; boolean tooltips = tooltipBit; boolean urls = false; JFreeChart chart = ChartFactory.createPieChart("Loklak Visualizes - PieChart", dataset, legend, tooltips, urls); chart.setBorderPaint(Color.BLACK); chart.setBorderStroke(new BasicStroke(5.0f)); chart.setBorderVisible(true); return chart; }
From source file:com.QuarkLabs.BTCeClient.services.CheckTickersService.java
@Override protected void onHandleIntent(Intent intent) { SharedPreferences sh = PreferenceManager.getDefaultSharedPreferences(this); Set<String> x = sh.getStringSet("PairsToDisplay", new HashSet<String>()); if (x.size() == 0) { return;//from ww w. ja va2 s . c om } String[] pairs = x.toArray(new String[x.size()]); ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); String url = BASE_URL; for (String xx : pairs) { url += xx.replace("/", "_").toLowerCase(Locale.US) + "-"; } SimpleRequest reqSim = new SimpleRequest(); if (networkInfo != null && networkInfo.isConnected()) { JSONObject data = null; try { data = reqSim.makeRequest(url); } catch (JSONException e) { e.printStackTrace(); } if (data != null && data.optInt("success", 1) != 0) { ArrayList<Ticker> tickers = new ArrayList<>(); for (@SuppressWarnings("unchecked") Iterator<String> iterator = data.keys(); iterator.hasNext();) { String key = iterator.next(); JSONObject pairData = data.optJSONObject(key); Ticker ticker = new Ticker(key); ticker.setUpdated(pairData.optLong("updated")); ticker.setAvg(pairData.optDouble("avg")); ticker.setBuy(pairData.optDouble("buy")); ticker.setSell(pairData.optDouble("sell")); ticker.setHigh(pairData.optDouble("high")); ticker.setLast(pairData.optDouble("last")); ticker.setLow(pairData.optDouble("low")); ticker.setVol(pairData.optDouble("vol")); ticker.setVolCur(pairData.optDouble("vol_cur")); tickers.add(ticker); } String message = checkNotifiers(tickers, TickersStorage.loadLatestData()); if (message.length() != 0) { NotificationManager notificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE); NotificationCompat.Builder nb = new NotificationCompat.Builder(this) .setContentTitle(getResources().getString(R.string.app_name)) .setSmallIcon(R.drawable.ic_stat_bitcoin_sign) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setContentText(message.substring(0, message.length() - 2)); notificationManager.notify(ConstantHolder.ALARM_NOTIF_ID, nb.build()); } Map<String, Ticker> newData = new HashMap<>(); for (Ticker ticker : tickers) { newData.put(ticker.getPair(), ticker); } TickersStorage.saveData(newData); LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("UpdateTickers")); } } else { new Handler().post(new Runnable() { @Override public void run() { //Toast.makeText(CheckTickersService.this, "Unable to fetch data", Toast.LENGTH_SHORT).show(); } }); } }