List of usage examples for org.json.simple JSONObject containsKey
boolean containsKey(Object key);
From source file:no.oddsor.simulator3.json.SensorReader.java
public Collection<Sensor> getSensors() { Collection<Sensor> sensors = new ArrayList<>(); if (object == null) return sensors; JSONArray sensorList = (JSONArray) object.get("Sensors"); for (Object sensorOb : sensorList) { JSONObject sensorObject = (JSONObject) sensorOb; Sensor sensor = null;//from w w w .j a v a 2 s .c o m String type = (String) sensorObject.get("Type"); String name = (String) sensorObject.get("Name"); JSONArray locationArray = (JSONArray) sensorObject.get("Position"); Point location = null; if (locationArray != null) { location = new Point(Integer.parseInt(locationArray.get(0).toString()), Integer.parseInt(locationArray.get(1).toString())); } switch (type) { case "Contact": String attached = (String) sensorObject.get("Attached_to"); sensor = new Contact(name, attached); break; case "Camera": JSONArray range = (JSONArray) sensorObject.get("Range"); double[] dArray = new double[range.size()]; for (int i = 0; i < dArray.length; i++) { dArray[i] = Double.parseDouble(range.get(i).toString()); } if (!sensorObject.containsKey("Resolution")) sensor = new Camera(name, location, Double.parseDouble(sensorObject.get("Direction").toString()), Double.parseDouble(sensorObject.get("FieldOfView").toString()), dArray); else sensor = new Camera(name, location, Double.parseDouble(sensorObject.get("Direction").toString()), Double.parseDouble(sensorObject.get("FieldOfView").toString()), dArray, Integer.parseInt(sensorObject.get("Resolution").toString())); break; case "Door": JSONArray dimensionArray = (JSONArray) sensorObject.get("Size"); Dimension dims = new Dimension(Integer.parseInt(dimensionArray.get(0).toString()), Integer.parseInt(dimensionArray.get(1).toString())); sensor = new Door(name, location, dims); break; case "MotionSensor": if (sensorObject.containsKey("Radius")) sensor = new MotionSensor(name, location, Double.parseDouble(sensorObject.get("Radius").toString())); else { sensor = new MotionSensor(name, location, Double.parseDouble(sensorObject.get("Direction").toString()), Double.parseDouble(sensorObject.get("Range").toString()), Double.parseDouble(sensorObject.get("FieldOfView").toString())); } } if (sensorObject.containsKey("Exclude")) { JSONArray excludeArray = (JSONArray) sensorObject.get("Exclude"); for (Object exclude : excludeArray) { JSONObject exclud = (JSONObject) exclude; JSONArray edgeArray = (JSONArray) exclud.get("Edge"); Point edgeLocation = new Point(Integer.parseInt(edgeArray.get(0).toString()), Integer.parseInt(edgeArray.get(1).toString())); String direction = (String) exclud.get("Direction"); Point edge = null; Dimension dim = new Dimension(1000, 1000); switch (direction) { case ("Northeast"): edge = new Point(edgeLocation.x, edgeLocation.y - 1000); break; case ("Northwest"): edge = new Point(edgeLocation.x - 1000, edgeLocation.y - 1000); break; case ("Southeast"): edge = new Point(edgeLocation.x, edgeLocation.y); break; case ("Southwest"): edge = new Point(edgeLocation.x - 1000, edgeLocation.y); } Rectangle exluTangle = new Rectangle(edge, dim); sensor.removeArea(new Area(exluTangle)); } } if (sensorObject.containsKey("Confine")) { JSONArray coords = (JSONArray) sensorObject.get("Confine"); int[] x = new int[coords.size()]; int[] y = new int[coords.size()]; for (int i = 0; i < coords.size(); i++) { JSONArray coord = (JSONArray) coords.get(i); x[i] = Integer.parseInt(coord.get(0).toString()); y[i] = Integer.parseInt(coord.get(1).toString()); } Polygon p = new Polygon(x, y, coords.size()); Area excluPoly = new Area(p); sensor.confineToArea(excluPoly); } sensors.add(sensor); } return sensors; }
From source file:no.oddsor.simulator3.json.TaskReader.java
public Collection<ITask> getTasks() { Collection<ITask> tasks = new ArrayList<>(); if (object == null) return tasks; JSONArray tasklist = (JSONArray) object.get("Activities"); Iterator taskIterator = tasklist.iterator(); while (taskIterator.hasNext()) { JSONObject nextTask = (JSONObject) taskIterator.next(); Task newTask;//from ww w .j ava2 s .c o m if (nextTask.containsKey("Timespan")) { JSONArray timespan = (JSONArray) nextTask.get("Timespan"); tasks.add(newTask = new Task((String) nextTask.get("Name"), (String) nextTask.get("Type"), Integer.parseInt(nextTask.get("Duration").toString()), Integer.parseInt(timespan.get(0).toString()), Integer.parseInt(timespan.get(1).toString()), (String) nextTask.get("Appliance"), (nextTask.containsKey("Label") ? (String) nextTask.get("Label") : null))); } else { tasks.add(newTask = new Task((String) nextTask.get("Name"), (String) nextTask.get("Type"), Integer.parseInt(nextTask.get("Duration").toString()), (String) nextTask.get("Appliance"), (nextTask.containsKey("Label") ? (String) nextTask.get("Label") : null))); } if (nextTask.containsKey("Cooldown")) { double d = (long) nextTask.get("Cooldown") * 3600.0; newTask.setCooldown(d); } if (nextTask.containsKey("IncreasesNeed")) { JSONArray need = (JSONArray) nextTask.get("IncreasesNeed"); newTask.addResult((String) need.get(0), Integer.parseInt(need.get(1).toString())); } if (nextTask.containsKey("RequiresItem")) { if (!(nextTask.get("RequiresItem") instanceof JSONArray)) { newTask.addRequiredItem((String) nextTask.get("RequiresItem"), 1); } else { JSONArray requirements = (JSONArray) nextTask.get("RequiresItem"); if (requirements.get(1) instanceof Number) { newTask.addRequiredItem((String) requirements.get(0), Integer.parseInt(requirements.get(1).toString())); } else { for (Object item : requirements) { newTask.addRequiredItem((String) item, 1); } } } } if (nextTask.containsKey("Creates")) { if (nextTask.get("Creates") instanceof JSONArray) { JSONArray creates = (JSONArray) nextTask.get("Creates"); newTask.addResultingItem((String) creates.get(0), Integer.parseInt(creates.get(1).toString())); } else newTask.addResultingItem((String) nextTask.get("Creates"), 1); } if (nextTask.containsKey("PoseFeatures")) { if (nextTask.get("PoseFeatures") instanceof JSONArray) { JSONArray poses = (JSONArray) nextTask.get("PoseFeatures"); for (Object pose : poses) { String poseString = (String) pose; newTask.addPose(poseString); } } } if (nextTask.containsKey("NeedsState")) { if (nextTask.get("NeedsState") instanceof JSONArray) { JSONArray poses = (JSONArray) nextTask.get("NeedsState"); for (Object pose : poses) { String poseString = (String) pose; newTask.addNeededState(poseString); } } } if (nextTask.containsKey("AddsState")) { if (nextTask.get("AddsState") instanceof JSONArray) { JSONArray poses = (JSONArray) nextTask.get("AddsState"); for (Object pose : poses) { String poseString = (String) pose; if (poseString.charAt(0) == '+') newTask.addPlusState(poseString.substring(1)); if (poseString.charAt(0) == '-') newTask.addMinusState(poseString.substring(1)); } } } } return tasks; }
From source file:no.oddsor.simulator3.json.TaskReader.java
public Set<String> getAppliances() { Set<String> appliances = new HashSet<>(); if (object == null) return appliances; JSONArray tasklist = (JSONArray) object.get("Activities"); Iterator tasks = tasklist.iterator(); while (tasks.hasNext()) { JSONObject task = (JSONObject) tasks.next(); if (task.containsKey("Appliance")) appliances.add((String) task.get("Appliance")); if (task.containsKey("Creates") && task.get("Creates") instanceof JSONArray) { JSONArray createArray = (JSONArray) task.get("Creates"); if (createArray.get(1) instanceof String) appliances.add(createArray.get(1).toString()); }//from w w w . jav a 2 s .c o m } return appliances; }
From source file:no.oddsor.simulator3.json.TaskReader.java
public List<Need> getNeeds() { List<Need> needs = new ArrayList<>(); if (object == null) return needs; JSONArray taskList = (JSONArray) object.get("Activities"); Set<String> needNames = new HashSet<>(); Iterator tasks = taskList.iterator(); while (tasks.hasNext()) { JSONObject task = (JSONObject) tasks.next(); if (task.containsKey("IncreasesNeed")) { JSONArray arr = (JSONArray) task.get("IncreasesNeed"); needNames.add((String) arr.get(0)); }//from ww w . j a v a2 s . c o m } for (String name : needNames) { needs.add(new Need(name, 1.0)); } return needs; }
From source file:org.alfresco.integrations.web.evaluator.IsMimetypeEvaluator.java
@Override public boolean evaluate(JSONObject jsonObject) { JSONObject importFormats = (JSONObject) getJSONValue(getMetadata(), accessor); try {/*from www . ja va2 s. c om*/ JSONObject node = (JSONObject) jsonObject.get("node"); if (node == null) { return false; } else { String mimetype = (String) node.get("mimetype"); if (mimetype == null || !importFormats.containsKey(mimetype)) { log.debug("NodeRef: " + node.get("nodeRef") + "; Mimetype not supported: " + mimetype); return false; } log.debug("NodeRef: " + node.get("nodeRef") + "; Mimetype supported: " + mimetype); } } catch (Exception err) { throw new AlfrescoRuntimeException("Failed to run action evaluator: " + err.getMessage()); } return true; }
From source file:org.alfresco.repo.content.filestore.SpoofedTextContentReader.java
/** * @param url a URL describing the type of text to produce (see class comments) */// w ww .java2 s . c o m public SpoofedTextContentReader(String url) { super(url); if (url.length() > 255) { throw new IllegalArgumentException("A content URL is limited to 255 characters: " + url); } // Split out data part int index = url.indexOf(ContentStore.PROTOCOL_DELIMITER); if (index <= 0 || !url.startsWith(FileContentStore.SPOOF_PROTOCOL)) { throw new RuntimeException("URL not supported by this reader: " + url); } String urlData = url.substring(index + 3, url.length()); // Parse URL try { JSONParser parser = new JSONParser(); JSONObject mappedData = (JSONObject) parser.parse(urlData); String jsonLocale = mappedData.containsKey(KEY_LOCALE) ? (String) mappedData.get(KEY_LOCALE) : Locale.ENGLISH.toString(); String jsonSeed = mappedData.containsKey(KEY_SEED) ? (String) mappedData.get(KEY_SEED) : "0"; String jsonSize = mappedData.containsKey(KEY_SIZE) ? (String) mappedData.get(KEY_SIZE) : "1024"; JSONArray jsonWords = mappedData.containsKey(KEY_WORDS) ? (JSONArray) mappedData.get(KEY_WORDS) : new JSONArray(); // Get the text generator Locale locale = new Locale(jsonLocale); seed = Long.valueOf(jsonSeed); size = Long.valueOf(jsonSize); words = new String[jsonWords.size()]; for (int i = 0; i < words.length; i++) { words[i] = (String) jsonWords.get(i); } this.textGenerator = SpoofedTextContentReader.getTextGenerator(locale); // Set the base class storage for external information super.setLocale(locale); super.setEncoding("UTF-8"); super.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN); } catch (Exception e) { throw new RuntimeException("Unable to interpret URL: " + url, e); } }
From source file:org.alfresco.repo.web.scripts.blogs.AbstractBlogWebScript.java
/** * Generates an activity entry for the discussion item * /*www. ja v a 2 s . c o m*/ * @param event One of created, updated, deleted * @param blog Either post or reply * @param site site * @param req request * @param json json * @param nodeRef NodeRef */ protected void addActivityEntry(String event, BlogPostInfo blog, SiteInfo site, WebScriptRequest req, JSONObject json, NodeRef nodeRef) { // We can only add activities against a site if (site == null) { logger.info("Unable to add activity entry for blog " + event + " as no site given"); return; } // What page is this for? String page = req.getParameter("page"); if (page == null && json != null) { if (json.containsKey("page")) { page = (String) json.get("page"); } } if (page == null) { // Default page = "blog-postview"; } if (page.indexOf('?') == -1) { page += "?postId=" + blog.getSystemName(); } // Get the title String title = blog.getTitle(); try { JSONWriter jsonWriter = new JSONStringer().object().key(TITLE).value(title).key(PAGE).value(page); if (nodeRef != null) { // ALF-10182: the nodeRef needs to be included in the activity // post to ensure read permissions are respected. jsonWriter.key(PostLookup.JSON_NODEREF).value(nodeRef.toString()); } String data = jsonWriter.endObject().toString(); activityService.postActivity("org.alfresco.blog.post-" + event, site.getShortName(), "blog", data); } catch (Exception e) { // Warn, but carry on logger.warn("Error adding blog post " + event + " to activities feed", e); } }
From source file:org.alfresco.repo.web.scripts.blogs.posts.BlogPostsPost.java
private JsonParams parsePostParams(JSONObject json) { JsonParams result = new JsonParams(); if (json.containsKey(TITLE)) { result.setTitle((String) json.get(TITLE)); }/*from www. ja v a 2 s .com*/ if (json.containsKey(CONTENT)) { result.setContent((String) json.get(CONTENT)); } if (json.containsKey(DRAFT)) { Object draft = json.get(DRAFT); if (draft instanceof Boolean) { result.setIsDraft((Boolean) draft); } else { result.setIsDraft(Boolean.parseBoolean((String) draft)); } } // If there are no tags, this is a java.lang.String "". // If there are any tags, it's a JSONArray of strings. One or more. if (json.containsKey(TAGS)) { Object tagsObj = json.get(TAGS); List<String> tags = new ArrayList<String>(); if (tagsObj instanceof JSONArray) { JSONArray tagsJsonArray = (JSONArray) tagsObj; for (int i = 0; i < tagsJsonArray.size(); i++) { tags.add((String) tagsJsonArray.get(i)); } } else { tags.add(tagsObj.toString()); } result.setTags(tags); } if (json.containsKey(SITE)) { result.setSite((String) json.get(SITE)); } if (json.containsKey(PAGE)) { result.setPage((String) json.get(PAGE)); } if (json.containsKey(CONTAINER)) { result.setContainer((String) json.get(CONTAINER)); } return result; }
From source file:org.alfresco.repo.web.scripts.calendar.AbstractCalendarWebScript.java
/** * Extracts the Start and End details, along with the All Day flag * from the JSON, and returns if the event is all day or not *///w w w.ja va 2s . c o m protected boolean extractDates(CalendarEntry entry, JSONObject json) throws JSONException { boolean isAllDay = false; if (json.containsKey("allday")) { isAllDay = true; } if (json.containsKey(PARAM_START_AT) && json.containsKey(PARAM_END_AT)) { // New style ISO8601 based dates and times Object startAtO = json.get(PARAM_START_AT); Object endAtO = json.get(PARAM_END_AT); // Grab the details String startAt; String endAt; String timezoneName = null; if (startAtO instanceof JSONObject) { // "startAt": { "iso8601":"2011-...." } JSONObject startAtJSON = (JSONObject) startAtO; JSONObject endAtJSON = (JSONObject) endAtO; startAt = (String) startAtJSON.get(PARAM_ISO8601); endAt = (String) endAtJSON.get(PARAM_ISO8601); if (startAtJSON.containsKey(PARAM_TIMEZONE)) { timezoneName = (String) startAtJSON.get(PARAM_TIMEZONE); if (endAtJSON.containsKey(PARAM_TIMEZONE)) { String endTZ = (String) endAtJSON.get(PARAM_TIMEZONE); if (!endTZ.equals(timezoneName)) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Timezones must match"); } } } } else { // "startAt": "2011-...." startAt = (String) json.get(PARAM_START_AT); endAt = (String) json.get(PARAM_END_AT); } if (json.containsKey(PARAM_TIMEZONE)) { timezoneName = (String) json.get(PARAM_TIMEZONE); } // Is this an all day event? if (json.containsKey("allday")) { // Store it as UTC midnight to midnight // Reset the time part to ensure that String utcMidnight = "T00:00:00Z"; startAt = startAt.substring(0, 10) + utcMidnight; endAt = endAt.substring(0, 10) + utcMidnight; entry.setStart(ISO8601DateFormat.parse(startAt)); entry.setEnd(ISO8601DateFormat.parse(endAt)); } else { // Regular event start and end rules // Do we have explicit timezone information? if (timezoneName != null) { // Get the specified timezone TimeZone tz = TimeZone.getTimeZone(timezoneName); // Grab the dates and times in the specified timezone entry.setStart(ISO8601DateFormat.parse(startAt, tz)); entry.setEnd(ISO8601DateFormat.parse(endAt, tz)); } else { // Offset info is either in the date, or we just have to guess entry.setStart(parseDate(startAt)); entry.setEnd(parseDate(endAt)); } } } else if (json.containsKey("allday")) { // Old style all-day event Date start = parseDate(getOrNull(json, "from")); Date end = parseDate(getOrNull(json, "to")); // Store it as UTC midnight to midnight // Reset the time part to ensure that String isoStartAt = ISO8601DateFormat.format(start); String isoEndAt = ISO8601DateFormat.format(end); String utcMidnight = "T00:00:00Z"; isoStartAt = isoStartAt.substring(0, 10) + utcMidnight; isoEndAt = isoEndAt.substring(0, 10) + utcMidnight; entry.setStart(ISO8601DateFormat.parse(isoStartAt)); entry.setEnd(ISO8601DateFormat.parse(isoEndAt)); } else { // Old style regular event entry.setStart(parseDate((String) json.get("from") + " " + (String) json.get("start"))); entry.setEnd(parseDate((String) json.get("to") + " " + (String) json.get("end"))); } return isAllDay; }
From source file:org.alfresco.repo.web.scripts.calendar.AbstractCalendarWebScript.java
protected String getOrNull(JSONObject json, String key) throws JSONException { if (json.containsKey(key)) { return (String) json.get(key); }/*w w w. j a v a 2 s . com*/ return null; }