List of usage examples for org.json JSONObject remove
public Object remove(String key)
From source file:de.jaetzold.philips.hue.HueBridge.java
/** * Returns all lights found at the last search for new lights. * If the returned list is empty it can mean that no scan has been performed, no new lights have been discovered or a scan is currently active. * Whether a scan was active at the last call to this method can be queried by calling {@link #isScanActive()}. * * See <a href="http://developers.meethue.com/1_lightsapi.html#12_get_new_lights">Philips hue API, Section 1.2</a> for further reference. *//*w w w.jav a2 s . c o m*/ public Collection<? extends HueLightBulb> getNewLights() { final List<JSONObject> response = request(GET, "/lights/new", ""); final JSONObject lightsJson = response.get(0); final String lastscan = (String) lightsJson.remove("lastscan"); scanActive = lastscan.equals("active"); parseLights(lightsJson); final ArrayList<HueLightBulb> result = new ArrayList<>(); for (Object key : lightsJson.keySet()) { Integer lightId = null; try { lightId = Integer.parseInt((String) key); } catch (Exception e) { } if (lightId != null) { final HueLightBulb light = getLight(lightId); if (light == null) { throw new IllegalStateException( "For some reason the new light is not available... probable bug?"); } result.add(light); } } return result; }
From source file:com.rapid.actions.Logic.java
@Override public String getJavaScript(RapidRequest rapidRequest, Application application, Page page, Control control, JSONObject jsonDetails) throws Exception { String js = ""; // assume we couldn't make a condition String conditionsJavaScript = "false"; // check conditions is set if (_conditions != null) { // check we have some if (_conditions.size() > 0) { // reset conditionsJavaScript conditionsJavaScript = ""; // loop them for (int i = 0; i < _conditions.size(); i++) { // add the condition conditionsJavaScript += _conditions.get(i) .getJavaScript(rapidRequest.getRapidServlet().getServletContext(), application, page); // if there is going to be another condition if (i < _conditions.size() - 1) { // add the separator if ("or".equals(_conditionsType)) { conditionsJavaScript += " || "; } else { conditionsJavaScript += " && "; }/*from w ww .jav a 2s . c om*/ } } } } // create the if statement js += "if (" + conditionsJavaScript + ") {\n"; // add any try actions if (_trueActions != null) { for (Action action : _trueActions) js += " " + action.getJavaScript(rapidRequest, application, page, control, jsonDetails).trim() .replace("\n", "\n ") + "\n"; } // close the if js += "}"; // assume no false actions boolean gotFalseActions = false; // if there is a collection if (_falseActions != null) { // if there are some in the collection we have false actions if (_falseActions.size() > 0) gotFalseActions = true; } // check for false actions if (gotFalseActions) { // add any false actions as an else js += " else {\n"; for (Action action : _falseActions) js += " " + action.getJavaScript(rapidRequest, application, page, control, jsonDetails).trim() .replace("\n", "\n ") + "\n"; js += "}"; } else { // if we got some details if (jsonDetails != null) { // check the details for a defaultErrorHandler String defaultErrorHandler = jsonDetails.optString("defaultErrorHandler", null); // if we got one if (defaultErrorHandler != null) { // print it js += " else {\n " + defaultErrorHandler + "\n}"; // remove it from the jsonObject to stop it re-appearing elsewhere jsonDetails.remove("defaultErrorHandler"); } } } // final line break js += "\n"; // return what we built return js; }
From source file:org.sleeksnap.ScreenSnapper.java
public boolean convertUploadDefinition(final JSONObject uploadConfig, final Class<?> originalClass, final Class<?> newClass) { if (uploadConfig.has(originalClass.getName())) { uploadConfig.put(newClass.getName(), uploadConfig.remove(originalClass.getName())); return true; }//from w ww . java 2 s .c o m return false; }
From source file:com.joyfulmongo.db.QueryConditionFilterGeoQuery.java
public static void adjustConstraints(JSONObject constraints) { String geoPointKey = null;/*from www . j ava2s .c o m*/ ContainerObjectGeoPoint geoPoint = null; Iterator<String> iter = constraints.keys(); while (iter.hasNext()) { String constraintKey = iter.next(); Object o = constraints.get(constraintKey); if (o instanceof JSONObject) { Object nearSphere = ((JSONObject) o).opt(S_KEY); if (nearSphere != null && nearSphere instanceof JSONObject) { ContainerObject childObj = ContainerObjectFactory.getChildObject(S_KEY, (JSONObject) nearSphere); if (childObj instanceof ContainerObjectGeoPoint) { geoPointKey = constraintKey; geoPoint = (ContainerObjectGeoPoint) childObj; break; } } } } if (geoPointKey != null && geoPoint != null) { constraints.remove(geoPointKey); JSONArray geoArray = geoPoint.to2DArray(); JSONObject nearSphereCondition = new JSONObject(); nearSphereCondition.put(S_KEY, geoArray); constraints.put(ContainerObjectGeoPoint.S_GEO_POINT, nearSphereCondition); } }
From source file:com.rapid.actions.Webservice.java
@Override public String getJavaScript(RapidRequest rapidRequest, Application application, Page page, Control control, JSONObject jsonDetails) throws Exception { String js = ""; if (_request != null) { // get the rapid servlet RapidHttpServlet rapidServlet = rapidRequest.getRapidServlet(); // get the most recent sequence number for this action to stop slow-running early requests overwriting the results of fast later requests js += "var sequence = getWebserviceActionSequence('" + getId() + "');\n"; // drop in the query variable which holds our inputs and sequence js += "var query = { inputs:[], sequence:sequence };\n"; // build the inputs if (_request.getInputs() != null) { for (Parameter parameter : _request.getInputs()) { String itemId = parameter.getItemId(); if (itemId != null) { // get any parameter field String field = parameter.getField(); // check if there was one if (field == null) { // no field js += " query.inputs.push({id:'" + itemId + "',value:" + Control.getDataJavaScript( rapidServlet.getServletContext(), application, page, itemId, null) + "});\n"; } else { // got field so let in appear in the inputs for matching later js += " query.inputs.push({id:'" + itemId + "',value:" + Control.getDataJavaScript(rapidServlet.getServletContext(), application, page, itemId, field) + ",field:'" + field + "'});\n"; }/* w w w . ja va 2 s.co m*/ } } } // got inputs // control can be null when the action is called from the page load String controlParam = ""; if (control != null) controlParam = "&c=" + control.getId(); // get the outputs ArrayList<Parameter> outputs = _request.getOutputs(); // instantiate the jsonDetails if required if (jsonDetails == null) jsonDetails = new JSONObject(); // look for a working page in the jsonDetails String workingPage = jsonDetails.optString("workingPage", null); // look for an offline page in the jsonDetails String offlinePage = jsonDetails.optString("offlinePage", null); // get the js to show the loading (if applicable) if (_showLoading) js += " " + getLoadingJS(page, outputs, true); // stringify the query js += "query = JSON.stringify(query);\n"; // open the ajax call js += "$.ajax({ url : '~?a=" + application.getId() + "&v=" + application.getVersion() + "&p=" + page.getId() + controlParam + "&act=" + getId() + "', type: 'POST', contentType: 'application/json', dataType: 'json',\n"; js += " data: query,\n"; js += " error: function(server, status, message) {\n"; // if there is a working page if (workingPage != null) { // remove any working page dialogue js += " $('#" + workingPage + "dialogue').remove();\n"; // remove any working page dialogue cover js += " $('#" + workingPage + "cover').remove();\n"; // remove the working page so as not to affect actions further down the tree } // hide the loading javascript (if applicable) if (_showLoading) js += " " + getLoadingJS(page, outputs, false); // this avoids doing the errors if the page is unloading or the back button was pressed js += " if (server.readyState > 0) {\n"; // retain if error actions boolean errorActions = false; // prepare a default error hander we'll show if no error actions, or pass to child actions for them to use String defaultErrorHandler = "alert('Error with webservice action : ' + server.responseText||message);"; // if we have an offline page if (offlinePage != null) { // update defaultErrorHandler to navigate to offline page defaultErrorHandler = "if (Action_navigate && typeof _rapidmobile != 'undefined' && !_rapidmobile.isOnline()) {\n Action_navigate('~?a=" + application.getId() + "&v=" + application.getVersion() + "&p=" + offlinePage + "&action=dialogue',true,'" + getId() + "');\n } else {\n " + defaultErrorHandler + "\n }"; // remove the offline page so we don't interfere with actions down the three jsonDetails.remove("offlinePage"); } // add any error actions if (_errorActions != null) { // count the actions int i = 0; // loop the actions for (Action action : _errorActions) { // retain that we have custom error actions errorActions = true; // if this is the last error action add in the default error handler if (i == _errorActions.size() - 1) jsonDetails.put("defaultErrorHandler", defaultErrorHandler); // add the js js += " " + action.getJavaScript(rapidRequest, application, page, control, jsonDetails) .trim().replace("\n", "\n ") + "\n"; // if this is the last error action and the default error handler is still present, remove it so it isn't sent down the success path if (i == _errorActions.size() - 1 && jsonDetails.optString("defaultErrorHandler", null) != null) jsonDetails.remove("defaultErrorHandler"); // increase the count i++; } } // add default error handler if none in collection if (!errorActions) js += " " + defaultErrorHandler + "\n"; // close unloading check js += " }\n"; // close error actions js += " },\n"; // open success function js += " success: function(data) {\n"; // get the js to hide the loading (if applicable) if (_showLoading) js += " " + getLoadingJS(page, outputs, false); // check there are outputs if (outputs != null) { if (outputs.size() > 0) { // open if data check js += " if (data) {\n"; // the outputs array we're going to make String jsOutputs = ""; // loop the output parameters for (int i = 0; i < outputs.size(); i++) { // get the parameter Parameter output = outputs.get(i); // get the control the data is going into Control outputControl = page.getControl(output.getItemId()); // try the application if still null if (outputControl == null) outputControl = application.getControl(rapidServlet.getServletContext(), output.getItemId()); // check the control is still on the page if (outputControl != null) { // get any mappings we may have String details = outputControl.getDetailsJavaScript(application, page); // set to empty string or clean up if (details == null) { details = ""; } else { details = ", details: " + details; } // append the javascript outputs jsOutputs += "{id: '" + outputControl.getId() + "', type: '" + outputControl.getType() + "', field: '" + output.getField() + "'" + details + "}"; // add a comma if not the last if (i < outputs.size() - 1) jsOutputs += ","; } } js += " var outputs = [" + jsOutputs + "];\n"; // send them them and the data to the webservice action js += " Action_webservice(ev, '" + getId() + "', data, outputs);\n"; // close if data check js += " }\n"; } } // if there is a working page (from the details) if (workingPage != null) { // remove any working page dialogue js += " $('#" + workingPage + "dialogue').remove();\n"; // remove any working page dialogue cover js += " $('#" + workingPage + "cover').remove();\n"; // remove the working page so as not to affect actions further down the tree jsonDetails.remove("workingPage"); } // add any sucess actions if (_successActions != null) { for (Action action : _successActions) { js += " " + action.getJavaScript(rapidRequest, application, page, control, jsonDetails) .trim().replace("\n", "\n ") + "\n"; } } // close success function js += " }\n"; // close ajax call js += "});"; } // return what we built return js; }
From source file:com.futureplatforms.kirin.internal.attic.ProxyGenerator.java
protected void handleSetter(JSONObject obj, String key, Object value) { if (value == null) { obj.remove(key); } else {//from w w w . jav a2 s .c o m try { obj.putOpt(key, value); } catch (JSONException e) { Log.e(C.TAG, "Problem putting " + value + " into a JSONObject with key " + key, e); } } }
From source file:org.eclipse.orion.internal.server.servlets.xfer.TransferResourceDecorator.java
private void addTransferLinks(HttpServletRequest request, URI resource, JSONObject representation) throws URISyntaxException, JSONException, UnsupportedEncodingException { URI location = new URI(representation.getString(ProtocolConstants.KEY_LOCATION)); IPath targetPath = new Path(location.getPath()).removeFirstSegments(1).removeTrailingSeparator(); IPath path = new Path("/xfer/import").append(targetPath); //$NON-NLS-1$ URI link = new URI(resource.getScheme(), resource.getAuthority(), path.toString(), null, null); if (representation.has(ProtocolConstants.KEY_EXCLUDED_IN_IMPORT)) { String linkString = link.toString(); if (linkString.contains("?")) { linkString += "&" + ProtocolConstants.PARAM_EXCLUDE + "=" + URLEncoder .encode(representation.getString(ProtocolConstants.KEY_EXCLUDED_IN_IMPORT), "UTF-8"); } else {/*from w w w . j av a 2 s. c o m*/ linkString += "?" + ProtocolConstants.PARAM_EXCLUDE + "=" + URLEncoder .encode(representation.getString(ProtocolConstants.KEY_EXCLUDED_IN_IMPORT), "UTF-8"); } link = new URI(linkString); representation.remove(ProtocolConstants.KEY_EXCLUDED_IN_IMPORT); } representation.put(ProtocolConstants.KEY_IMPORT_LOCATION, link); //Bug 348073: don't add export links for empty directories if (isEmptyDirectory(request, targetPath)) { return; } path = new Path("/xfer/export").append(targetPath).addFileExtension("zip"); //$NON-NLS-1$ //$NON-NLS-2$ link = new URI(resource.getScheme(), resource.getAuthority(), path.toString(), null, null); if (representation.has(ProtocolConstants.KEY_EXCLUDED_IN_EXPORT)) { String linkString = link.toString(); if (linkString.contains("?")) { linkString += "&" + ProtocolConstants.PARAM_EXCLUDE + "=" + URLEncoder .encode(representation.getString(ProtocolConstants.KEY_EXCLUDED_IN_EXPORT), "UTF-8"); } else { linkString += "?" + ProtocolConstants.PARAM_EXCLUDE + "=" + URLEncoder .encode(representation.getString(ProtocolConstants.KEY_EXCLUDED_IN_EXPORT), "UTF-8"); } link = new URI(linkString); representation.remove(ProtocolConstants.KEY_EXCLUDED_IN_EXPORT); } representation.put(ProtocolConstants.KEY_EXPORT_LOCATION, link); }
From source file:de.elepferd.web.pushnotifier.server.PushNotifierServlet.java
@JsonRpcMethod(method = PushNotifierProtocol.NotesSync.METHOD, requires_login = true) public JSONObject notesSync(final CallContext context) throws JSONException, JsonRpcException { // This method should return a list of updated notes since a current // date, optionally reconciling/merging a set of a local notes. String clientDeviceId = null; UserInfo userInfo = getCurrentUserInfo(context); Date sinceDate;/* w ww. j av a 2 s . c o m*/ try { clientDeviceId = context.getParams().optString(PushNotifierProtocol.ARG_CLIENT_DEVICE_ID); sinceDate = Util .parseDateISO8601(context.getParams().getString(PushNotifierProtocol.NotesSync.ARG_SINCE_DATE)); } catch (ParseException e) { throw new JsonRpcException(400, "Invalid since_date.", e); } catch (JSONException e) { throw new JsonRpcException(400, "Invalid since_date.", e); } JSONObject responseJson = new JSONObject(); JSONArray notesJson = new JSONArray(); Transaction tx = context.getPersistenceManager().currentTransaction(); Date newSinceDate = new Date(); try { tx.begin(); List<Note> localNotes = new ArrayList<Note>(); if (context.getParams().has(PushNotifierProtocol.NotesSync.ARG_LOCAL_NOTES)) { JSONArray localChangesJson = context.getParams() .getJSONArray(PushNotifierProtocol.NotesSync.ARG_LOCAL_NOTES); for (int i = 0; i < localChangesJson.length(); i++) { try { JSONObject noteJson = localChangesJson.getJSONObject(i); if (noteJson.has("id")) { Key existingNoteKey = Note.makeKey(userInfo.getId(), noteJson.get("id").toString()); try { Note existingNote = (Note) context.getPersistenceManager().getObjectById(Note.class, existingNoteKey); if (!existingNote.getOwnerId().equals(userInfo.getId())) { // User doesn't have permission to edit this note. Instead of // throwing an error, just re-create it on the server side. //throw new JsonRpcException(403, // "You do not have permission to modify this note."); noteJson.remove("id"); } } catch (JDOObjectNotFoundException e) { // Note doesn't exist, instead of throwing an error, // just re-create the note on the server side (unassign its ID). //throw new JsonRpcException(404, "Note with ID " // + noteJson.get("id").toString() + " does not exist."); noteJson.remove("id"); } } noteJson.put("owner_id", userInfo.getId()); Note localNote = new Note(noteJson); localNotes.add(localNote); } catch (JSONException e) { throw new JsonRpcException(400, "Invalid local note content.", e); } } } // Query server-side note changes. Query query = context.getPersistenceManager().newQuery(Note.class); query.setFilter("ownerKey == ownerKeyParam && modifiedDate > sinceDate"); query.setOrdering("modifiedDate desc"); query.declareParameters(Key.class.getName() + " ownerKeyParam, java.util.Date sinceDate"); @SuppressWarnings("unchecked") List<Note> notes = (List<Note>) query.execute(userInfo.getKey(), sinceDate); // Now merge the lists and conflicting objects. /*Reconciler<Note> reconciler = new Reconciler<Note>() { @Override public Note reconcile(Note o1, Note o2) { boolean pick1 = o1.getModifiedDate().after(o2.getModifiedDate()); // Make sure only the chosen version of the note is persisted context.getPersistenceManager().makeTransient(pick1 ? o2 : o1); return pick1 ? o1 : o2; } }; Collection<Note> reconciledNotes = reconciler.reconcileLists(notes, localNotes); for (Note note : reconciledNotes) { // Save the note. context.getPersistenceManager().makePersistent(note); // Put it in the response output. notesJson.put(note.toJSON()); } tx.commit();*/ } finally { if (tx.isActive()) { tx.rollback(); } } enqueueDeviceMessage(context.getPersistenceManager(), userInfo, clientDeviceId); responseJson.put(PushNotifierProtocol.NotesSync.RET_NOTES, notesJson); responseJson.put(PushNotifierProtocol.NotesSync.RET_NEW_SINCE_DATE, Util.formatDateISO8601(newSinceDate)); return responseJson; }
From source file:org.loklak.server.AbstractAPIHandler.java
private void process(HttpServletRequest request, HttpServletResponse response, Query query) throws ServletException, IOException { // basic protection BaseUserRole minimalBaseUserRole = getMinimalBaseUserRole() != null ? getMinimalBaseUserRole() : BaseUserRole.ANONYMOUS;//from w w w . j a v a2 s . c o m if (query.isDoS_blackout()) { response.sendError(503, "your request frequency is too high"); return; } // DoS protection if (DAO.getConfig("users.admin.localonly", true) && minimalBaseUserRole == BaseUserRole.ADMIN && !query.isLocalhostAccess()) { response.sendError(503, "access only allowed from localhost, your request comes from " + query.getClientHost()); return; } // danger! do not remove this! // user identification ClientIdentity identity = getIdentity(request, response, query); // user authorization: we use the identification of the user to get the assigned authorization Authorization authorization = new Authorization(identity, DAO.authorization, DAO.userRoles); if (authorization.getBaseUserRole().ordinal() < minimalBaseUserRole.ordinal()) { response.sendError(401, "Base user role not sufficient. Your base user role is '" + authorization.getBaseUserRole().name() + "', your user role is '" + authorization.getUserRole().getDisplayName() + "'"); return; } // user accounting: we maintain static and persistent user data; we again search the accounts using the usder identity string //JSONObject accounting_persistent_obj = DAO.accounting_persistent.has(user_id) ? DAO.accounting_persistent.getJSONObject(anon_id) : DAO.accounting_persistent.put(user_id, new JSONObject()).getJSONObject(user_id); Accounting accounting_temporary = DAO.accounting_temporary.get(identity.toString()); if (accounting_temporary == null) { accounting_temporary = new Accounting(); DAO.accounting_temporary.put(identity.toString(), accounting_temporary); } // the accounting data is assigned to the authorization authorization.setAccounting(accounting_temporary); // extract standard query attributes String callback = query.get("callback", ""); boolean jsonp = callback.length() > 0; boolean minified = query.get("minified", false); try { JSONObject json = serviceImpl(query, response, authorization, authorization.getPermissions(this)); if (json == null) { response.sendError(400, "your request does not contain the required data"); return; } // evaluate special fields if (json.has("$EXPIRES")) { int expires = json.getInt("$EXPIRES"); FileHandler.setCaching(response, expires); json.remove("$EXPIRES"); } // add session information JSONObject session = new JSONObject(true); session.put("identity", identity.toJSON()); json.put("session", session); // write json query.setResponse(response, "application/javascript"); response.setCharacterEncoding("UTF-8"); PrintWriter sos = response.getWriter(); if (jsonp) sos.print(callback + "("); sos.print(json.toString(minified ? 0 : 2)); if (jsonp) sos.println(");"); sos.println(); query.finalize(); } catch (APIException e) { response.sendError(e.getStatusCode(), e.getMessage()); return; } }
From source file:org.chromium.ChromeStorage.java
private void remove(final CordovaArgs args, final CallbackContext callbackContext) { cordova.getThreadPool().execute(new Runnable() { @Override/* w w w .ja va2s. c o m*/ public void run() { try { String namespace = args.getString(0); JSONObject jsonObject = (JSONObject) args.optJSONObject(1); JSONArray jsonArray = args.optJSONArray(1); boolean isNull = args.isNull(1); List<String> keys = new ArrayList<String>(); JSONObject oldValues = new JSONObject(); if (jsonObject != null) { keys = toStringList(jsonObject.names()); } else if (jsonArray != null) { keys = toStringList(jsonArray); } else if (isNull) { keys = null; } if (keys != null && !keys.isEmpty()) { JSONObject storage = getStorage(namespace); for (String key : keys) { Object oldValue = storage.opt(key); if (oldValue != null) { oldValues.put(key, oldValue); } storage.remove(key); } setStorage(namespace, storage); } callbackContext.success(oldValues); } catch (Exception e) { Log.e(LOG_TAG, "Could not update storage", e); callbackContext.error("Could not update storage"); } } }); }