List of usage examples for org.json.simple JSONArray add
public boolean add(E e)
From source file:net.duckling.ddl.web.controller.task.TaskBaseController.java
/** * ?JSONJSON? users:[{ id: a ??? value:[{ id: * abc@cnic.cn (UID) name: ?? },......] },.... ] * //from ww w . j a va 2 s.co m * @param list * SimpleUser * @return */ private JSONObject getAlphabetJSONFromSortedPinyin(List<SimpleUser> list) { JSONArray array = new JSONArray(); if (null == list || list.isEmpty()) { return new JSONObject(); } Map<Character, JSONArray> map = new TreeMap<Character, JSONArray>(); for (SimpleUser user : list) { Character c = null; if (StringUtils.isEmpty(user.getPinyin())) { c = user.getUid().charAt(0); } else { c = user.getPinyin().charAt(0); } c = Character.toUpperCase(c); JSONArray child = map.get(c); if (child == null) { child = new JSONArray(); map.put(c, child); } child.add(getJSONFromSimpleUser(user)); } for (Entry<Character, JSONArray> entry : map.entrySet()) { add2Array(array, entry.getValue(), entry.getKey()); } JSONObject obj = new JSONObject(); obj.put("users", array); return obj; }
From source file:io.openvidu.java.client.Session.java
@SuppressWarnings("unchecked") protected String toJson() { JSONObject json = new JSONObject(); json.put("sessionId", this.sessionId); json.put("createdAt", this.createdAt); json.put("customSessionId", this.properties.customSessionId()); json.put("recording", this.recording); json.put("mediaMode", this.properties.mediaMode().name()); json.put("recordingMode", this.properties.recordingMode().name()); json.put("defaultOutputMode", this.properties.defaultOutputMode().name()); json.put("defaultRecordingLayout", this.properties.defaultRecordingLayout().name()); json.put("defaultCustomLayout", this.properties.defaultCustomLayout()); JSONObject connections = new JSONObject(); connections.put("numberOfElements", this.getActiveConnections().size()); JSONArray jsonArrayConnections = new JSONArray(); this.getActiveConnections().forEach(con -> { JSONObject c = new JSONObject(); c.put("connectionId", con.getConnectionId()); c.put("role", con.getRole().name()); c.put("token", con.getToken()); c.put("clientData", con.getClientData()); c.put("serverData", con.getServerData()); JSONArray pubs = new JSONArray(); con.getPublishers().forEach(p -> { pubs.add(p.toJson()); });//from w w w . ja va 2s .com JSONArray subs = new JSONArray(); con.getSubscribers().forEach(s -> { subs.add(s); }); c.put("publishers", pubs); c.put("subscribers", subs); jsonArrayConnections.add(c); }); connections.put("content", jsonArrayConnections); json.put("connections", connections); return json.toJSONString(); }
From source file:com.punyal.blackhole.core.net.web.WebHandler.java
public void getVibrationStrainData(Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String deviceName = request.getParameter("device"); LWM2Mdevice device = devicesList.getDeviceByName(deviceName); JSONObject json = new JSONObject(); if (device != null) { JSONArray list = new JSONArray(); JSONObject tmp;/*from w w w.ja va 2 s. c o m*/ for (RMSdata data : device.getVibrationData()) { tmp = new JSONObject(); tmp.put("time", data.timestamp); tmp.put("X", Math.sqrt(data.X)); tmp.put("Y", Math.sqrt(data.Y)); tmp.put("Z", Math.sqrt(data.Z)); list.add(tmp); //System.out.println(data.X+ " "+ Math.sqrt(data.X)); } json.put("vibration", list); list = new JSONArray(); for (StrainData data : device.getStrainData()) { tmp = new JSONObject(); tmp.put("time", data.timestamp); tmp.put("strain", data.strain); list.add(tmp); } json.put("strain", list); } json.put("test", 123); //System.out.println(json.toJSONString()); response.setContentType(MIMEtype.getMIME(JSON_MIME_TYPE)); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); response.getWriter().println(json.toJSONString()); }
From source file:name.yumaa.ChromeLogger4J.java
private void addValue(JSONArray object, Object value, int depth) { value = processValue(object, value, depth); if (value != null || this.addnull) object.add(value); }
From source file:net.matthewauld.racetrack.server.WrSQL.java
@SuppressWarnings("unchecked") public String getJSONString(String query, String[] args) throws SQLException { connect();/* ww w . j a v a2s . c o m*/ ps = con.prepareStatement(query); for (int i = 0; i < args.length; i++) { ps.setString(i + 1, args[i]); } rs = ps.executeQuery(); JSONObject json = new JSONObject(); JSONArray riders = new JSONArray(); while (rs.next()) { JSONObject riderJSON = new JSONObject(); riderJSON.put("id", rs.getInt("id")); riderJSON.put("first_name", rs.getString("first_name")); riderJSON.put("last_name", rs.getString("last_name")); riders.add(riderJSON); } if (riders.size() == 0) { json.put("riders", null); } else { json.put("riders", riders); } return json.toJSONString(); }
From source file:Javafile.java
long findMatchedWords(String s, HashMap words, HashMap matchedWords, JSONArray matchedArrayJSON, int count) { String s1;//from ww w. j av a2 s.com int i = 0; long totalFind = 0; for (Iterator it = words.keySet().iterator(); it.hasNext();) { Object key = it.next(); s1 = key.toString(); if (s1.contains(s)) { totalFind++; i++; if (i >= count - 10 && i < count) { JSONObject matchedWordJSON = new JSONObject(); matchedWordJSON.put("id", s1); matchedWordJSON.put("text", s1); matchedArrayJSON.add(matchedWordJSON); } } } return totalFind; }
From source file:com.opensoc.alerts.TelemetryAlertsBolt.java
@SuppressWarnings("unchecked") public void execute(Tuple tuple) { LOG.trace("[OpenSOC] Starting to process message for alerts"); JSONObject original_message = null;/*from w w w .j a v a2s . co m*/ String key = null; try { key = tuple.getStringByField("key"); original_message = (JSONObject) tuple.getValueByField("message"); if (original_message == null || original_message.isEmpty()) throw new Exception("Could not parse message from byte stream"); if (key == null) throw new Exception("Key is not valid"); LOG.trace("[OpenSOC] Received tuple: " + original_message); JSONObject alerts_tag = new JSONObject(); Map<String, JSONObject> alerts_list = _adapter.alert(original_message); JSONArray uuid_list = new JSONArray(); if (alerts_list == null || alerts_list.isEmpty()) { System.out.println("[OpenSOC] No alerts detected in: " + original_message); _collector.ack(tuple); _collector.emit("message", new Values(key, original_message)); } else { for (String alert : alerts_list.keySet()) { uuid_list.add(alert); LOG.trace("[OpenSOC] Checking alerts cache: " + alert); if (cache.getIfPresent(alert) == null) { System.out.println("[OpenSOC]: Alert not found in cache: " + alert); JSONObject global_alert = new JSONObject(); global_alert.putAll(_identifier); global_alert.putAll(alerts_list.get(alert)); global_alert.put("timestamp", System.currentTimeMillis()); _collector.emit("alert", new Values(global_alert)); cache.put(alert, ""); } else LOG.trace("Alert located in cache: " + alert); LOG.debug("[OpenSOC] Alerts are: " + alerts_list); if (original_message.containsKey("alerts")) { JSONArray already_triggered = (JSONArray) original_message.get("alerts"); uuid_list.addAll(already_triggered); LOG.trace("[OpenSOC] Messages already had alerts...tagging more"); } original_message.put("alerts", uuid_list); LOG.debug("[OpenSOC] Detected alerts: " + alerts_tag); _collector.ack(tuple); _collector.emit("message", new Values(key, original_message)); } /* * if (metricConfiguration != null) { emitCounter.inc(); * ackCounter.inc(); } */ } } catch (Exception e) { e.printStackTrace(); LOG.error("Failed to tag message :" + original_message); e.printStackTrace(); _collector.fail(tuple); /* * if (metricConfiguration != null) { failCounter.inc(); } */ JSONObject error = ErrorGenerator.generateErrorMessage("Alerts problem: " + original_message, e); _collector.emit("error", new Values(error)); } }
From source file:gr.iit.demokritos.cru.cps.api.GetUserProfile.java
public JSONObject processRequest() throws IOException { String response_code = "e0"; ArrayList<UserProperty> up = new ArrayList<UserProperty>(); // String filename = "/WEB-INF/configuration.properties"; String location = (String) properties.get("location"); String database_name = (String) properties.get("database_name"); String username = (String) properties.get("username"); String password = (String) properties.get("password"); MySQLConnector mysql = new MySQLConnector(location, database_name, username, password); Connection connection = mysql.connectToCPSDatabase(); try {//from w w w . j a va 2 s.com CreativityUserModellingController cumc = new CreativityUserModellingController( Long.parseLong(application_key), Long.parseLong(user_id.trim())); boolean isvalid = cumc.validateClientApplication(mysql); if (isvalid == true) { isvalid = cumc.validateUser(mysql); if (isvalid == true) { cumc.retrieveUserProfile(mysql); up = cumc.getUserProperties(); response_code = "OK"; } else { response_code = "e102"; } } else { response_code = "e101"; } } catch (NumberFormatException ex) { response_code = "e101"; Logger.getLogger(CreateUser.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex) { Logger.getLogger(GetUserProfile.class.getName()).log(Level.SEVERE, null, ex); } JSONArray list = new JSONArray(); Iterator it = up.iterator(); int window = 0; JSONObject obj = new JSONObject(); JSONObject obj_temp = new JSONObject(); while (it.hasNext()) { JSONObject obj_window = new JSONObject(); UserProperty temp_up = (UserProperty) it.next(); obj_window.put("window", temp_up.getWindow()); obj_window.put(temp_up.getProperty_name(), temp_up.getProperty_value()); obj_window.put("timestamp", temp_up.getTimestamp()); list.add(obj_window); //System.out.println(obj_temp.toJSONString()); //obj_window.clear(); } //obj_temp.put("properties",list); JSONObject main_obj = new JSONObject(); main_obj.put("application_key", application_key); main_obj.put("user_id", user_id); main_obj.put("profile", list); main_obj.put("response_code", response_code); return main_obj; }
From source file:com.relayrides.pushy.apns.util.ApnsPayloadBuilder.java
@SuppressWarnings("unchecked") private Object createAlertObject() { if (this.hasAlertContent()) { if (this.shouldRepresentAlertAsString()) { return this.alertBody; } else {/* ww w . j av a 2 s.c o m*/ final JSONObject alert = new JSONObject(); if (this.alertBody != null) { alert.put(ALERT_BODY_KEY, this.alertBody); } if (this.alertTitle != null) { alert.put(ALERT_TITLE_KEY, this.alertTitle); } if (this.showActionButton) { if (this.localizedActionButtonKey != null) { alert.put(ACTION_LOC_KEY, this.localizedActionButtonKey); } } else { // To hide the action button, the key needs to be present, but the value needs to be null alert.put(ACTION_LOC_KEY, null); } if (this.localizedAlertKey != null) { alert.put(ALERT_LOC_KEY, this.localizedAlertKey); if (this.localizedAlertArguments != null) { final JSONArray alertArgs = new JSONArray(); for (final String arg : this.localizedAlertArguments) { alertArgs.add(arg); } alert.put(ALERT_ARGS_KEY, alertArgs); } } if (this.localizedAlertTitleKey != null) { alert.put(ALERT_TITLE_LOC_KEY, this.localizedAlertTitleKey); if (this.localizedAlertTitleArguments != null) { final JSONArray alertTitleArgs = new JSONArray(); for (final String arg : this.localizedAlertTitleArguments) { alertTitleArgs.add(arg); } alert.put(ALERT_TITLE_ARGS_KEY, alertTitleArgs); } } if (this.launchImageFileName != null) { alert.put(LAUNCH_IMAGE_KEY, this.launchImageFileName); } return alert; } } else { return null; } }
From source file:de.ingrid.external.gemet.GEMETClient.java
/** * This one is buggy e.g.<br>//from www . java 2 s.c o m * works for this URL:<br> * http://www.eionet.europa.eu/gemet/getRelatedConcepts?concept_uri=http://www.eionet.europa.eu/gemet/group/10117&relation_uri=http://www.eionet.europa.eu/gemet/2004/06/gemet-schema.rdf%23groupMember&language=de * <br> * but NOT for this one:<br> * http://www.eionet.europa.eu/gemet/getRelatedConcepts?concept_uri=http://www.eionet.europa.eu/gemet/group/10114&relation_uri=http://www.eionet.europa.eu/gemet/2004/06/gemet-schema.rdf%23groupMember&language=de * @param conceptUri * @param language * @return */ // @formatter:on protected List<JSONArray> getChildConceptsViaGetRelatedConcepts(String conceptUri, String language) { // child relations ConceptRelation[] relations = null; if (isGroup(conceptUri)) { // for groups the relation is "groupMember" relations = new ConceptRelation[] { ConceptRelation.GROUP_MEMBER }; } else { // for concepts and soupergroups the relation is "narrower" relations = new ConceptRelation[] { ConceptRelation.NARROWER }; } // get children List<JSONArray> conceptList = new ArrayList<JSONArray>(); for (ConceptRelation relation : relations) { JSONArray concepts = getRelatedConcepts(conceptUri, relation, language); // we have to filter GROUP_MEMBER ! // we use only those having NO BROADER concept meaning their only // parent is the group ! if (relation == ConceptRelation.GROUP_MEMBER && concepts.size() > 0) { JSONArray groupConcepts = new JSONArray(); for (Object concept : concepts) { if (!hasRelation(JSONUtils.getId((JSONObject) concept), ConceptRelation.BROADER, language)) { groupConcepts.add(concept); } } concepts = groupConcepts; } conceptList.add(concepts); } return conceptList; }