List of usage examples for org.json JSONObject has
public boolean has(String key)
From source file:com.nginious.http.websocket.WebSocketTestCase.java
public void testDeserializableBeans() throws Exception { WebSocketTestConnection wsConn = null; try {//www. j a va 2 s .co m wsConn = handshake("wsdeserialize"); byte[] mask = generateRandomBytes(4); String str = "{ \"testBean1\": { \"first\": \"true\" } }"; byte len = (byte) (0x80 + str.length()); byte[] payload = generateMaskedString(str, mask); byte[] header = { (byte) 0x81, len, mask[0], mask[1], mask[2], mask[3] }; byte[] frame = new byte[header.length + payload.length]; System.arraycopy(header, 0, frame, 0, header.length); System.arraycopy(payload, 0, frame, header.length, payload.length); wsConn.write(frame); // Check response frame byte[] respFrame = wsConn.readFrame(); assertNotNull(respFrame); byte flags = respFrame[0]; assertTrue((flags & 0x80) > 0); // Check for final frame flag set assertTrue("i=" + str.length() + ", flags=" + flags, (flags & 0x0F) == 0x01); // Check for opcode text message len = respFrame[1]; String respStr = new String(respFrame, 2, len); JSONObject testBean = new JSONObject(respStr); assertTrue(testBean.has("testBean1")); JSONObject testBean2 = testBean.getJSONObject("testBean1"); assertNotNull(testBean2); assertTrue(testBean2.getBoolean("first")); } finally { if (wsConn != null) { wsConn.close(); } } }
From source file:com.nginious.http.websocket.WebSocketTestCase.java
public void testSerializableBeans() throws Exception { WebSocketTestConnection wsConn = null; try {// w w w. j a v a 2s . c o m wsConn = handshake("wsserialize"); byte[] mask = generateRandomBytes(4); String str = "{ \"testBean1\": { \"first\": \"true\" } }"; byte len = (byte) (0x80 + str.length()); byte[] payload = generateMaskedString(str, mask); byte[] header = { (byte) 0x81, len, mask[0], mask[1], mask[2], mask[3] }; byte[] frame = new byte[header.length + payload.length]; System.arraycopy(header, 0, frame, 0, header.length); System.arraycopy(payload, 0, frame, header.length, payload.length); wsConn.write(frame); // Check response frame byte[] respFrame = wsConn.readFrame(); assertNotNull(respFrame); byte flags = respFrame[0]; assertTrue((flags & 0x80) > 0); // Check for final frame flag set assertTrue("i=" + str.length() + ", flags=" + flags, (flags & 0x0F) == 0x01); // Check for opcode text message len = respFrame[1]; String respStr = new String(respFrame, 2, len); JSONObject testBean = new JSONObject(respStr); assertTrue(testBean.has("testBean1")); JSONObject testBean2 = testBean.getJSONObject("testBean1"); assertNotNull(testBean2); assertTrue(testBean2.getBoolean("first")); } finally { if (wsConn != null) { wsConn.close(); } } }
From source file:com.whizzosoftware.hobson.scheduler.ical.ICalTask.java
public ICalTask(ActionManager actionManager, String providerId, VEvent event, TaskExecutionListener listener) throws InvalidVEventException { this.actionManager = actionManager; this.providerId = providerId; this.event = event; this.listener = listener; if (event != null) { // adjust start time if sun offset is set Property sunOffset = event.getProperty(PROP_SUN_OFFSET); if (sunOffset != null) { try { solarOffset = new SolarOffset(sunOffset.getValue()); } catch (ParseException e) { throw new InvalidVEventException("Invalid X-SUN-OFFSET", e); }/* w ww. j a v a 2s. c o m*/ } // parse actions Property commentProp = event.getProperty("COMMENT"); if (commentProp != null) { JSONArray arr = new JSONArray(new JSONTokener(commentProp.getValue())); for (int i = 0; i < arr.length(); i++) { JSONObject json = arr.getJSONObject(i); if (json.has("pluginId") && json.has("actionId")) { addActionRef(json); } else { throw new InvalidVEventException("Found scheduled event with no plugin and/or action"); } } } else { throw new InvalidVEventException("ICalEventTask event must have a COMMENT property"); } } else { throw new InvalidVEventException("ICalEventTask must have a non-null event"); } }
From source file:com.whizzosoftware.hobson.scheduler.ical.ICalTask.java
public ICalTask(ActionManager actionManager, String providerId, JSONObject json) { this.actionManager = actionManager; this.providerId = providerId; this.event = new VEvent(); String id;//w ww .j a v a 2s . c o m if (json.has("id")) { id = json.getString("id"); } else { id = UUID.randomUUID().toString(); } event.getProperties().add(new Uid(id)); event.getProperties().add(new Summary(json.getString("name"))); try { if (json.has("conditions")) { JSONArray conditions = json.getJSONArray("conditions"); if (conditions.length() == 1) { JSONObject jc = conditions.getJSONObject(0); if (jc.has("start") && !jc.isNull("start")) { event.getProperties().add(new DtStart(jc.getString("start"))); } if (jc.has("recurrence") && !jc.isNull("recurrence")) { event.getProperties().add(new RRule(jc.getString("recurrence"))); } if (jc.has("sunOffset") && !jc.isNull("sunOffset")) { event.getProperties().add(new XProperty(PROP_SUN_OFFSET, jc.getString("sunOffset"))); } } else { throw new HobsonRuntimeException("ICalTasks only support one condition"); } } } catch (ParseException e) { throw new HobsonRuntimeException("Error parsing recurrence rule", e); } try { if (json.has("actions")) { JSONArray actions = json.getJSONArray("actions"); event.getProperties().add(new Comment(actions.toString())); for (int i = 0; i < actions.length(); i++) { addActionRef(actions.getJSONObject(i)); } } } catch (Exception e) { throw new HobsonRuntimeException("Error parsing actions", e); } }
From source file:com.whizzosoftware.hobson.scheduler.ical.ICalTask.java
private void addActionRef(JSONObject json) { HobsonActionRef ref = new HobsonActionRef(json.getString("pluginId"), json.getString("actionId"), json.getString("name")); if (json.has("properties")) { JSONObject propJson = json.getJSONObject("properties"); Iterator it = propJson.keys(); while (it.hasNext()) { String key = (String) it.next(); ref.addProperty(key, propJson.get(key)); }/* ww w . jav a 2 s. com*/ } actions.add(ref); }
From source file:ai.susi.mind.SusiSkill.java
/** * Generate a set of skills from a single skill definition. This may be possible if the skill contains an 'options' * object which creates a set of skills, one for each option. The options combine with one set of phrases * @param json - a multi-skill definition * @return a set of skills/*from www . j a v a 2 s.co m*/ */ public static List<SusiSkill> getSkills(JSONObject json) { if (!json.has("phrases")) throw new PatternSyntaxException("phrases missing", "", 0); final List<SusiSkill> skills = new ArrayList<>(); if (json.has("options")) { JSONArray options = json.getJSONArray("options"); for (int i = 0; i < options.length(); i++) { JSONObject option = new JSONObject(); option.put("phrases", json.get("phrases")); JSONObject or = options.getJSONObject(i); for (String k : or.keySet()) option.put(k, or.get(k)); skills.add(new SusiSkill(option)); } } else { try { SusiSkill skill = new SusiSkill(json); skills.add(skill); } catch (PatternSyntaxException e) { Logger.getLogger("SusiSkill") .warning("Regular Expression error in Susi Skill: " + json.toString(2)); } } return skills; }
From source file:ai.susi.mind.SusiSkill.java
/** * Create a skill by parsing of the skill description * @param json the skill description//from w w w. ja va 2s . c o m * @throws PatternSyntaxException */ private SusiSkill(JSONObject json) throws PatternSyntaxException { // extract the phrases and the phrases subscore if (!json.has("phrases")) throw new PatternSyntaxException("phrases missing", "", 0); JSONArray p = (JSONArray) json.remove("phrases"); this.phrases = new ArrayList<>(p.length()); p.forEach(q -> this.phrases.add(new SusiPhrase((JSONObject) q))); // extract the actions and the action subscore if (!json.has("actions")) throw new PatternSyntaxException("actions missing", "", 0); p = (JSONArray) json.remove("actions"); this.actions = new ArrayList<>(p.length()); p.forEach(q -> this.actions.add(new SusiAction((JSONObject) q))); // extract the inferences and the process subscore; there may be no inference at all if (json.has("process")) { p = (JSONArray) json.remove("process"); this.inferences = new ArrayList<>(p.length()); p.forEach(q -> this.inferences.add(new SusiInference((JSONObject) q))); } else { this.inferences = new ArrayList<>(0); } // extract (or compute) the keys; there may be none key given, then they will be computed this.keys = new HashSet<>(); JSONArray k; if (json.has("keys")) { k = json.getJSONArray("keys"); if (k.length() == 0 || (k.length() == 1 && k.getString(0).length() == 0)) k = computeKeysFromPhrases(this.phrases); } else { k = computeKeysFromPhrases(this.phrases); } k.forEach(o -> this.keys.add((String) o)); this.user_subscore = json.has("score") ? json.getInt("score") : DEFAULT_SCORE; this.score = null; // calculate this later if required // extract the comment this.comment = json.has("comment") ? json.getString("comment") : ""; // calculate the id String ids0 = this.actions.toString(); String ids1 = this.phrases.toString(); this.id = ids0.hashCode() + ids1.hashCode(); }
From source file:org.dasein.cloud.joyent.SmartDataCenter.java
public @Nonnull String getEndpoint() throws CloudException, InternalException { ProviderContext ctx = getContext();// w ww .ja va 2 s . c o m if (ctx == null) { throw new CloudException("No context has been established for this request"); } String e = ctx.getEndpoint(); if (e == null) { e = "https://us-west-1.api.joyentcloud.com"; } String[] parts = e.split(","); if (parts == null || parts.length < 1) { parts = new String[] { e }; } String r = ctx.getRegionId(); if (r == null) { return parts[0]; } if (endpointCache.containsKey(e)) { Map<String, String> cache = endpointCache.get(e); if (cache != null && cache.containsKey(r)) { String endpoint = cache.get(r); if (endpoint != null) { return endpoint; } } } JoyentMethod method = new JoyentMethod(this); String json = method.doGetJson(parts[0], "datacenters"); try { JSONObject ob = new JSONObject(json); JSONArray ids = ob.names(); for (int i = 0; i < ids.length(); i++) { String regionId = ids.getString(i); if (regionId.equals(r) && ob.has(regionId)) { String endpoint = ob.getString(regionId); Map<String, String> cache; if (endpointCache.containsKey(e)) { cache = endpointCache.get(e); } else { cache = new HashMap<String, String>(); endpointCache.put(e, cache); } cache.put(r, endpoint); return endpoint; } } throw new CloudException("No endpoint exists for " + r); } catch (JSONException ex) { throw new CloudException(ex); } }
From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java
private static void addFieldToXml(Element root, Field field, JSONObject in, String permlevel) throws JSONException, UnderlyingStorageException { if (field.isServicesReadOnly()) { // Omit fields that are read-only in the services layer. log.debug("Omitting services-readonly field: " + field.getID()); return;/* ww w . ja va 2 s .co m*/ } Element element = root; if (field.getUIType().startsWith("groupfield") && field.getUIType().contains("selfrenderer")) { //ignore the top level if this is a self renderer as the UI needs it but the services doesn't } else { element = root.addElement(field.getServicesTag()); } String value = in.optString(field.getID()); if (field.getUIType().startsWith("groupfield")) { if (field.getUIType().contains("selfrenderer")) { addSubRecordToXml(element, field, in, permlevel); } else { if (in.has(field.getID())) { addSubRecordToXml(element, field, in.getJSONObject(field.getID()), permlevel); } } } else if (field.getDataType().equals("boolean")) { // Rather than dump what we have coming in, first convert to proper boolean and back. // Properly handles null, in particular. boolean bool = Boolean.parseBoolean(value); element.addText(Boolean.toString(bool)); } else { element.addText(value); } }
From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java
public static Document convertToXml(Record r, JSONObject in, String section, String permtype, Boolean useInstance) throws JSONException, UnderlyingStorageException { if (!useInstance) { return convertToXml(r, in, section, permtype); }// www. j ava 2 s .co m Document doc = DocumentFactory.getInstance().createDocument(); String[] parts = r.getServicesRecordPath(section).split(":", 2); if (useInstance) { parts = r.getServicesInstancesPath(section).split(":", 2); } String[] rootel = parts[1].split(","); Element root = doc.addElement(new QName(rootel[1], new Namespace("ns2", rootel[0]))); Element element = root.addElement("displayName"); element.addText(in.getString("displayName")); Element element2 = root.addElement("shortIdentifier"); element2.addText(in.getString("shortIdentifier")); if (in.has("vocabType")) { Element element3 = root.addElement("vocabType"); element3.addText(in.getString("vocabType")); } return doc; //yes I know hardcode is bad - but I need this out of the door today /* <ns2:personauthorities_common xmlns:ns2="http://collectionspace.org/services/person"> <displayName>PAHMA Person Authority</displayName> <vocabType>PersonAuthority</vocabType> <shortIdentifier>pamha</shortIdentifier> </ns2:personauthorities_common> */ }