List of usage examples for org.json.simple JSONObject containsKey
boolean containsKey(Object key);
From source file:sensorsActuators.JsonSocketSensor.java
private boolean messageIsValid(JSONObject JS) { for (String s : codes) { if (!JS.containsKey(s)) return false; }// w ww. ja va 2s. c om return true; }
From source file:sf.net.experimaestro.server.JsonRPCMethods.java
void handleJSON(JSONObject object) { String requestID = null;/*from w w w . j a v a 2s. c o m*/ try { requestID = object.get("id").toString(); if (requestID == null) throw new RuntimeException("No id in JSON request"); Object command = object.get("method"); if (command == null) throw new RuntimeException("No method in JSON"); if (!object.containsKey("params")) throw new RuntimeException("No params in JSON"); Object p = object.get("params"); Collection<MethodDescription> candidates = methods.get(command.toString()); int max = Integer.MIN_VALUE; MethodDescription argmax = null; for (MethodDescription candidate : candidates) { int score = Integer.MAX_VALUE; for (int i = 0; i < candidate.types.length && score > max; i++) { score = convert(p, candidate, score, null, i); } if (score > max) { max = score; argmax = candidate; } } if (argmax == null) throw new XPMCommandException("Cannot find a matching method"); Object[] args = new Object[argmax.arguments.length]; for (int i = 0; i < args.length; i++) { int score = convert(p, argmax, 0, Arrays.asList(args), i); assert score > Integer.MIN_VALUE; } Object result = argmax.method.invoke(this, args); mos.endMessage(requestID, result); } catch (ExitException e) { try { mos.error(requestID, e.getCode(), e.getMessage()); } catch (IOException e2) { LOGGER.error(e2, "Could not send the return code"); } } catch (InvocationTargetException e) { LOGGER.info("Error while handling JSON request [%s]", e); try { Throwable t = e; while (t.getCause() != null) { t = t.getCause(); } mos.error(requestID, 1, t.getMessage()); } catch (IOException e2) { LOGGER.error(e2, "Could not send the return code"); } } catch (Throwable t) { LOGGER.info(t, "Internal error while handling JSON request"); try { mos.error(requestID, 1, "Internal error while running request"); } catch (IOException e) { LOGGER.error("Could not send the return code"); } } }
From source file:tests.RenewTestData.java
private static String lookupData(final String meta) { String ret = null;/*from w w w. j a v a2 s . c o m*/ JSONObject object = (JSONObject) ((JSONObject) JSONValue.parse(meta)).get("index"); String id = ((String) object.get("_id")); String type = ((String) object.get("_type")); if (!type.equals("json-ld-lobid-collection")) { id = id.replaceAll("http:\\/\\/d-nb.info/gnd\\/", "http:\\/\\/lobid.org\\/subject/"); int i = id.lastIndexOf("/"); id = id.substring(0, i).concat("?id=").concat(id.substring(i + 1)).concat("&format=internal"); } URL url; try { url = new URL(id); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("Accept", "application/ld+json"); urlConnection.connect(); ret = IOUtils.toString(urlConnection.getInputStream(), "UTF-8"); if (type.equals("json-ld-lobid-collection")) { Iterator<JSONObject> it = ((JSONArray) JSONValue.parse(ret)).iterator(); while (it.hasNext()) { object = it.next(); if (object.containsKey("@graph")) { ret = "{\"@graph\":" + object.get("@graph").toString().concat("}"); } } } } catch (IOException e) { e.printStackTrace(); } return ret; }
From source file:tilt.handler.Options.java
/** * Initialise an options object fro a possibly empty set of properties * @param opts a RAW JSON object/*from w w w . ja va 2 s. com*/ */ public Options(JSONObject opts) { if (opts.containsKey("url")) this.url = (String) opts.get("url"); if (opts.containsKey("blur")) this.blur = ((Number) opts.get("blur")).intValue(); if (opts.containsKey("smoothN")) this.smoothN = ((Number) opts.get("smoothN")).intValue(); if (opts.containsKey("hScaleRatio")) this.hScaleRatio = ((Number) opts.get("hScaleRatio")).floatValue(); if (opts.containsKey("minBlackPC")) this.minBlackPC = ((Number) opts.get("minBlackPC")).floatValue(); if (opts.containsKey("minHProportion")) this.minHProportion = ((Number) opts.get("minHProportion")).floatValue(); if (opts.containsKey("minVProportion")) this.minVProportion = ((Number) opts.get("minVProportion")).floatValue(); if (opts.containsKey("oddShape")) this.oddShape = ((Number) opts.get("oddShape")).floatValue(); if (opts.containsKey("lineDepthFactor")) this.lineDepthFactor = ((Number) opts.get("lineDepthFactor")).floatValue(); if (opts.containsKey("sharedRatio")) this.sharedRatio = ((Number) opts.get("sharedRatio")).floatValue(); if (opts.containsKey("hyphenated")) this.hyphenated = ((Boolean) opts.get("hyphenated")).booleanValue(); String s = "[[0.0,0.0],[100.0,0.0],[100.0,100.0],[0.0,100.0]]"; Object obj = JSONValue.parse(s); this.coords = (JSONArray) obj; }
From source file:tilt.test.Post.java
/** * Display the test GUI//from w w w . j a va2s . co m * @param request the request to read from * @param urn the original URN */ @Override public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws TiltException { try { // create the doc and install the scripts etc doc = new HTML(); doc.getHead().addEncoding("UTF-8"); doc.getHead().addScriptFile("/tilt/static/js/jquery-1.11.1.js"); doc.getHead().addScriptFile("/tilt/static/js/jquery.highlight.js"); doc.getHead().addScriptFile("/tilt/static/js/post.js"); doc.getHead().addCssFile("/tilt/static/css/post.css"); Connection conn = Connector.getConnection(); String[] docids = conn.listCollection(Database.OPTIONS); HashMap<String, String> selections = new HashMap<>(); String first = null; String defaultDocId = (docids.length > 0) ? docids[0] : ""; String defaultPageId = ""; for (int i = 0; i < docids.length; i++) { String jstr = conn.getFromDb(Database.OPTIONS, docids[i]); JSONObject jobj = (JSONObject) JSONValue.parse(jstr); String title; if (jobj.containsKey(JSONKeys.TITLE)) title = (String) jobj.get(JSONKeys.TITLE); else title = docids[i]; // default Number pageNum = (Number) jobj.get("test_page"); String pageId = new Integer(pageNum.intValue()).toString(); if (first == null) { defaultDocId = docids[i]; // we'll get a double with exponent notation otherwise defaultPageId = pageId; first = title; } selections.put(title, docids[i] + "#" + pageId); } Form f = new Form("POST", "http://" + request.getServerName() + "/tilt/test/", "multipart/form-data"); f.addAttribute("id", "main"); Select s = new Select(selections, "selections", first); Element p = new Element("p"); Element span = new Element("span"); span.addAttribute("id", "title"); span.addText("TILT upload test: "); p.addElement(span); p.addElement(s); f.addElement(p); p = new Element("p"); p.addElement(new Input("preflight", "button", "preflight", false)); p.addElement(new Input("greyscale", "button", "greyscale", false)); p.addElement(new Input("twotone", "button", "two tone", false)); p.addElement(new Input("cleaned", "button", "cleaned", false)); p.addElement(new Input("reconstructed", "button", "reconstructed", false)); p.addElement(new Input("baselines", "button", "baselines", false)); p.addElement(new Input("words", "button", "words", false)); p.addElement(new Input("link", "button", "link", false)); f.addElement(p); addHiddenElement(f, "docid", defaultDocId); addHiddenElement(f, "pageid", defaultPageId); addHiddenElement(f, "text", ""); doc.addElement(f); Element lhs = new Element("div"); lhs.addAttribute("id", "left"); Element container = new Element("div"); container.addAttribute("id", "container"); lhs.addElement(container); doc.addElement(lhs); Element rhs = new Element("div"); rhs.addAttribute("id", "right"); Element contentDiv = new Element("div"); contentDiv.addAttribute("id", "content"); rhs.addElement(contentDiv); doc.addElement(rhs); response.setContentType("text/html;charset=UTF-8"); response.getWriter().println(doc); } catch (Exception e) { throw new TiltException(e); } }
From source file:tk.itstake.steakgui.util.ItemStackConverter.java
public static ItemStack convert(JSONObject json) { ItemStack item = new ItemStack(Material.valueOf(((String) json.get("type")).toUpperCase()), (int) (long) json.get("amount"), (short) (long) json.get("data")); if (json.containsKey("meta")) { JSONObject metajson = (JSONObject) json.get("meta"); ItemMeta meta = item.getItemMeta(); if (metajson.containsKey("name")) { meta.setDisplayName((String) metajson.get("name")); }//from www . ja v a 2 s . c o m if (metajson.containsKey("lore")) { meta.setLore((List<String>) metajson.get("lore")); } if (metajson.containsKey("enchantments")) { JSONObject enchantment = (JSONObject) metajson.get("enchantments"); for (Object enchant : enchantment.keySet()) { Integer level = (int) (long) enchantment.get(enchant); meta.addEnchant(Enchantment.getByName((String) enchant), level, true); } } if (metajson.containsKey("flags")) { try { Class.forName("org.bukkit.inventory.ItemFlag"); JSONArray flagobj = (JSONArray) metajson.get("flags"); org.bukkit.inventory.ItemFlag[] flaglist = new org.bukkit.inventory.ItemFlag[flagobj.size()]; int ai = 0; for (Object flag : flagobj.toArray()) { flaglist[ai] = org.bukkit.inventory.ItemFlag.valueOf((String) flag); ai++; } meta.addItemFlags(flaglist); } catch (ClassNotFoundException e) { } } item.setItemMeta(meta); } return item; }
From source file:tree.handler.TitleHandler.java
/** * Get a JPG representing a tree of an MVD * @param request the servlet request//from w w w .jav a 2s . c om * @param response the servlet response * @param urn the docID, stripped of its prefix * @throws TreeException */ public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws TreeException { String docid = request.getParameter(Params.DOCID); try { if (docid != null) { JSONObject jObj = doGetMetadata(docid); String title = "no title"; if (jObj != null && jObj.containsKey(JSONKeys.TITLE)) title = (String) jObj.get(JSONKeys.TITLE); response.setContentType("text/plain"); response.getWriter().write(title); } else throw new Exception(docid + " not found"); } catch (Exception e) { throw new TreeException(e); } }
From source file:uk.ac.ebi.arrayexpress.servlets.GenomeSpaceUploadServlet.java
private Integer getDirectoryInfo(String path, DirectoryInfo directoryInfo, String gsToken) throws IOException { GetMethod get = new GetMethod( GS_DM_ROOT_URL + ("/".equals(path) ? GS_HOME_DIRECTORY : GS_ROOT_DIRECTORY + path)); get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); get.setRequestHeader("Cookie", "gs-token=" + gsToken); get.setRequestHeader("Accept", "application/json"); get.setRequestHeader("Content-Type", "application/json"); JSONParser jsonParser = new JSONParser(); Integer statusCode = null;//from ww w. j ava 2 s . co m try { statusCode = httpClient.executeMethod(get); if (HttpServletResponse.SC_OK == statusCode) { try (InputStream is = get.getResponseBodyAsStream()) { JSONObject dirInfo = (JSONObject) jsonParser .parse(new BufferedReader(new InputStreamReader(is))); directoryInfo.setInfo((null != dirInfo && dirInfo.containsKey("directory")) ? (JSONObject) dirInfo.get("directory") : null); } catch (ParseException x) { logger.error("Unable to parse JSON response:", x); } } else { logger.error("Unable to get directory info, status code [{}]", statusCode); } } catch (HttpException x) { logger.error("Caught an exception:", x); } finally { get.releaseConnection(); } return statusCode; }
From source file:uk.ac.jorum.integration.matchers.ContainsJSONKey.java
private boolean runMatch(JSONObject item) { isKeyPresent = item.containsKey(key); if (!isKeyPresent) { return false; }/* w w w .ja v a 2s . com*/ if (expectedValue == null) { return true; } T actualValue = (T) item.get(key); if (actualValue == null) { return (expectedValue == null); } return actualValue.equals(expectedValue); }
From source file:uk.ac.jorum.integration.matchers.MatchJSONArray.java
@Override public boolean matchesSafely(JSONObject item) { run = true;/*from w w w. j a v a2s .co m*/ isKeyPresent = item.containsKey(key); if (!isKeyPresent) { return false; } array = (JSONArray) item.get(key); if (array.size() == 0 && matchers.size() == 0) { return true; } else if (array.size() == 0 && matchers.size() > 0) { return false; } else if (array.size() > 0 && matchers.size() == 0) { return false; } anyOfmatcher = anyOf((Iterable) matchers); for (Object obj : array) { if (!anyOfmatcher.matches((T) obj)) { return false; } } return true; }